SafeStackColoring.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. //===- SafeStackColoring.cpp - SafeStack frame coloring -------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "SafeStackColoring.h"
  10. #include "llvm/ADT/BitVector.h"
  11. #include "llvm/ADT/DenseMap.h"
  12. #include "llvm/ADT/DepthFirstIterator.h"
  13. #include "llvm/ADT/SmallVector.h"
  14. #include "llvm/Config/llvm-config.h"
  15. #include "llvm/IR/BasicBlock.h"
  16. #include "llvm/IR/CFG.h"
  17. #include "llvm/IR/Instruction.h"
  18. #include "llvm/IR/Instructions.h"
  19. #include "llvm/IR/IntrinsicInst.h"
  20. #include "llvm/IR/Intrinsics.h"
  21. #include "llvm/IR/User.h"
  22. #include "llvm/Support/Casting.h"
  23. #include "llvm/Support/CommandLine.h"
  24. #include "llvm/Support/Compiler.h"
  25. #include "llvm/Support/Debug.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <cassert>
  28. #include <tuple>
  29. #include <utility>
  30. using namespace llvm;
  31. using namespace llvm::safestack;
  32. #define DEBUG_TYPE "safestackcoloring"
  33. // Disabled by default due to PR32143.
  34. static cl::opt<bool> ClColoring("safe-stack-coloring",
  35. cl::desc("enable safe stack coloring"),
  36. cl::Hidden, cl::init(false));
  37. const StackColoring::LiveRange &StackColoring::getLiveRange(AllocaInst *AI) {
  38. const auto IT = AllocaNumbering.find(AI);
  39. assert(IT != AllocaNumbering.end());
  40. return LiveRanges[IT->second];
  41. }
  42. bool StackColoring::readMarker(Instruction *I, bool *IsStart) {
  43. auto *II = dyn_cast<IntrinsicInst>(I);
  44. if (!II || (II->getIntrinsicID() != Intrinsic::lifetime_start &&
  45. II->getIntrinsicID() != Intrinsic::lifetime_end))
  46. return false;
  47. *IsStart = II->getIntrinsicID() == Intrinsic::lifetime_start;
  48. return true;
  49. }
  50. void StackColoring::removeAllMarkers() {
  51. for (auto *I : Markers) {
  52. auto *Op = dyn_cast<Instruction>(I->getOperand(1));
  53. I->eraseFromParent();
  54. // Remove the operand bitcast, too, if it has no more uses left.
  55. if (Op && Op->use_empty())
  56. Op->eraseFromParent();
  57. }
  58. }
  59. void StackColoring::collectMarkers() {
  60. InterestingAllocas.resize(NumAllocas);
  61. DenseMap<BasicBlock *, SmallDenseMap<Instruction *, Marker>> BBMarkerSet;
  62. // Compute the set of start/end markers per basic block.
  63. for (unsigned AllocaNo = 0; AllocaNo < NumAllocas; ++AllocaNo) {
  64. AllocaInst *AI = Allocas[AllocaNo];
  65. SmallVector<Instruction *, 8> WorkList;
  66. WorkList.push_back(AI);
  67. while (!WorkList.empty()) {
  68. Instruction *I = WorkList.pop_back_val();
  69. for (User *U : I->users()) {
  70. if (auto *BI = dyn_cast<BitCastInst>(U)) {
  71. WorkList.push_back(BI);
  72. continue;
  73. }
  74. auto *UI = dyn_cast<Instruction>(U);
  75. if (!UI)
  76. continue;
  77. bool IsStart;
  78. if (!readMarker(UI, &IsStart))
  79. continue;
  80. if (IsStart)
  81. InterestingAllocas.set(AllocaNo);
  82. BBMarkerSet[UI->getParent()][UI] = {AllocaNo, IsStart};
  83. Markers.push_back(UI);
  84. }
  85. }
  86. }
  87. // Compute instruction numbering. Only the following instructions are
  88. // considered:
  89. // * Basic block entries
  90. // * Lifetime markers
  91. // For each basic block, compute
  92. // * the list of markers in the instruction order
  93. // * the sets of allocas whose lifetime starts or ends in this BB
  94. DEBUG(dbgs() << "Instructions:\n");
  95. unsigned InstNo = 0;
  96. for (BasicBlock *BB : depth_first(&F)) {
  97. DEBUG(dbgs() << " " << InstNo << ": BB " << BB->getName() << "\n");
  98. unsigned BBStart = InstNo++;
  99. BlockLifetimeInfo &BlockInfo = BlockLiveness[BB];
  100. BlockInfo.Begin.resize(NumAllocas);
  101. BlockInfo.End.resize(NumAllocas);
  102. BlockInfo.LiveIn.resize(NumAllocas);
  103. BlockInfo.LiveOut.resize(NumAllocas);
  104. auto &BlockMarkerSet = BBMarkerSet[BB];
  105. if (BlockMarkerSet.empty()) {
  106. unsigned BBEnd = InstNo;
  107. BlockInstRange[BB] = std::make_pair(BBStart, BBEnd);
  108. continue;
  109. }
  110. auto ProcessMarker = [&](Instruction *I, const Marker &M) {
  111. DEBUG(dbgs() << " " << InstNo << ": "
  112. << (M.IsStart ? "start " : "end ") << M.AllocaNo << ", "
  113. << *I << "\n");
  114. BBMarkers[BB].push_back({InstNo, M});
  115. InstructionNumbering[I] = InstNo++;
  116. if (M.IsStart) {
  117. if (BlockInfo.End.test(M.AllocaNo))
  118. BlockInfo.End.reset(M.AllocaNo);
  119. BlockInfo.Begin.set(M.AllocaNo);
  120. } else {
  121. if (BlockInfo.Begin.test(M.AllocaNo))
  122. BlockInfo.Begin.reset(M.AllocaNo);
  123. BlockInfo.End.set(M.AllocaNo);
  124. }
  125. };
  126. if (BlockMarkerSet.size() == 1) {
  127. ProcessMarker(BlockMarkerSet.begin()->getFirst(),
  128. BlockMarkerSet.begin()->getSecond());
  129. } else {
  130. // Scan the BB to determine the marker order.
  131. for (Instruction &I : *BB) {
  132. auto It = BlockMarkerSet.find(&I);
  133. if (It == BlockMarkerSet.end())
  134. continue;
  135. ProcessMarker(&I, It->getSecond());
  136. }
  137. }
  138. unsigned BBEnd = InstNo;
  139. BlockInstRange[BB] = std::make_pair(BBStart, BBEnd);
  140. }
  141. NumInst = InstNo;
  142. }
  143. void StackColoring::calculateLocalLiveness() {
  144. bool changed = true;
  145. while (changed) {
  146. changed = false;
  147. for (BasicBlock *BB : depth_first(&F)) {
  148. BlockLifetimeInfo &BlockInfo = BlockLiveness[BB];
  149. // Compute LiveIn by unioning together the LiveOut sets of all preds.
  150. BitVector LocalLiveIn;
  151. for (auto *PredBB : predecessors(BB)) {
  152. LivenessMap::const_iterator I = BlockLiveness.find(PredBB);
  153. assert(I != BlockLiveness.end() && "Predecessor not found");
  154. LocalLiveIn |= I->second.LiveOut;
  155. }
  156. // Compute LiveOut by subtracting out lifetimes that end in this
  157. // block, then adding in lifetimes that begin in this block. If
  158. // we have both BEGIN and END markers in the same basic block
  159. // then we know that the BEGIN marker comes after the END,
  160. // because we already handle the case where the BEGIN comes
  161. // before the END when collecting the markers (and building the
  162. // BEGIN/END vectors).
  163. BitVector LocalLiveOut = LocalLiveIn;
  164. LocalLiveOut.reset(BlockInfo.End);
  165. LocalLiveOut |= BlockInfo.Begin;
  166. // Update block LiveIn set, noting whether it has changed.
  167. if (LocalLiveIn.test(BlockInfo.LiveIn)) {
  168. changed = true;
  169. BlockInfo.LiveIn |= LocalLiveIn;
  170. }
  171. // Update block LiveOut set, noting whether it has changed.
  172. if (LocalLiveOut.test(BlockInfo.LiveOut)) {
  173. changed = true;
  174. BlockInfo.LiveOut |= LocalLiveOut;
  175. }
  176. }
  177. } // while changed.
  178. }
  179. void StackColoring::calculateLiveIntervals() {
  180. for (auto IT : BlockLiveness) {
  181. BasicBlock *BB = IT.getFirst();
  182. BlockLifetimeInfo &BlockInfo = IT.getSecond();
  183. unsigned BBStart, BBEnd;
  184. std::tie(BBStart, BBEnd) = BlockInstRange[BB];
  185. BitVector Started, Ended;
  186. Started.resize(NumAllocas);
  187. Ended.resize(NumAllocas);
  188. SmallVector<unsigned, 8> Start;
  189. Start.resize(NumAllocas);
  190. // LiveIn ranges start at the first instruction.
  191. for (unsigned AllocaNo = 0; AllocaNo < NumAllocas; ++AllocaNo) {
  192. if (BlockInfo.LiveIn.test(AllocaNo)) {
  193. Started.set(AllocaNo);
  194. Start[AllocaNo] = BBStart;
  195. }
  196. }
  197. for (auto &It : BBMarkers[BB]) {
  198. unsigned InstNo = It.first;
  199. bool IsStart = It.second.IsStart;
  200. unsigned AllocaNo = It.second.AllocaNo;
  201. if (IsStart) {
  202. assert(!Started.test(AllocaNo) || Start[AllocaNo] == BBStart);
  203. if (!Started.test(AllocaNo)) {
  204. Started.set(AllocaNo);
  205. Ended.reset(AllocaNo);
  206. Start[AllocaNo] = InstNo;
  207. }
  208. } else {
  209. assert(!Ended.test(AllocaNo));
  210. if (Started.test(AllocaNo)) {
  211. LiveRanges[AllocaNo].AddRange(Start[AllocaNo], InstNo);
  212. Started.reset(AllocaNo);
  213. }
  214. Ended.set(AllocaNo);
  215. }
  216. }
  217. for (unsigned AllocaNo = 0; AllocaNo < NumAllocas; ++AllocaNo)
  218. if (Started.test(AllocaNo))
  219. LiveRanges[AllocaNo].AddRange(Start[AllocaNo], BBEnd);
  220. }
  221. }
  222. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  223. LLVM_DUMP_METHOD void StackColoring::dumpAllocas() {
  224. dbgs() << "Allocas:\n";
  225. for (unsigned AllocaNo = 0; AllocaNo < NumAllocas; ++AllocaNo)
  226. dbgs() << " " << AllocaNo << ": " << *Allocas[AllocaNo] << "\n";
  227. }
  228. LLVM_DUMP_METHOD void StackColoring::dumpBlockLiveness() {
  229. dbgs() << "Block liveness:\n";
  230. for (auto IT : BlockLiveness) {
  231. BasicBlock *BB = IT.getFirst();
  232. BlockLifetimeInfo &BlockInfo = BlockLiveness[BB];
  233. auto BlockRange = BlockInstRange[BB];
  234. dbgs() << " BB [" << BlockRange.first << ", " << BlockRange.second
  235. << "): begin " << BlockInfo.Begin << ", end " << BlockInfo.End
  236. << ", livein " << BlockInfo.LiveIn << ", liveout "
  237. << BlockInfo.LiveOut << "\n";
  238. }
  239. }
  240. LLVM_DUMP_METHOD void StackColoring::dumpLiveRanges() {
  241. dbgs() << "Alloca liveness:\n";
  242. for (unsigned AllocaNo = 0; AllocaNo < NumAllocas; ++AllocaNo) {
  243. LiveRange &Range = LiveRanges[AllocaNo];
  244. dbgs() << " " << AllocaNo << ": " << Range << "\n";
  245. }
  246. }
  247. #endif
  248. void StackColoring::run() {
  249. DEBUG(dumpAllocas());
  250. for (unsigned I = 0; I < NumAllocas; ++I)
  251. AllocaNumbering[Allocas[I]] = I;
  252. LiveRanges.resize(NumAllocas);
  253. collectMarkers();
  254. if (!ClColoring) {
  255. for (auto &R : LiveRanges) {
  256. R.SetMaximum(1);
  257. R.AddRange(0, 1);
  258. }
  259. return;
  260. }
  261. for (auto &R : LiveRanges)
  262. R.SetMaximum(NumInst);
  263. for (unsigned I = 0; I < NumAllocas; ++I)
  264. if (!InterestingAllocas.test(I))
  265. LiveRanges[I] = getFullLiveRange();
  266. calculateLocalLiveness();
  267. DEBUG(dumpBlockLiveness());
  268. calculateLiveIntervals();
  269. DEBUG(dumpLiveRanges());
  270. }