StackColoring.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. //===-- StackColoring.cpp -------------------------------------------------===//
  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. //
  10. // This pass implements the stack-coloring optimization that looks for
  11. // lifetime markers machine instructions (LIFESTART_BEGIN and LIFESTART_END),
  12. // which represent the possible lifetime of stack slots. It attempts to
  13. // merge disjoint stack slots and reduce the used stack space.
  14. // NOTE: This pass is not StackSlotColoring, which optimizes spill slots.
  15. //
  16. // TODO: In the future we plan to improve stack coloring in the following ways:
  17. // 1. Allow merging multiple small slots into a single larger slot at different
  18. // offsets.
  19. // 2. Merge this pass with StackSlotColoring and allow merging of allocas with
  20. // spill slots.
  21. //
  22. //===----------------------------------------------------------------------===//
  23. #include "llvm/ADT/BitVector.h"
  24. #include "llvm/ADT/DepthFirstIterator.h"
  25. #include "llvm/ADT/PostOrderIterator.h"
  26. #include "llvm/ADT/SetVector.h"
  27. #include "llvm/ADT/SmallPtrSet.h"
  28. #include "llvm/ADT/Statistic.h"
  29. #include "llvm/Analysis/ValueTracking.h"
  30. #include "llvm/CodeGen/LiveInterval.h"
  31. #include "llvm/CodeGen/MachineBasicBlock.h"
  32. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  33. #include "llvm/CodeGen/MachineDominators.h"
  34. #include "llvm/CodeGen/MachineFrameInfo.h"
  35. #include "llvm/CodeGen/MachineFunctionPass.h"
  36. #include "llvm/CodeGen/MachineLoopInfo.h"
  37. #include "llvm/CodeGen/MachineMemOperand.h"
  38. #include "llvm/CodeGen/MachineModuleInfo.h"
  39. #include "llvm/CodeGen/MachineRegisterInfo.h"
  40. #include "llvm/CodeGen/Passes.h"
  41. #include "llvm/CodeGen/PseudoSourceValue.h"
  42. #include "llvm/CodeGen/SlotIndexes.h"
  43. #include "llvm/CodeGen/StackProtector.h"
  44. #include "llvm/CodeGen/WinEHFuncInfo.h"
  45. #include "llvm/IR/DebugInfo.h"
  46. #include "llvm/IR/Dominators.h"
  47. #include "llvm/IR/Function.h"
  48. #include "llvm/IR/Instructions.h"
  49. #include "llvm/IR/IntrinsicInst.h"
  50. #include "llvm/IR/Module.h"
  51. #include "llvm/Support/CommandLine.h"
  52. #include "llvm/Support/Debug.h"
  53. #include "llvm/Support/raw_ostream.h"
  54. #include "llvm/Target/TargetInstrInfo.h"
  55. #include "llvm/Target/TargetRegisterInfo.h"
  56. using namespace llvm;
  57. #define DEBUG_TYPE "stackcoloring"
  58. static cl::opt<bool>
  59. DisableColoring("no-stack-coloring",
  60. cl::init(false), cl::Hidden,
  61. cl::desc("Disable stack coloring"));
  62. /// The user may write code that uses allocas outside of the declared lifetime
  63. /// zone. This can happen when the user returns a reference to a local
  64. /// data-structure. We can detect these cases and decide not to optimize the
  65. /// code. If this flag is enabled, we try to save the user.
  66. static cl::opt<bool>
  67. ProtectFromEscapedAllocas("protect-from-escaped-allocas",
  68. cl::init(false), cl::Hidden,
  69. cl::desc("Do not optimize lifetime zones that "
  70. "are broken"));
  71. STATISTIC(NumMarkerSeen, "Number of lifetime markers found.");
  72. STATISTIC(StackSpaceSaved, "Number of bytes saved due to merging slots.");
  73. STATISTIC(StackSlotMerged, "Number of stack slot merged.");
  74. STATISTIC(EscapedAllocas, "Number of allocas that escaped the lifetime region");
  75. //===----------------------------------------------------------------------===//
  76. // StackColoring Pass
  77. //===----------------------------------------------------------------------===//
  78. namespace {
  79. /// StackColoring - A machine pass for merging disjoint stack allocations,
  80. /// marked by the LIFETIME_START and LIFETIME_END pseudo instructions.
  81. class StackColoring : public MachineFunctionPass {
  82. MachineFrameInfo *MFI;
  83. MachineFunction *MF;
  84. /// A class representing liveness information for a single basic block.
  85. /// Each bit in the BitVector represents the liveness property
  86. /// for a different stack slot.
  87. struct BlockLifetimeInfo {
  88. /// Which slots BEGINs in each basic block.
  89. BitVector Begin;
  90. /// Which slots ENDs in each basic block.
  91. BitVector End;
  92. /// Which slots are marked as LIVE_IN, coming into each basic block.
  93. BitVector LiveIn;
  94. /// Which slots are marked as LIVE_OUT, coming out of each basic block.
  95. BitVector LiveOut;
  96. };
  97. /// Maps active slots (per bit) for each basic block.
  98. typedef DenseMap<const MachineBasicBlock*, BlockLifetimeInfo> LivenessMap;
  99. LivenessMap BlockLiveness;
  100. /// Maps serial numbers to basic blocks.
  101. DenseMap<const MachineBasicBlock*, int> BasicBlocks;
  102. /// Maps basic blocks to a serial number.
  103. SmallVector<const MachineBasicBlock*, 8> BasicBlockNumbering;
  104. /// Maps liveness intervals for each slot.
  105. SmallVector<std::unique_ptr<LiveInterval>, 16> Intervals;
  106. /// VNInfo is used for the construction of LiveIntervals.
  107. VNInfo::Allocator VNInfoAllocator;
  108. /// SlotIndex analysis object.
  109. SlotIndexes *Indexes;
  110. /// The stack protector object.
  111. StackProtector *SP;
  112. /// The list of lifetime markers found. These markers are to be removed
  113. /// once the coloring is done.
  114. SmallVector<MachineInstr*, 8> Markers;
  115. public:
  116. static char ID;
  117. StackColoring() : MachineFunctionPass(ID) {
  118. initializeStackColoringPass(*PassRegistry::getPassRegistry());
  119. }
  120. void getAnalysisUsage(AnalysisUsage &AU) const override;
  121. bool runOnMachineFunction(MachineFunction &MF) override;
  122. private:
  123. /// Debug.
  124. void dump() const;
  125. /// Removes all of the lifetime marker instructions from the function.
  126. /// \returns true if any markers were removed.
  127. bool removeAllMarkers();
  128. /// Scan the machine function and find all of the lifetime markers.
  129. /// Record the findings in the BEGIN and END vectors.
  130. /// \returns the number of markers found.
  131. unsigned collectMarkers(unsigned NumSlot);
  132. /// Perform the dataflow calculation and calculate the lifetime for each of
  133. /// the slots, based on the BEGIN/END vectors. Set the LifetimeLIVE_IN and
  134. /// LifetimeLIVE_OUT maps that represent which stack slots are live coming
  135. /// in and out blocks.
  136. void calculateLocalLiveness();
  137. /// Construct the LiveIntervals for the slots.
  138. void calculateLiveIntervals(unsigned NumSlots);
  139. /// Go over the machine function and change instructions which use stack
  140. /// slots to use the joint slots.
  141. void remapInstructions(DenseMap<int, int> &SlotRemap);
  142. /// The input program may contain instructions which are not inside lifetime
  143. /// markers. This can happen due to a bug in the compiler or due to a bug in
  144. /// user code (for example, returning a reference to a local variable).
  145. /// This procedure checks all of the instructions in the function and
  146. /// invalidates lifetime ranges which do not contain all of the instructions
  147. /// which access that frame slot.
  148. void removeInvalidSlotRanges();
  149. /// Map entries which point to other entries to their destination.
  150. /// A->B->C becomes A->C.
  151. void expungeSlotMap(DenseMap<int, int> &SlotRemap, unsigned NumSlots);
  152. };
  153. } // end anonymous namespace
  154. char StackColoring::ID = 0;
  155. char &llvm::StackColoringID = StackColoring::ID;
  156. INITIALIZE_PASS_BEGIN(StackColoring,
  157. "stack-coloring", "Merge disjoint stack slots", false, false)
  158. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  159. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  160. INITIALIZE_PASS_DEPENDENCY(StackProtector)
  161. INITIALIZE_PASS_END(StackColoring,
  162. "stack-coloring", "Merge disjoint stack slots", false, false)
  163. void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const {
  164. AU.addRequired<MachineDominatorTree>();
  165. AU.addPreserved<MachineDominatorTree>();
  166. AU.addRequired<SlotIndexes>();
  167. AU.addRequired<StackProtector>();
  168. MachineFunctionPass::getAnalysisUsage(AU);
  169. }
  170. LLVM_DUMP_METHOD void StackColoring::dump() const {
  171. for (MachineBasicBlock *MBB : depth_first(MF)) {
  172. DEBUG(dbgs() << "Inspecting block #" << BasicBlocks.lookup(MBB) << " ["
  173. << MBB->getName() << "]\n");
  174. LivenessMap::const_iterator BI = BlockLiveness.find(MBB);
  175. assert(BI != BlockLiveness.end() && "Block not found");
  176. const BlockLifetimeInfo &BlockInfo = BI->second;
  177. DEBUG(dbgs()<<"BEGIN : {");
  178. for (unsigned i=0; i < BlockInfo.Begin.size(); ++i)
  179. DEBUG(dbgs()<<BlockInfo.Begin.test(i)<<" ");
  180. DEBUG(dbgs()<<"}\n");
  181. DEBUG(dbgs()<<"END : {");
  182. for (unsigned i=0; i < BlockInfo.End.size(); ++i)
  183. DEBUG(dbgs()<<BlockInfo.End.test(i)<<" ");
  184. DEBUG(dbgs()<<"}\n");
  185. DEBUG(dbgs()<<"LIVE_IN: {");
  186. for (unsigned i=0; i < BlockInfo.LiveIn.size(); ++i)
  187. DEBUG(dbgs()<<BlockInfo.LiveIn.test(i)<<" ");
  188. DEBUG(dbgs()<<"}\n");
  189. DEBUG(dbgs()<<"LIVEOUT: {");
  190. for (unsigned i=0; i < BlockInfo.LiveOut.size(); ++i)
  191. DEBUG(dbgs()<<BlockInfo.LiveOut.test(i)<<" ");
  192. DEBUG(dbgs()<<"}\n");
  193. }
  194. }
  195. unsigned StackColoring::collectMarkers(unsigned NumSlot) {
  196. unsigned MarkersFound = 0;
  197. // Scan the function to find all lifetime markers.
  198. // NOTE: We use a reverse-post-order iteration to ensure that we obtain a
  199. // deterministic numbering, and because we'll need a post-order iteration
  200. // later for solving the liveness dataflow problem.
  201. for (MachineBasicBlock *MBB : depth_first(MF)) {
  202. // Assign a serial number to this basic block.
  203. BasicBlocks[MBB] = BasicBlockNumbering.size();
  204. BasicBlockNumbering.push_back(MBB);
  205. // Keep a reference to avoid repeated lookups.
  206. BlockLifetimeInfo &BlockInfo = BlockLiveness[MBB];
  207. BlockInfo.Begin.resize(NumSlot);
  208. BlockInfo.End.resize(NumSlot);
  209. for (MachineInstr &MI : *MBB) {
  210. if (MI.getOpcode() != TargetOpcode::LIFETIME_START &&
  211. MI.getOpcode() != TargetOpcode::LIFETIME_END)
  212. continue;
  213. bool IsStart = MI.getOpcode() == TargetOpcode::LIFETIME_START;
  214. const MachineOperand &MO = MI.getOperand(0);
  215. int Slot = MO.getIndex();
  216. if (Slot < 0)
  217. continue;
  218. Markers.push_back(&MI);
  219. MarkersFound++;
  220. const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
  221. if (Allocation) {
  222. DEBUG(dbgs()<<"Found a lifetime marker for slot #"<<Slot<<
  223. " with allocation: "<< Allocation->getName()<<"\n");
  224. }
  225. if (IsStart) {
  226. BlockInfo.Begin.set(Slot);
  227. } else {
  228. if (BlockInfo.Begin.test(Slot)) {
  229. // Allocas that start and end within a single block are handled
  230. // specially when computing the LiveIntervals to avoid pessimizing
  231. // the liveness propagation.
  232. BlockInfo.Begin.reset(Slot);
  233. } else {
  234. BlockInfo.End.set(Slot);
  235. }
  236. }
  237. }
  238. }
  239. // Update statistics.
  240. NumMarkerSeen += MarkersFound;
  241. return MarkersFound;
  242. }
  243. void StackColoring::calculateLocalLiveness() {
  244. // Perform a standard reverse dataflow computation to solve for
  245. // global liveness. The BEGIN set here is equivalent to KILL in the standard
  246. // formulation, and END is equivalent to GEN. The result of this computation
  247. // is a map from blocks to bitvectors where the bitvectors represent which
  248. // allocas are live in/out of that block.
  249. SmallPtrSet<const MachineBasicBlock*, 8> BBSet(BasicBlockNumbering.begin(),
  250. BasicBlockNumbering.end());
  251. unsigned NumSSMIters = 0;
  252. bool changed = true;
  253. while (changed) {
  254. changed = false;
  255. ++NumSSMIters;
  256. SmallPtrSet<const MachineBasicBlock*, 8> NextBBSet;
  257. for (const MachineBasicBlock *BB : BasicBlockNumbering) {
  258. if (!BBSet.count(BB)) continue;
  259. // Use an iterator to avoid repeated lookups.
  260. LivenessMap::iterator BI = BlockLiveness.find(BB);
  261. assert(BI != BlockLiveness.end() && "Block not found");
  262. BlockLifetimeInfo &BlockInfo = BI->second;
  263. BitVector LocalLiveIn;
  264. BitVector LocalLiveOut;
  265. // Forward propagation from begins to ends.
  266. for (MachineBasicBlock::const_pred_iterator PI = BB->pred_begin(),
  267. PE = BB->pred_end(); PI != PE; ++PI) {
  268. LivenessMap::const_iterator I = BlockLiveness.find(*PI);
  269. assert(I != BlockLiveness.end() && "Predecessor not found");
  270. LocalLiveIn |= I->second.LiveOut;
  271. }
  272. LocalLiveIn |= BlockInfo.End;
  273. LocalLiveIn.reset(BlockInfo.Begin);
  274. // Reverse propagation from ends to begins.
  275. for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
  276. SE = BB->succ_end(); SI != SE; ++SI) {
  277. LivenessMap::const_iterator I = BlockLiveness.find(*SI);
  278. assert(I != BlockLiveness.end() && "Successor not found");
  279. LocalLiveOut |= I->second.LiveIn;
  280. }
  281. LocalLiveOut |= BlockInfo.Begin;
  282. LocalLiveOut.reset(BlockInfo.End);
  283. LocalLiveIn |= LocalLiveOut;
  284. LocalLiveOut |= LocalLiveIn;
  285. // After adopting the live bits, we need to turn-off the bits which
  286. // are de-activated in this block.
  287. LocalLiveOut.reset(BlockInfo.End);
  288. LocalLiveIn.reset(BlockInfo.Begin);
  289. // If we have both BEGIN and END markers in the same basic block then
  290. // we know that the BEGIN marker comes after the END, because we already
  291. // handle the case where the BEGIN comes before the END when collecting
  292. // the markers (and building the BEGIN/END vectore).
  293. // Want to enable the LIVE_IN and LIVE_OUT of slots that have both
  294. // BEGIN and END because it means that the value lives before and after
  295. // this basic block.
  296. BitVector LocalEndBegin = BlockInfo.End;
  297. LocalEndBegin &= BlockInfo.Begin;
  298. LocalLiveIn |= LocalEndBegin;
  299. LocalLiveOut |= LocalEndBegin;
  300. if (LocalLiveIn.test(BlockInfo.LiveIn)) {
  301. changed = true;
  302. BlockInfo.LiveIn |= LocalLiveIn;
  303. NextBBSet.insert(BB->pred_begin(), BB->pred_end());
  304. }
  305. if (LocalLiveOut.test(BlockInfo.LiveOut)) {
  306. changed = true;
  307. BlockInfo.LiveOut |= LocalLiveOut;
  308. NextBBSet.insert(BB->succ_begin(), BB->succ_end());
  309. }
  310. }
  311. BBSet = std::move(NextBBSet);
  312. }// while changed.
  313. }
  314. void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
  315. SmallVector<SlotIndex, 16> Starts;
  316. SmallVector<SlotIndex, 16> Finishes;
  317. // For each block, find which slots are active within this block
  318. // and update the live intervals.
  319. for (const MachineBasicBlock &MBB : *MF) {
  320. Starts.clear();
  321. Starts.resize(NumSlots);
  322. Finishes.clear();
  323. Finishes.resize(NumSlots);
  324. // Create the interval for the basic blocks with lifetime markers in them.
  325. for (const MachineInstr *MI : Markers) {
  326. if (MI->getParent() != &MBB)
  327. continue;
  328. assert((MI->getOpcode() == TargetOpcode::LIFETIME_START ||
  329. MI->getOpcode() == TargetOpcode::LIFETIME_END) &&
  330. "Invalid Lifetime marker");
  331. bool IsStart = MI->getOpcode() == TargetOpcode::LIFETIME_START;
  332. const MachineOperand &Mo = MI->getOperand(0);
  333. int Slot = Mo.getIndex();
  334. if (Slot < 0)
  335. continue;
  336. SlotIndex ThisIndex = Indexes->getInstructionIndex(*MI);
  337. if (IsStart) {
  338. if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex)
  339. Starts[Slot] = ThisIndex;
  340. } else {
  341. if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex)
  342. Finishes[Slot] = ThisIndex;
  343. }
  344. }
  345. // Create the interval of the blocks that we previously found to be 'alive'.
  346. BlockLifetimeInfo &MBBLiveness = BlockLiveness[&MBB];
  347. for (int pos = MBBLiveness.LiveIn.find_first(); pos != -1;
  348. pos = MBBLiveness.LiveIn.find_next(pos)) {
  349. Starts[pos] = Indexes->getMBBStartIdx(&MBB);
  350. }
  351. for (int pos = MBBLiveness.LiveOut.find_first(); pos != -1;
  352. pos = MBBLiveness.LiveOut.find_next(pos)) {
  353. Finishes[pos] = Indexes->getMBBEndIdx(&MBB);
  354. }
  355. for (unsigned i = 0; i < NumSlots; ++i) {
  356. assert(Starts[i].isValid() == Finishes[i].isValid() && "Unmatched range");
  357. if (!Starts[i].isValid())
  358. continue;
  359. assert(Starts[i] && Finishes[i] && "Invalid interval");
  360. VNInfo *ValNum = Intervals[i]->getValNumInfo(0);
  361. SlotIndex S = Starts[i];
  362. SlotIndex F = Finishes[i];
  363. if (S < F) {
  364. // We have a single consecutive region.
  365. Intervals[i]->addSegment(LiveInterval::Segment(S, F, ValNum));
  366. } else {
  367. // We have two non-consecutive regions. This happens when
  368. // LIFETIME_START appears after the LIFETIME_END marker.
  369. SlotIndex NewStart = Indexes->getMBBStartIdx(&MBB);
  370. SlotIndex NewFin = Indexes->getMBBEndIdx(&MBB);
  371. Intervals[i]->addSegment(LiveInterval::Segment(NewStart, F, ValNum));
  372. Intervals[i]->addSegment(LiveInterval::Segment(S, NewFin, ValNum));
  373. }
  374. }
  375. }
  376. }
  377. bool StackColoring::removeAllMarkers() {
  378. unsigned Count = 0;
  379. for (MachineInstr *MI : Markers) {
  380. MI->eraseFromParent();
  381. Count++;
  382. }
  383. Markers.clear();
  384. DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n");
  385. return Count;
  386. }
  387. void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
  388. unsigned FixedInstr = 0;
  389. unsigned FixedMemOp = 0;
  390. unsigned FixedDbg = 0;
  391. MachineModuleInfo *MMI = &MF->getMMI();
  392. // Remap debug information that refers to stack slots.
  393. for (auto &VI : MMI->getVariableDbgInfo()) {
  394. if (!VI.Var)
  395. continue;
  396. if (SlotRemap.count(VI.Slot)) {
  397. DEBUG(dbgs() << "Remapping debug info for ["
  398. << cast<DILocalVariable>(VI.Var)->getName() << "].\n");
  399. VI.Slot = SlotRemap[VI.Slot];
  400. FixedDbg++;
  401. }
  402. }
  403. // Keep a list of *allocas* which need to be remapped.
  404. DenseMap<const AllocaInst*, const AllocaInst*> Allocas;
  405. for (const std::pair<int, int> &SI : SlotRemap) {
  406. const AllocaInst *From = MFI->getObjectAllocation(SI.first);
  407. const AllocaInst *To = MFI->getObjectAllocation(SI.second);
  408. assert(To && From && "Invalid allocation object");
  409. Allocas[From] = To;
  410. // AA might be used later for instruction scheduling, and we need it to be
  411. // able to deduce the correct aliasing releationships between pointers
  412. // derived from the alloca being remapped and the target of that remapping.
  413. // The only safe way, without directly informing AA about the remapping
  414. // somehow, is to directly update the IR to reflect the change being made
  415. // here.
  416. Instruction *Inst = const_cast<AllocaInst *>(To);
  417. if (From->getType() != To->getType()) {
  418. BitCastInst *Cast = new BitCastInst(Inst, From->getType());
  419. Cast->insertAfter(Inst);
  420. Inst = Cast;
  421. }
  422. // Allow the stack protector to adjust its value map to account for the
  423. // upcoming replacement.
  424. SP->adjustForColoring(From, To);
  425. // The new alloca might not be valid in a llvm.dbg.declare for this
  426. // variable, so undef out the use to make the verifier happy.
  427. AllocaInst *FromAI = const_cast<AllocaInst *>(From);
  428. if (FromAI->isUsedByMetadata())
  429. ValueAsMetadata::handleRAUW(FromAI, UndefValue::get(FromAI->getType()));
  430. for (auto &Use : FromAI->uses()) {
  431. if (BitCastInst *BCI = dyn_cast<BitCastInst>(Use.get()))
  432. if (BCI->isUsedByMetadata())
  433. ValueAsMetadata::handleRAUW(BCI, UndefValue::get(BCI->getType()));
  434. }
  435. // Note that this will not replace uses in MMOs (which we'll update below),
  436. // or anywhere else (which is why we won't delete the original
  437. // instruction).
  438. FromAI->replaceAllUsesWith(Inst);
  439. }
  440. // Remap all instructions to the new stack slots.
  441. for (MachineBasicBlock &BB : *MF)
  442. for (MachineInstr &I : BB) {
  443. // Skip lifetime markers. We'll remove them soon.
  444. if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
  445. I.getOpcode() == TargetOpcode::LIFETIME_END)
  446. continue;
  447. // Update the MachineMemOperand to use the new alloca.
  448. for (MachineMemOperand *MMO : I.memoperands()) {
  449. // FIXME: In order to enable the use of TBAA when using AA in CodeGen,
  450. // we'll also need to update the TBAA nodes in MMOs with values
  451. // derived from the merged allocas. When doing this, we'll need to use
  452. // the same variant of GetUnderlyingObjects that is used by the
  453. // instruction scheduler (that can look through ptrtoint/inttoptr
  454. // pairs).
  455. // We've replaced IR-level uses of the remapped allocas, so we only
  456. // need to replace direct uses here.
  457. const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(MMO->getValue());
  458. if (!AI)
  459. continue;
  460. if (!Allocas.count(AI))
  461. continue;
  462. MMO->setValue(Allocas[AI]);
  463. FixedMemOp++;
  464. }
  465. // Update all of the machine instruction operands.
  466. for (MachineOperand &MO : I.operands()) {
  467. if (!MO.isFI())
  468. continue;
  469. int FromSlot = MO.getIndex();
  470. // Don't touch arguments.
  471. if (FromSlot<0)
  472. continue;
  473. // Only look at mapped slots.
  474. if (!SlotRemap.count(FromSlot))
  475. continue;
  476. // In a debug build, check that the instruction that we are modifying is
  477. // inside the expected live range. If the instruction is not inside
  478. // the calculated range then it means that the alloca usage moved
  479. // outside of the lifetime markers, or that the user has a bug.
  480. // NOTE: Alloca address calculations which happen outside the lifetime
  481. // zone are are okay, despite the fact that we don't have a good way
  482. // for validating all of the usages of the calculation.
  483. #ifndef NDEBUG
  484. bool TouchesMemory = I.mayLoad() || I.mayStore();
  485. // If we *don't* protect the user from escaped allocas, don't bother
  486. // validating the instructions.
  487. if (!I.isDebugValue() && TouchesMemory && ProtectFromEscapedAllocas) {
  488. SlotIndex Index = Indexes->getInstructionIndex(I);
  489. const LiveInterval *Interval = &*Intervals[FromSlot];
  490. assert(Interval->find(Index) != Interval->end() &&
  491. "Found instruction usage outside of live range.");
  492. }
  493. #endif
  494. // Fix the machine instructions.
  495. int ToSlot = SlotRemap[FromSlot];
  496. MO.setIndex(ToSlot);
  497. FixedInstr++;
  498. }
  499. }
  500. // Update the location of C++ catch objects for the MSVC personality routine.
  501. if (WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo())
  502. for (WinEHTryBlockMapEntry &TBME : EHInfo->TryBlockMap)
  503. for (WinEHHandlerType &H : TBME.HandlerArray)
  504. if (H.CatchObj.FrameIndex != INT_MAX &&
  505. SlotRemap.count(H.CatchObj.FrameIndex))
  506. H.CatchObj.FrameIndex = SlotRemap[H.CatchObj.FrameIndex];
  507. DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n");
  508. DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n");
  509. DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n");
  510. }
  511. void StackColoring::removeInvalidSlotRanges() {
  512. for (MachineBasicBlock &BB : *MF)
  513. for (MachineInstr &I : BB) {
  514. if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
  515. I.getOpcode() == TargetOpcode::LIFETIME_END || I.isDebugValue())
  516. continue;
  517. // Some intervals are suspicious! In some cases we find address
  518. // calculations outside of the lifetime zone, but not actual memory
  519. // read or write. Memory accesses outside of the lifetime zone are a clear
  520. // violation, but address calculations are okay. This can happen when
  521. // GEPs are hoisted outside of the lifetime zone.
  522. // So, in here we only check instructions which can read or write memory.
  523. if (!I.mayLoad() && !I.mayStore())
  524. continue;
  525. // Check all of the machine operands.
  526. for (const MachineOperand &MO : I.operands()) {
  527. if (!MO.isFI())
  528. continue;
  529. int Slot = MO.getIndex();
  530. if (Slot<0)
  531. continue;
  532. if (Intervals[Slot]->empty())
  533. continue;
  534. // Check that the used slot is inside the calculated lifetime range.
  535. // If it is not, warn about it and invalidate the range.
  536. LiveInterval *Interval = &*Intervals[Slot];
  537. SlotIndex Index = Indexes->getInstructionIndex(I);
  538. if (Interval->find(Index) == Interval->end()) {
  539. Interval->clear();
  540. DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n");
  541. EscapedAllocas++;
  542. }
  543. }
  544. }
  545. }
  546. void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
  547. unsigned NumSlots) {
  548. // Expunge slot remap map.
  549. for (unsigned i=0; i < NumSlots; ++i) {
  550. // If we are remapping i
  551. if (SlotRemap.count(i)) {
  552. int Target = SlotRemap[i];
  553. // As long as our target is mapped to something else, follow it.
  554. while (SlotRemap.count(Target)) {
  555. Target = SlotRemap[Target];
  556. SlotRemap[i] = Target;
  557. }
  558. }
  559. }
  560. }
  561. bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
  562. if (skipFunction(*Func.getFunction()))
  563. return false;
  564. DEBUG(dbgs() << "********** Stack Coloring **********\n"
  565. << "********** Function: "
  566. << ((const Value*)Func.getFunction())->getName() << '\n');
  567. MF = &Func;
  568. MFI = MF->getFrameInfo();
  569. Indexes = &getAnalysis<SlotIndexes>();
  570. SP = &getAnalysis<StackProtector>();
  571. BlockLiveness.clear();
  572. BasicBlocks.clear();
  573. BasicBlockNumbering.clear();
  574. Markers.clear();
  575. Intervals.clear();
  576. VNInfoAllocator.Reset();
  577. unsigned NumSlots = MFI->getObjectIndexEnd();
  578. // If there are no stack slots then there are no markers to remove.
  579. if (!NumSlots)
  580. return false;
  581. SmallVector<int, 8> SortedSlots;
  582. SortedSlots.reserve(NumSlots);
  583. Intervals.reserve(NumSlots);
  584. unsigned NumMarkers = collectMarkers(NumSlots);
  585. unsigned TotalSize = 0;
  586. DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n");
  587. DEBUG(dbgs()<<"Slot structure:\n");
  588. for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
  589. DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n");
  590. TotalSize += MFI->getObjectSize(i);
  591. }
  592. DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n");
  593. // Don't continue because there are not enough lifetime markers, or the
  594. // stack is too small, or we are told not to optimize the slots.
  595. if (NumMarkers < 2 || TotalSize < 16 || DisableColoring) {
  596. DEBUG(dbgs()<<"Will not try to merge slots.\n");
  597. return removeAllMarkers();
  598. }
  599. for (unsigned i=0; i < NumSlots; ++i) {
  600. std::unique_ptr<LiveInterval> LI(new LiveInterval(i, 0));
  601. LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
  602. Intervals.push_back(std::move(LI));
  603. SortedSlots.push_back(i);
  604. }
  605. // Calculate the liveness of each block.
  606. calculateLocalLiveness();
  607. // Propagate the liveness information.
  608. calculateLiveIntervals(NumSlots);
  609. // Search for allocas which are used outside of the declared lifetime
  610. // markers.
  611. if (ProtectFromEscapedAllocas)
  612. removeInvalidSlotRanges();
  613. // Maps old slots to new slots.
  614. DenseMap<int, int> SlotRemap;
  615. unsigned RemovedSlots = 0;
  616. unsigned ReducedSize = 0;
  617. // Do not bother looking at empty intervals.
  618. for (unsigned I = 0; I < NumSlots; ++I) {
  619. if (Intervals[SortedSlots[I]]->empty())
  620. SortedSlots[I] = -1;
  621. }
  622. // This is a simple greedy algorithm for merging allocas. First, sort the
  623. // slots, placing the largest slots first. Next, perform an n^2 scan and look
  624. // for disjoint slots. When you find disjoint slots, merge the samller one
  625. // into the bigger one and update the live interval. Remove the small alloca
  626. // and continue.
  627. // Sort the slots according to their size. Place unused slots at the end.
  628. // Use stable sort to guarantee deterministic code generation.
  629. std::stable_sort(SortedSlots.begin(), SortedSlots.end(),
  630. [this](int LHS, int RHS) {
  631. // We use -1 to denote a uninteresting slot. Place these slots at the end.
  632. if (LHS == -1) return false;
  633. if (RHS == -1) return true;
  634. // Sort according to size.
  635. return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS);
  636. });
  637. bool Changed = true;
  638. while (Changed) {
  639. Changed = false;
  640. for (unsigned I = 0; I < NumSlots; ++I) {
  641. if (SortedSlots[I] == -1)
  642. continue;
  643. for (unsigned J=I+1; J < NumSlots; ++J) {
  644. if (SortedSlots[J] == -1)
  645. continue;
  646. int FirstSlot = SortedSlots[I];
  647. int SecondSlot = SortedSlots[J];
  648. LiveInterval *First = &*Intervals[FirstSlot];
  649. LiveInterval *Second = &*Intervals[SecondSlot];
  650. assert (!First->empty() && !Second->empty() && "Found an empty range");
  651. // Merge disjoint slots.
  652. if (!First->overlaps(*Second)) {
  653. Changed = true;
  654. First->MergeSegmentsInAsValue(*Second, First->getValNumInfo(0));
  655. SlotRemap[SecondSlot] = FirstSlot;
  656. SortedSlots[J] = -1;
  657. DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<<
  658. SecondSlot<<" together.\n");
  659. unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot),
  660. MFI->getObjectAlignment(SecondSlot));
  661. assert(MFI->getObjectSize(FirstSlot) >=
  662. MFI->getObjectSize(SecondSlot) &&
  663. "Merging a small object into a larger one");
  664. RemovedSlots+=1;
  665. ReducedSize += MFI->getObjectSize(SecondSlot);
  666. MFI->setObjectAlignment(FirstSlot, MaxAlignment);
  667. MFI->RemoveStackObject(SecondSlot);
  668. }
  669. }
  670. }
  671. }// While changed.
  672. // Record statistics.
  673. StackSpaceSaved += ReducedSize;
  674. StackSlotMerged += RemovedSlots;
  675. DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<<
  676. ReducedSize<<" bytes\n");
  677. // Scan the entire function and update all machine operands that use frame
  678. // indices to use the remapped frame index.
  679. expungeSlotMap(SlotRemap, NumSlots);
  680. remapInstructions(SlotRemap);
  681. return removeAllMarkers();
  682. }