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/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineLoopInfo.h"
36 #include "llvm/CodeGen/MachineMemOperand.h"
37 #include "llvm/CodeGen/MachineModuleInfo.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/CodeGen/Passes.h"
40 #include "llvm/CodeGen/PseudoSourceValue.h"
41 #include "llvm/CodeGen/SlotIndexes.h"
42 #include "llvm/CodeGen/StackProtector.h"
43 #include "llvm/CodeGen/WinEHFuncInfo.h"
44 #include "llvm/IR/DebugInfo.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/IntrinsicInst.h"
48 #include "llvm/IR/Module.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Target/TargetInstrInfo.h"
53 #include "llvm/Target/TargetRegisterInfo.h"
54 
55 using namespace llvm;
56 
57 #define DEBUG_TYPE "stackcoloring"
58 
59 static cl::opt<bool>
60 DisableColoring("no-stack-coloring",
61         cl::init(false), cl::Hidden,
62         cl::desc("Disable stack coloring"));
63 
64 /// The user may write code that uses allocas outside of the declared lifetime
65 /// zone. This can happen when the user returns a reference to a local
66 /// data-structure. We can detect these cases and decide not to optimize the
67 /// code. If this flag is enabled, we try to save the user. This option
68 /// is treated as overriding LifetimeStartOnFirstUse below.
69 static cl::opt<bool>
70 ProtectFromEscapedAllocas("protect-from-escaped-allocas",
71                           cl::init(false), cl::Hidden,
72                           cl::desc("Do not optimize lifetime zones that "
73                                    "are broken"));
74 
75 /// Enable enhanced dataflow scheme for lifetime analysis (treat first
76 /// use of stack slot as start of slot lifetime, as opposed to looking
77 /// for LIFETIME_START marker). See "Implementation notes" below for
78 /// more info.
79 static cl::opt<bool>
80 LifetimeStartOnFirstUse("stackcoloring-lifetime-start-on-first-use",
81         cl::init(true), cl::Hidden,
82         cl::desc("Treat stack lifetimes as starting on first use, not on START marker."));
83 
84 
85 STATISTIC(NumMarkerSeen,  "Number of lifetime markers found.");
86 STATISTIC(StackSpaceSaved, "Number of bytes saved due to merging slots.");
87 STATISTIC(StackSlotMerged, "Number of stack slot merged.");
88 STATISTIC(EscapedAllocas, "Number of allocas that escaped the lifetime region");
89 
90 //
91 // Implementation Notes:
92 // ---------------------
93 //
94 // Consider the following motivating example:
95 //
96 //     int foo() {
97 //       char b1[1024], b2[1024];
98 //       if (...) {
99 //         char b3[1024];
100 //         <uses of b1, b3>;
101 //         return x;
102 //       } else {
103 //         char b4[1024], b5[1024];
104 //         <uses of b2, b4, b5>;
105 //         return y;
106 //       }
107 //     }
108 //
109 // In the code above, "b3" and "b4" are declared in distinct lexical
110 // scopes, meaning that it is easy to prove that they can share the
111 // same stack slot. Variables "b1" and "b2" are declared in the same
112 // scope, meaning that from a lexical point of view, their lifetimes
113 // overlap. From a control flow pointer of view, however, the two
114 // variables are accessed in disjoint regions of the CFG, thus it
115 // should be possible for them to share the same stack slot. An ideal
116 // stack allocation for the function above would look like:
117 //
118 //     slot 0: b1, b2
119 //     slot 1: b3, b4
120 //     slot 2: b5
121 //
122 // Achieving this allocation is tricky, however, due to the way
123 // lifetime markers are inserted. Here is a simplified view of the
124 // control flow graph for the code above:
125 //
126 //                +------  block 0 -------+
127 //               0| LIFETIME_START b1, b2 |
128 //               1| <test 'if' condition> |
129 //                +-----------------------+
130 //                   ./              \.
131 //   +------  block 1 -------+   +------  block 2 -------+
132 //  2| LIFETIME_START b3     |  5| LIFETIME_START b4, b5 |
133 //  3| <uses of b1, b3>      |  6| <uses of b2, b4, b5>  |
134 //  4| LIFETIME_END b3       |  7| LIFETIME_END b4, b5   |
135 //   +-----------------------+   +-----------------------+
136 //                   \.              /.
137 //                +------  block 3 -------+
138 //               8| <cleanupcode>         |
139 //               9| LIFETIME_END b1, b2   |
140 //              10| return                |
141 //                +-----------------------+
142 //
143 // If we create live intervals for the variables above strictly based
144 // on the lifetime markers, we'll get the set of intervals on the
145 // left. If we ignore the lifetime start markers and instead treat a
146 // variable's lifetime as beginning with the first reference to the
147 // var, then we get the intervals on the right.
148 //
149 //            LIFETIME_START      First Use
150 //     b1:    [0,9]               [3,4] [8,9]
151 //     b2:    [0,9]               [6,9]
152 //     b3:    [2,4]               [3,4]
153 //     b4:    [5,7]               [6,7]
154 //     b5:    [5,7]               [6,7]
155 //
156 // For the intervals on the left, the best we can do is overlap two
157 // variables (b3 and b4, for example); this gives us a stack size of
158 // 4*1024 bytes, not ideal. When treating first-use as the start of a
159 // lifetime, we can additionally overlap b1 and b5, giving us a 3*1024
160 // byte stack (better).
161 //
162 // Relying entirely on first-use of stack slots is problematic,
163 // however, due to the fact that optimizations can sometimes migrate
164 // uses of a variable outside of its lifetime start/end region. Here
165 // is an example:
166 //
167 //     int bar() {
168 //       char b1[1024], b2[1024];
169 //       if (...) {
170 //         <uses of b2>
171 //         return y;
172 //       } else {
173 //         <uses of b1>
174 //         while (...) {
175 //           char b3[1024];
176 //           <uses of b3>
177 //         }
178 //       }
179 //     }
180 //
181 // Before optimization, the control flow graph for the code above
182 // might look like the following:
183 //
184 //                +------  block 0 -------+
185 //               0| LIFETIME_START b1, b2 |
186 //               1| <test 'if' condition> |
187 //                +-----------------------+
188 //                   ./              \.
189 //   +------  block 1 -------+    +------- block 2 -------+
190 //  2| <uses of b2>          |   3| <uses of b1>          |
191 //   +-----------------------+    +-----------------------+
192 //              |                            |
193 //              |                 +------- block 3 -------+ <-\.
194 //              |                4| <while condition>     |    |
195 //              |                 +-----------------------+    |
196 //              |               /          |                   |
197 //              |              /  +------- block 4 -------+
198 //              \             /  5| LIFETIME_START b3     |    |
199 //               \           /   6| <uses of b3>          |    |
200 //                \         /    7| LIFETIME_END b3       |    |
201 //                 \        |    +------------------------+    |
202 //                  \       |                 \                /
203 //                +------  block 5 -----+      \---------------
204 //               8| <cleanupcode>       |
205 //               9| LIFETIME_END b1, b2 |
206 //              10| return              |
207 //                +---------------------+
208 //
209 // During optimization, however, it can happen that an instruction
210 // computing an address in "b3" (for example, a loop-invariant GEP) is
211 // hoisted up out of the loop from block 4 to block 2.  [Note that
212 // this is not an actual load from the stack, only an instruction that
213 // computes the address to be loaded]. If this happens, there is now a
214 // path leading from the first use of b3 to the return instruction
215 // that does not encounter the b3 LIFETIME_END, hence b3's lifetime is
216 // now larger than if we were computing live intervals strictly based
217 // on lifetime markers. In the example above, this lengthened lifetime
218 // would mean that it would appear illegal to overlap b3 with b2.
219 //
220 // To deal with this such cases, the code in ::collectMarkers() below
221 // tries to identify "degenerate" slots -- those slots where on a single
222 // forward pass through the CFG we encounter a first reference to slot
223 // K before we hit the slot K lifetime start marker. For such slots,
224 // we fall back on using the lifetime start marker as the beginning of
225 // the variable's lifetime.  NB: with this implementation, slots can
226 // appear degenerate in cases where there is unstructured control flow:
227 //
228 //    if (q) goto mid;
229 //    if (x > 9) {
230 //         int b[100];
231 //         memcpy(&b[0], ...);
232 //    mid: b[k] = ...;
233 //         abc(&b);
234 //    }
235 //
236 // If in RPO ordering chosen to walk the CFG  we happen to visit the b[k]
237 // before visiting the memcpy block (which will contain the lifetime start
238 // for "b" then it will appear that 'b' has a degenerate lifetime.
239 //
240 
241 //===----------------------------------------------------------------------===//
242 //                           StackColoring Pass
243 //===----------------------------------------------------------------------===//
244 
245 namespace {
246 /// StackColoring - A machine pass for merging disjoint stack allocations,
247 /// marked by the LIFETIME_START and LIFETIME_END pseudo instructions.
248 class StackColoring : public MachineFunctionPass {
249   MachineFrameInfo *MFI;
250   MachineFunction *MF;
251 
252   /// A class representing liveness information for a single basic block.
253   /// Each bit in the BitVector represents the liveness property
254   /// for a different stack slot.
255   struct BlockLifetimeInfo {
256     /// Which slots BEGINs in each basic block.
257     BitVector Begin;
258     /// Which slots ENDs in each basic block.
259     BitVector End;
260     /// Which slots are marked as LIVE_IN, coming into each basic block.
261     BitVector LiveIn;
262     /// Which slots are marked as LIVE_OUT, coming out of each basic block.
263     BitVector LiveOut;
264   };
265 
266   /// Maps active slots (per bit) for each basic block.
267   typedef DenseMap<const MachineBasicBlock*, BlockLifetimeInfo> LivenessMap;
268   LivenessMap BlockLiveness;
269 
270   /// Maps serial numbers to basic blocks.
271   DenseMap<const MachineBasicBlock*, int> BasicBlocks;
272   /// Maps basic blocks to a serial number.
273   SmallVector<const MachineBasicBlock*, 8> BasicBlockNumbering;
274 
275   /// Maps liveness intervals for each slot.
276   SmallVector<std::unique_ptr<LiveInterval>, 16> Intervals;
277   /// VNInfo is used for the construction of LiveIntervals.
278   VNInfo::Allocator VNInfoAllocator;
279   /// SlotIndex analysis object.
280   SlotIndexes *Indexes;
281   /// The stack protector object.
282   StackProtector *SP;
283 
284   /// The list of lifetime markers found. These markers are to be removed
285   /// once the coloring is done.
286   SmallVector<MachineInstr*, 8> Markers;
287 
288   /// Record the FI slots for which we have seen some sort of
289   /// lifetime marker (either start or end).
290   BitVector InterestingSlots;
291 
292   /// FI slots that need to be handled conservatively (for these
293   /// slots lifetime-start-on-first-use is disabled).
294   BitVector ConservativeSlots;
295 
296   /// Number of iterations taken during data flow analysis.
297   unsigned NumIterations;
298 
299 public:
300   static char ID;
301   StackColoring() : MachineFunctionPass(ID) {
302     initializeStackColoringPass(*PassRegistry::getPassRegistry());
303   }
304   void getAnalysisUsage(AnalysisUsage &AU) const override;
305   bool runOnMachineFunction(MachineFunction &MF) override;
306 
307 private:
308   /// Debug.
309   void dump() const;
310   void dumpIntervals() const;
311   void dumpBB(MachineBasicBlock *MBB) const;
312   void dumpBV(const char *tag, const BitVector &BV) const;
313 
314   /// Removes all of the lifetime marker instructions from the function.
315   /// \returns true if any markers were removed.
316   bool removeAllMarkers();
317 
318   /// Scan the machine function and find all of the lifetime markers.
319   /// Record the findings in the BEGIN and END vectors.
320   /// \returns the number of markers found.
321   unsigned collectMarkers(unsigned NumSlot);
322 
323   /// Perform the dataflow calculation and calculate the lifetime for each of
324   /// the slots, based on the BEGIN/END vectors. Set the LifetimeLIVE_IN and
325   /// LifetimeLIVE_OUT maps that represent which stack slots are live coming
326   /// in and out blocks.
327   void calculateLocalLiveness();
328 
329   /// Returns TRUE if we're using the first-use-begins-lifetime method for
330   /// this slot (if FALSE, then the start marker is treated as start of lifetime).
331   bool applyFirstUse(int Slot) {
332     if (!LifetimeStartOnFirstUse || ProtectFromEscapedAllocas)
333       return false;
334     if (ConservativeSlots.test(Slot))
335       return false;
336     return true;
337   }
338 
339   /// Examines the specified instruction and returns TRUE if the instruction
340   /// represents the start or end of an interesting lifetime. The slot or slots
341   /// starting or ending are added to the vector "slots" and "isStart" is set
342   /// accordingly.
343   /// \returns True if inst contains a lifetime start or end
344   bool isLifetimeStartOrEnd(const MachineInstr &MI,
345                             SmallVector<int, 4> &slots,
346                             bool &isStart);
347 
348   /// Construct the LiveIntervals for the slots.
349   void calculateLiveIntervals(unsigned NumSlots);
350 
351   /// Go over the machine function and change instructions which use stack
352   /// slots to use the joint slots.
353   void remapInstructions(DenseMap<int, int> &SlotRemap);
354 
355   /// The input program may contain instructions which are not inside lifetime
356   /// markers. This can happen due to a bug in the compiler or due to a bug in
357   /// user code (for example, returning a reference to a local variable).
358   /// This procedure checks all of the instructions in the function and
359   /// invalidates lifetime ranges which do not contain all of the instructions
360   /// which access that frame slot.
361   void removeInvalidSlotRanges();
362 
363   /// Map entries which point to other entries to their destination.
364   ///   A->B->C becomes A->C.
365   void expungeSlotMap(DenseMap<int, int> &SlotRemap, unsigned NumSlots);
366 
367   /// Used in collectMarkers
368   typedef DenseMap<const MachineBasicBlock*, BitVector> BlockBitVecMap;
369 };
370 } // end anonymous namespace
371 
372 char StackColoring::ID = 0;
373 char &llvm::StackColoringID = StackColoring::ID;
374 
375 INITIALIZE_PASS_BEGIN(StackColoring,
376                    "stack-coloring", "Merge disjoint stack slots", false, false)
377 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
378 INITIALIZE_PASS_DEPENDENCY(StackProtector)
379 INITIALIZE_PASS_END(StackColoring,
380                    "stack-coloring", "Merge disjoint stack slots", false, false)
381 
382 void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const {
383   AU.addRequired<SlotIndexes>();
384   AU.addRequired<StackProtector>();
385   MachineFunctionPass::getAnalysisUsage(AU);
386 }
387 
388 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
389 LLVM_DUMP_METHOD void StackColoring::dumpBV(const char *tag,
390                                             const BitVector &BV) const {
391   dbgs() << tag << " : { ";
392   for (unsigned I = 0, E = BV.size(); I != E; ++I)
393     dbgs() << BV.test(I) << " ";
394   dbgs() << "}\n";
395 }
396 
397 LLVM_DUMP_METHOD void StackColoring::dumpBB(MachineBasicBlock *MBB) const {
398   LivenessMap::const_iterator BI = BlockLiveness.find(MBB);
399   assert(BI != BlockLiveness.end() && "Block not found");
400   const BlockLifetimeInfo &BlockInfo = BI->second;
401 
402   dumpBV("BEGIN", BlockInfo.Begin);
403   dumpBV("END", BlockInfo.End);
404   dumpBV("LIVE_IN", BlockInfo.LiveIn);
405   dumpBV("LIVE_OUT", BlockInfo.LiveOut);
406 }
407 
408 LLVM_DUMP_METHOD void StackColoring::dump() const {
409   for (MachineBasicBlock *MBB : depth_first(MF)) {
410     dbgs() << "Inspecting block #" << MBB->getNumber() << " ["
411            << MBB->getName() << "]\n";
412     dumpBB(MBB);
413   }
414 }
415 
416 LLVM_DUMP_METHOD void StackColoring::dumpIntervals() const {
417   for (unsigned I = 0, E = Intervals.size(); I != E; ++I) {
418     dbgs() << "Interval[" << I << "]:\n";
419     Intervals[I]->dump();
420   }
421 }
422 #endif
423 
424 static inline int getStartOrEndSlot(const MachineInstr &MI)
425 {
426   assert((MI.getOpcode() == TargetOpcode::LIFETIME_START ||
427           MI.getOpcode() == TargetOpcode::LIFETIME_END) &&
428          "Expected LIFETIME_START or LIFETIME_END op");
429   const MachineOperand &MO = MI.getOperand(0);
430   int Slot = MO.getIndex();
431   if (Slot >= 0)
432     return Slot;
433   return -1;
434 }
435 
436 //
437 // At the moment the only way to end a variable lifetime is with
438 // a VARIABLE_LIFETIME op (which can't contain a start). If things
439 // change and the IR allows for a single inst that both begins
440 // and ends lifetime(s), this interface will need to be reworked.
441 //
442 bool StackColoring::isLifetimeStartOrEnd(const MachineInstr &MI,
443                                          SmallVector<int, 4> &slots,
444                                          bool &isStart)
445 {
446   if (MI.getOpcode() == TargetOpcode::LIFETIME_START ||
447       MI.getOpcode() == TargetOpcode::LIFETIME_END) {
448     int Slot = getStartOrEndSlot(MI);
449     if (Slot < 0)
450       return false;
451     if (!InterestingSlots.test(Slot))
452       return false;
453     slots.push_back(Slot);
454     if (MI.getOpcode() == TargetOpcode::LIFETIME_END) {
455       isStart = false;
456       return true;
457     }
458     if (! applyFirstUse(Slot)) {
459       isStart = true;
460       return true;
461     }
462   } else if (LifetimeStartOnFirstUse && !ProtectFromEscapedAllocas) {
463     if (! MI.isDebugValue()) {
464       bool found = false;
465       for (const MachineOperand &MO : MI.operands()) {
466         if (!MO.isFI())
467           continue;
468         int Slot = MO.getIndex();
469         if (Slot<0)
470           continue;
471         if (InterestingSlots.test(Slot) && applyFirstUse(Slot)) {
472           slots.push_back(Slot);
473           found = true;
474         }
475       }
476       if (found) {
477         isStart = true;
478         return true;
479       }
480     }
481   }
482   return false;
483 }
484 
485 unsigned StackColoring::collectMarkers(unsigned NumSlot)
486 {
487   unsigned MarkersFound = 0;
488   BlockBitVecMap SeenStartMap;
489   InterestingSlots.clear();
490   InterestingSlots.resize(NumSlot);
491   ConservativeSlots.clear();
492   ConservativeSlots.resize(NumSlot);
493 
494   // number of start and end lifetime ops for each slot
495   SmallVector<int, 8> NumStartLifetimes(NumSlot, 0);
496   SmallVector<int, 8> NumEndLifetimes(NumSlot, 0);
497 
498   // Step 1: collect markers and populate the "InterestingSlots"
499   // and "ConservativeSlots" sets.
500   for (MachineBasicBlock *MBB : depth_first(MF)) {
501 
502     // Compute the set of slots for which we've seen a START marker but have
503     // not yet seen an END marker at this point in the walk (e.g. on entry
504     // to this bb).
505     BitVector BetweenStartEnd;
506     BetweenStartEnd.resize(NumSlot);
507     for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
508              PE = MBB->pred_end(); PI != PE; ++PI) {
509       BlockBitVecMap::const_iterator I = SeenStartMap.find(*PI);
510       if (I != SeenStartMap.end()) {
511         BetweenStartEnd |= I->second;
512       }
513     }
514 
515     // Walk the instructions in the block to look for start/end ops.
516     for (MachineInstr &MI : *MBB) {
517       if (MI.getOpcode() == TargetOpcode::LIFETIME_START ||
518           MI.getOpcode() == TargetOpcode::LIFETIME_END) {
519         int Slot = getStartOrEndSlot(MI);
520         if (Slot < 0)
521           continue;
522         InterestingSlots.set(Slot);
523         if (MI.getOpcode() == TargetOpcode::LIFETIME_START) {
524           BetweenStartEnd.set(Slot);
525           NumStartLifetimes[Slot] += 1;
526         } else {
527           BetweenStartEnd.reset(Slot);
528           NumEndLifetimes[Slot] += 1;
529         }
530         const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
531         if (Allocation) {
532           DEBUG(dbgs() << "Found a lifetime ");
533           DEBUG(dbgs() << (MI.getOpcode() == TargetOpcode::LIFETIME_START
534                                ? "start"
535                                : "end"));
536           DEBUG(dbgs() << " marker for slot #" << Slot);
537           DEBUG(dbgs() << " with allocation: " << Allocation->getName()
538                        << "\n");
539         }
540         Markers.push_back(&MI);
541         MarkersFound += 1;
542       } else {
543         for (const MachineOperand &MO : MI.operands()) {
544           if (!MO.isFI())
545             continue;
546           int Slot = MO.getIndex();
547           if (Slot < 0)
548             continue;
549           if (! BetweenStartEnd.test(Slot)) {
550             ConservativeSlots.set(Slot);
551           }
552         }
553       }
554     }
555     BitVector &SeenStart = SeenStartMap[MBB];
556     SeenStart |= BetweenStartEnd;
557   }
558   if (!MarkersFound) {
559     return 0;
560   }
561 
562   // PR27903: slots with multiple start or end lifetime ops are not
563   // safe to enable for "lifetime-start-on-first-use".
564   for (unsigned slot = 0; slot < NumSlot; ++slot)
565     if (NumStartLifetimes[slot] > 1 || NumEndLifetimes[slot] > 1)
566       ConservativeSlots.set(slot);
567   DEBUG(dumpBV("Conservative slots", ConservativeSlots));
568 
569   // Step 2: compute begin/end sets for each block
570 
571   // NOTE: We use a reverse-post-order iteration to ensure that we obtain a
572   // deterministic numbering, and because we'll need a post-order iteration
573   // later for solving the liveness dataflow problem.
574   for (MachineBasicBlock *MBB : depth_first(MF)) {
575 
576     // Assign a serial number to this basic block.
577     BasicBlocks[MBB] = BasicBlockNumbering.size();
578     BasicBlockNumbering.push_back(MBB);
579 
580     // Keep a reference to avoid repeated lookups.
581     BlockLifetimeInfo &BlockInfo = BlockLiveness[MBB];
582 
583     BlockInfo.Begin.resize(NumSlot);
584     BlockInfo.End.resize(NumSlot);
585 
586     SmallVector<int, 4> slots;
587     for (MachineInstr &MI : *MBB) {
588       bool isStart = false;
589       slots.clear();
590       if (isLifetimeStartOrEnd(MI, slots, isStart)) {
591         if (!isStart) {
592           assert(slots.size() == 1 && "unexpected: MI ends multiple slots");
593           int Slot = slots[0];
594           if (BlockInfo.Begin.test(Slot)) {
595             BlockInfo.Begin.reset(Slot);
596           }
597           BlockInfo.End.set(Slot);
598         } else {
599           for (auto Slot : slots) {
600             DEBUG(dbgs() << "Found a use of slot #" << Slot);
601             DEBUG(dbgs() << " at BB#" << MBB->getNumber() << " index ");
602             DEBUG(Indexes->getInstructionIndex(MI).print(dbgs()));
603             const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
604             if (Allocation) {
605               DEBUG(dbgs() << " with allocation: "<< Allocation->getName());
606             }
607             DEBUG(dbgs() << "\n");
608             if (BlockInfo.End.test(Slot)) {
609               BlockInfo.End.reset(Slot);
610             }
611             BlockInfo.Begin.set(Slot);
612           }
613         }
614       }
615     }
616   }
617 
618   // Update statistics.
619   NumMarkerSeen += MarkersFound;
620   return MarkersFound;
621 }
622 
623 void StackColoring::calculateLocalLiveness()
624 {
625   unsigned NumIters = 0;
626   bool changed = true;
627   while (changed) {
628     changed = false;
629     ++NumIters;
630 
631     for (const MachineBasicBlock *BB : BasicBlockNumbering) {
632 
633       // Use an iterator to avoid repeated lookups.
634       LivenessMap::iterator BI = BlockLiveness.find(BB);
635       assert(BI != BlockLiveness.end() && "Block not found");
636       BlockLifetimeInfo &BlockInfo = BI->second;
637 
638       // Compute LiveIn by unioning together the LiveOut sets of all preds.
639       BitVector LocalLiveIn;
640       for (MachineBasicBlock::const_pred_iterator PI = BB->pred_begin(),
641            PE = BB->pred_end(); PI != PE; ++PI) {
642         LivenessMap::const_iterator I = BlockLiveness.find(*PI);
643         assert(I != BlockLiveness.end() && "Predecessor not found");
644         LocalLiveIn |= I->second.LiveOut;
645       }
646 
647       // Compute LiveOut by subtracting out lifetimes that end in this
648       // block, then adding in lifetimes that begin in this block.  If
649       // we have both BEGIN and END markers in the same basic block
650       // then we know that the BEGIN marker comes after the END,
651       // because we already handle the case where the BEGIN comes
652       // before the END when collecting the markers (and building the
653       // BEGIN/END vectors).
654       BitVector LocalLiveOut = LocalLiveIn;
655       LocalLiveOut.reset(BlockInfo.End);
656       LocalLiveOut |= BlockInfo.Begin;
657 
658       // Update block LiveIn set, noting whether it has changed.
659       if (LocalLiveIn.test(BlockInfo.LiveIn)) {
660         changed = true;
661         BlockInfo.LiveIn |= LocalLiveIn;
662       }
663 
664       // Update block LiveOut set, noting whether it has changed.
665       if (LocalLiveOut.test(BlockInfo.LiveOut)) {
666         changed = true;
667         BlockInfo.LiveOut |= LocalLiveOut;
668       }
669     }
670   }// while changed.
671 
672   NumIterations = NumIters;
673 }
674 
675 void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
676   SmallVector<SlotIndex, 16> Starts;
677   SmallVector<SlotIndex, 16> Finishes;
678 
679   // For each block, find which slots are active within this block
680   // and update the live intervals.
681   for (const MachineBasicBlock &MBB : *MF) {
682     Starts.clear();
683     Starts.resize(NumSlots);
684     Finishes.clear();
685     Finishes.resize(NumSlots);
686 
687     // Create the interval for the basic blocks containing lifetime begin/end.
688     for (const MachineInstr &MI : MBB) {
689 
690       SmallVector<int, 4> slots;
691       bool IsStart = false;
692       if (!isLifetimeStartOrEnd(MI, slots, IsStart))
693         continue;
694       SlotIndex ThisIndex = Indexes->getInstructionIndex(MI);
695       for (auto Slot : slots) {
696         if (IsStart) {
697           if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex)
698             Starts[Slot] = ThisIndex;
699         } else {
700           if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex)
701             Finishes[Slot] = ThisIndex;
702         }
703       }
704     }
705 
706     // Create the interval of the blocks that we previously found to be 'alive'.
707     BlockLifetimeInfo &MBBLiveness = BlockLiveness[&MBB];
708     for (int pos = MBBLiveness.LiveIn.find_first(); pos != -1;
709          pos = MBBLiveness.LiveIn.find_next(pos)) {
710       Starts[pos] = Indexes->getMBBStartIdx(&MBB);
711     }
712     for (int pos = MBBLiveness.LiveOut.find_first(); pos != -1;
713          pos = MBBLiveness.LiveOut.find_next(pos)) {
714       Finishes[pos] = Indexes->getMBBEndIdx(&MBB);
715     }
716 
717     for (unsigned i = 0; i < NumSlots; ++i) {
718       //
719       // When LifetimeStartOnFirstUse is turned on, data flow analysis
720       // is forward (from starts to ends), not bidirectional. A
721       // consequence of this is that we can wind up in situations
722       // where Starts[i] is invalid but Finishes[i] is valid and vice
723       // versa. Example:
724       //
725       //     LIFETIME_START x
726       //     if (...) {
727       //       <use of x>
728       //       throw ...;
729       //     }
730       //     LIFETIME_END x
731       //     return 2;
732       //
733       //
734       // Here the slot for "x" will not be live into the block
735       // containing the "return 2" (since lifetimes start with first
736       // use, not at the dominating LIFETIME_START marker).
737       //
738       if (Starts[i].isValid() && !Finishes[i].isValid()) {
739         Finishes[i] = Indexes->getMBBEndIdx(&MBB);
740       }
741       if (!Starts[i].isValid())
742         continue;
743 
744       assert(Starts[i] && Finishes[i] && "Invalid interval");
745       VNInfo *ValNum = Intervals[i]->getValNumInfo(0);
746       SlotIndex S = Starts[i];
747       SlotIndex F = Finishes[i];
748       if (S < F) {
749         // We have a single consecutive region.
750         Intervals[i]->addSegment(LiveInterval::Segment(S, F, ValNum));
751       } else {
752         // We have two non-consecutive regions. This happens when
753         // LIFETIME_START appears after the LIFETIME_END marker.
754         SlotIndex NewStart = Indexes->getMBBStartIdx(&MBB);
755         SlotIndex NewFin = Indexes->getMBBEndIdx(&MBB);
756         Intervals[i]->addSegment(LiveInterval::Segment(NewStart, F, ValNum));
757         Intervals[i]->addSegment(LiveInterval::Segment(S, NewFin, ValNum));
758       }
759     }
760   }
761 }
762 
763 bool StackColoring::removeAllMarkers() {
764   unsigned Count = 0;
765   for (MachineInstr *MI : Markers) {
766     MI->eraseFromParent();
767     Count++;
768   }
769   Markers.clear();
770 
771   DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n");
772   return Count;
773 }
774 
775 void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
776   unsigned FixedInstr = 0;
777   unsigned FixedMemOp = 0;
778   unsigned FixedDbg = 0;
779 
780   // Remap debug information that refers to stack slots.
781   for (auto &VI : MF->getVariableDbgInfo()) {
782     if (!VI.Var)
783       continue;
784     if (SlotRemap.count(VI.Slot)) {
785       DEBUG(dbgs() << "Remapping debug info for ["
786                    << cast<DILocalVariable>(VI.Var)->getName() << "].\n");
787       VI.Slot = SlotRemap[VI.Slot];
788       FixedDbg++;
789     }
790   }
791 
792   // Keep a list of *allocas* which need to be remapped.
793   DenseMap<const AllocaInst*, const AllocaInst*> Allocas;
794   for (const std::pair<int, int> &SI : SlotRemap) {
795     const AllocaInst *From = MFI->getObjectAllocation(SI.first);
796     const AllocaInst *To = MFI->getObjectAllocation(SI.second);
797     assert(To && From && "Invalid allocation object");
798     Allocas[From] = To;
799 
800     // AA might be used later for instruction scheduling, and we need it to be
801     // able to deduce the correct aliasing releationships between pointers
802     // derived from the alloca being remapped and the target of that remapping.
803     // The only safe way, without directly informing AA about the remapping
804     // somehow, is to directly update the IR to reflect the change being made
805     // here.
806     Instruction *Inst = const_cast<AllocaInst *>(To);
807     if (From->getType() != To->getType()) {
808       BitCastInst *Cast = new BitCastInst(Inst, From->getType());
809       Cast->insertAfter(Inst);
810       Inst = Cast;
811     }
812 
813     // Allow the stack protector to adjust its value map to account for the
814     // upcoming replacement.
815     SP->adjustForColoring(From, To);
816 
817     // The new alloca might not be valid in a llvm.dbg.declare for this
818     // variable, so undef out the use to make the verifier happy.
819     AllocaInst *FromAI = const_cast<AllocaInst *>(From);
820     if (FromAI->isUsedByMetadata())
821       ValueAsMetadata::handleRAUW(FromAI, UndefValue::get(FromAI->getType()));
822     for (auto &Use : FromAI->uses()) {
823       if (BitCastInst *BCI = dyn_cast<BitCastInst>(Use.get()))
824         if (BCI->isUsedByMetadata())
825           ValueAsMetadata::handleRAUW(BCI, UndefValue::get(BCI->getType()));
826     }
827 
828     // Note that this will not replace uses in MMOs (which we'll update below),
829     // or anywhere else (which is why we won't delete the original
830     // instruction).
831     FromAI->replaceAllUsesWith(Inst);
832   }
833 
834   // Remap all instructions to the new stack slots.
835   for (MachineBasicBlock &BB : *MF)
836     for (MachineInstr &I : BB) {
837       // Skip lifetime markers. We'll remove them soon.
838       if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
839           I.getOpcode() == TargetOpcode::LIFETIME_END)
840         continue;
841 
842       // Update the MachineMemOperand to use the new alloca.
843       for (MachineMemOperand *MMO : I.memoperands()) {
844         // FIXME: In order to enable the use of TBAA when using AA in CodeGen,
845         // we'll also need to update the TBAA nodes in MMOs with values
846         // derived from the merged allocas. When doing this, we'll need to use
847         // the same variant of GetUnderlyingObjects that is used by the
848         // instruction scheduler (that can look through ptrtoint/inttoptr
849         // pairs).
850 
851         // We've replaced IR-level uses of the remapped allocas, so we only
852         // need to replace direct uses here.
853         const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(MMO->getValue());
854         if (!AI)
855           continue;
856 
857         if (!Allocas.count(AI))
858           continue;
859 
860         MMO->setValue(Allocas[AI]);
861         FixedMemOp++;
862       }
863 
864       // Update all of the machine instruction operands.
865       for (MachineOperand &MO : I.operands()) {
866         if (!MO.isFI())
867           continue;
868         int FromSlot = MO.getIndex();
869 
870         // Don't touch arguments.
871         if (FromSlot<0)
872           continue;
873 
874         // Only look at mapped slots.
875         if (!SlotRemap.count(FromSlot))
876           continue;
877 
878         // In a debug build, check that the instruction that we are modifying is
879         // inside the expected live range. If the instruction is not inside
880         // the calculated range then it means that the alloca usage moved
881         // outside of the lifetime markers, or that the user has a bug.
882         // NOTE: Alloca address calculations which happen outside the lifetime
883         // zone are are okay, despite the fact that we don't have a good way
884         // for validating all of the usages of the calculation.
885 #ifndef NDEBUG
886         bool TouchesMemory = I.mayLoad() || I.mayStore();
887         // If we *don't* protect the user from escaped allocas, don't bother
888         // validating the instructions.
889         if (!I.isDebugValue() && TouchesMemory && ProtectFromEscapedAllocas) {
890           SlotIndex Index = Indexes->getInstructionIndex(I);
891           const LiveInterval *Interval = &*Intervals[FromSlot];
892           assert(Interval->find(Index) != Interval->end() &&
893                  "Found instruction usage outside of live range.");
894         }
895 #endif
896 
897         // Fix the machine instructions.
898         int ToSlot = SlotRemap[FromSlot];
899         MO.setIndex(ToSlot);
900         FixedInstr++;
901       }
902     }
903 
904   // Update the location of C++ catch objects for the MSVC personality routine.
905   if (WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo())
906     for (WinEHTryBlockMapEntry &TBME : EHInfo->TryBlockMap)
907       for (WinEHHandlerType &H : TBME.HandlerArray)
908         if (H.CatchObj.FrameIndex != INT_MAX &&
909             SlotRemap.count(H.CatchObj.FrameIndex))
910           H.CatchObj.FrameIndex = SlotRemap[H.CatchObj.FrameIndex];
911 
912   DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n");
913   DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n");
914   DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n");
915 }
916 
917 void StackColoring::removeInvalidSlotRanges() {
918   for (MachineBasicBlock &BB : *MF)
919     for (MachineInstr &I : BB) {
920       if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
921           I.getOpcode() == TargetOpcode::LIFETIME_END || I.isDebugValue())
922         continue;
923 
924       // Some intervals are suspicious! In some cases we find address
925       // calculations outside of the lifetime zone, but not actual memory
926       // read or write. Memory accesses outside of the lifetime zone are a clear
927       // violation, but address calculations are okay. This can happen when
928       // GEPs are hoisted outside of the lifetime zone.
929       // So, in here we only check instructions which can read or write memory.
930       if (!I.mayLoad() && !I.mayStore())
931         continue;
932 
933       // Check all of the machine operands.
934       for (const MachineOperand &MO : I.operands()) {
935         if (!MO.isFI())
936           continue;
937 
938         int Slot = MO.getIndex();
939 
940         if (Slot<0)
941           continue;
942 
943         if (Intervals[Slot]->empty())
944           continue;
945 
946         // Check that the used slot is inside the calculated lifetime range.
947         // If it is not, warn about it and invalidate the range.
948         LiveInterval *Interval = &*Intervals[Slot];
949         SlotIndex Index = Indexes->getInstructionIndex(I);
950         if (Interval->find(Index) == Interval->end()) {
951           Interval->clear();
952           DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n");
953           EscapedAllocas++;
954         }
955       }
956     }
957 }
958 
959 void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
960                                    unsigned NumSlots) {
961   // Expunge slot remap map.
962   for (unsigned i=0; i < NumSlots; ++i) {
963     // If we are remapping i
964     if (SlotRemap.count(i)) {
965       int Target = SlotRemap[i];
966       // As long as our target is mapped to something else, follow it.
967       while (SlotRemap.count(Target)) {
968         Target = SlotRemap[Target];
969         SlotRemap[i] = Target;
970       }
971     }
972   }
973 }
974 
975 bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
976   DEBUG(dbgs() << "********** Stack Coloring **********\n"
977                << "********** Function: "
978                << ((const Value*)Func.getFunction())->getName() << '\n');
979   MF = &Func;
980   MFI = &MF->getFrameInfo();
981   Indexes = &getAnalysis<SlotIndexes>();
982   SP = &getAnalysis<StackProtector>();
983   BlockLiveness.clear();
984   BasicBlocks.clear();
985   BasicBlockNumbering.clear();
986   Markers.clear();
987   Intervals.clear();
988   VNInfoAllocator.Reset();
989 
990   unsigned NumSlots = MFI->getObjectIndexEnd();
991 
992   // If there are no stack slots then there are no markers to remove.
993   if (!NumSlots)
994     return false;
995 
996   SmallVector<int, 8> SortedSlots;
997   SortedSlots.reserve(NumSlots);
998   Intervals.reserve(NumSlots);
999 
1000   unsigned NumMarkers = collectMarkers(NumSlots);
1001 
1002   unsigned TotalSize = 0;
1003   DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n");
1004   DEBUG(dbgs()<<"Slot structure:\n");
1005 
1006   for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
1007     DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n");
1008     TotalSize += MFI->getObjectSize(i);
1009   }
1010 
1011   DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n");
1012 
1013   // Don't continue because there are not enough lifetime markers, or the
1014   // stack is too small, or we are told not to optimize the slots.
1015   if (NumMarkers < 2 || TotalSize < 16 || DisableColoring ||
1016       skipFunction(*Func.getFunction())) {
1017     DEBUG(dbgs()<<"Will not try to merge slots.\n");
1018     return removeAllMarkers();
1019   }
1020 
1021   for (unsigned i=0; i < NumSlots; ++i) {
1022     std::unique_ptr<LiveInterval> LI(new LiveInterval(i, 0));
1023     LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
1024     Intervals.push_back(std::move(LI));
1025     SortedSlots.push_back(i);
1026   }
1027 
1028   // Calculate the liveness of each block.
1029   calculateLocalLiveness();
1030   DEBUG(dbgs() << "Dataflow iterations: " << NumIterations << "\n");
1031   DEBUG(dump());
1032 
1033   // Propagate the liveness information.
1034   calculateLiveIntervals(NumSlots);
1035   DEBUG(dumpIntervals());
1036 
1037   // Search for allocas which are used outside of the declared lifetime
1038   // markers.
1039   if (ProtectFromEscapedAllocas)
1040     removeInvalidSlotRanges();
1041 
1042   // Maps old slots to new slots.
1043   DenseMap<int, int> SlotRemap;
1044   unsigned RemovedSlots = 0;
1045   unsigned ReducedSize = 0;
1046 
1047   // Do not bother looking at empty intervals.
1048   for (unsigned I = 0; I < NumSlots; ++I) {
1049     if (Intervals[SortedSlots[I]]->empty())
1050       SortedSlots[I] = -1;
1051   }
1052 
1053   // This is a simple greedy algorithm for merging allocas. First, sort the
1054   // slots, placing the largest slots first. Next, perform an n^2 scan and look
1055   // for disjoint slots. When you find disjoint slots, merge the samller one
1056   // into the bigger one and update the live interval. Remove the small alloca
1057   // and continue.
1058 
1059   // Sort the slots according to their size. Place unused slots at the end.
1060   // Use stable sort to guarantee deterministic code generation.
1061   std::stable_sort(SortedSlots.begin(), SortedSlots.end(),
1062                    [this](int LHS, int RHS) {
1063     // We use -1 to denote a uninteresting slot. Place these slots at the end.
1064     if (LHS == -1) return false;
1065     if (RHS == -1) return true;
1066     // Sort according to size.
1067     return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS);
1068   });
1069 
1070   bool Changed = true;
1071   while (Changed) {
1072     Changed = false;
1073     for (unsigned I = 0; I < NumSlots; ++I) {
1074       if (SortedSlots[I] == -1)
1075         continue;
1076 
1077       for (unsigned J=I+1; J < NumSlots; ++J) {
1078         if (SortedSlots[J] == -1)
1079           continue;
1080 
1081         int FirstSlot = SortedSlots[I];
1082         int SecondSlot = SortedSlots[J];
1083         LiveInterval *First = &*Intervals[FirstSlot];
1084         LiveInterval *Second = &*Intervals[SecondSlot];
1085         assert (!First->empty() && !Second->empty() && "Found an empty range");
1086 
1087         // Merge disjoint slots.
1088         if (!First->overlaps(*Second)) {
1089           Changed = true;
1090           First->MergeSegmentsInAsValue(*Second, First->getValNumInfo(0));
1091           SlotRemap[SecondSlot] = FirstSlot;
1092           SortedSlots[J] = -1;
1093           DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<<
1094                 SecondSlot<<" together.\n");
1095           unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot),
1096                                            MFI->getObjectAlignment(SecondSlot));
1097 
1098           assert(MFI->getObjectSize(FirstSlot) >=
1099                  MFI->getObjectSize(SecondSlot) &&
1100                  "Merging a small object into a larger one");
1101 
1102           RemovedSlots+=1;
1103           ReducedSize += MFI->getObjectSize(SecondSlot);
1104           MFI->setObjectAlignment(FirstSlot, MaxAlignment);
1105           MFI->RemoveStackObject(SecondSlot);
1106         }
1107       }
1108     }
1109   }// While changed.
1110 
1111   // Record statistics.
1112   StackSpaceSaved += ReducedSize;
1113   StackSlotMerged += RemovedSlots;
1114   DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<<
1115         ReducedSize<<" bytes\n");
1116 
1117   // Scan the entire function and update all machine operands that use frame
1118   // indices to use the remapped frame index.
1119   expungeSlotMap(SlotRemap, NumSlots);
1120   remapInstructions(SlotRemap);
1121 
1122   return removeAllMarkers();
1123 }
1124