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