LLVM 20.0.0git
StackColoring.cpp
Go to the documentation of this file.
1//===- StackColoring.cpp --------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass implements the stack-coloring optimization that looks for
10// lifetime markers machine instructions (LIFETIME_START and LIFETIME_END),
11// which represent the possible lifetime of stack slots. It attempts to
12// merge disjoint stack slots and reduce the used stack space.
13// NOTE: This pass is not StackSlotColoring, which optimizes spill slots.
14//
15// TODO: In the future we plan to improve stack coloring in the following ways:
16// 1. Allow merging multiple small slots into a single larger slot at different
17// offsets.
18// 2. Merge this pass with StackSlotColoring and allow merging of allocas with
19// spill slots.
20//
21//===----------------------------------------------------------------------===//
22
23#include "llvm/ADT/BitVector.h"
24#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/Statistic.h"
38#include "llvm/CodeGen/Passes.h"
43#include "llvm/Config/llvm-config.h"
44#include "llvm/IR/Constants.h"
47#include "llvm/IR/Metadata.h"
48#include "llvm/IR/Use.h"
49#include "llvm/IR/Value.h"
51#include "llvm/Pass.h"
55#include "llvm/Support/Debug.h"
57#include <algorithm>
58#include <cassert>
59#include <limits>
60#include <memory>
61#include <utility>
62
63using namespace llvm;
64
65#define DEBUG_TYPE "stack-coloring"
66
67static cl::opt<bool>
68DisableColoring("no-stack-coloring",
69 cl::init(false), cl::Hidden,
70 cl::desc("Disable stack coloring"));
71
72/// The user may write code that uses allocas outside of the declared lifetime
73/// zone. This can happen when the user returns a reference to a local
74/// data-structure. We can detect these cases and decide not to optimize the
75/// code. If this flag is enabled, we try to save the user. This option
76/// is treated as overriding LifetimeStartOnFirstUse below.
77static cl::opt<bool>
78ProtectFromEscapedAllocas("protect-from-escaped-allocas",
79 cl::init(false), cl::Hidden,
80 cl::desc("Do not optimize lifetime zones that "
81 "are broken"));
82
83/// Enable enhanced dataflow scheme for lifetime analysis (treat first
84/// use of stack slot as start of slot lifetime, as opposed to looking
85/// for LIFETIME_START marker). See "Implementation notes" below for
86/// more info.
87static cl::opt<bool>
88LifetimeStartOnFirstUse("stackcoloring-lifetime-start-on-first-use",
89 cl::init(true), cl::Hidden,
90 cl::desc("Treat stack lifetimes as starting on first use, not on START marker."));
91
92
93STATISTIC(NumMarkerSeen, "Number of lifetime markers found.");
94STATISTIC(StackSpaceSaved, "Number of bytes saved due to merging slots.");
95STATISTIC(StackSlotMerged, "Number of stack slot merged.");
96STATISTIC(EscapedAllocas, "Number of allocas that escaped the lifetime region");
97
98//===----------------------------------------------------------------------===//
99// StackColoring Pass
100//===----------------------------------------------------------------------===//
101//
102// Stack Coloring reduces stack usage by merging stack slots when they
103// can't be used together. For example, consider the following C program:
104//
105// void bar(char *, int);
106// void foo(bool var) {
107// A: {
108// char z[4096];
109// bar(z, 0);
110// }
111//
112// char *p;
113// char x[4096];
114// char y[4096];
115// if (var) {
116// p = x;
117// } else {
118// bar(y, 1);
119// p = y + 1024;
120// }
121// B:
122// bar(p, 2);
123// }
124//
125// Naively-compiled, this program would use 12k of stack space. However, the
126// stack slot corresponding to `z` is always destroyed before either of the
127// stack slots for `x` or `y` are used, and then `x` is only used if `var`
128// is true, while `y` is only used if `var` is false. So in no time are 2
129// of the stack slots used together, and therefore we can merge them,
130// compiling the function using only a single 4k alloca:
131//
132// void foo(bool var) { // equivalent
133// char x[4096];
134// char *p;
135// bar(x, 0);
136// if (var) {
137// p = x;
138// } else {
139// bar(x, 1);
140// p = x + 1024;
141// }
142// bar(p, 2);
143// }
144//
145// This is an important optimization if we want stack space to be under
146// control in large functions, both open-coded ones and ones created by
147// inlining.
148//
149// Implementation Notes:
150// ---------------------
151//
152// An important part of the above reasoning is that `z` can't be accessed
153// while the latter 2 calls to `bar` are running. This is justified because
154// `z`'s lifetime is over after we exit from block `A:`, so any further
155// accesses to it would be UB. The way we represent this information
156// in LLVM is by having frontends delimit blocks with `lifetime.start`
157// and `lifetime.end` intrinsics.
158//
159// The effect of these intrinsics seems to be as follows (maybe I should
160// specify this in the reference?):
161//
162// L1) at start, each stack-slot is marked as *out-of-scope*, unless no
163// lifetime intrinsic refers to that stack slot, in which case
164// it is marked as *in-scope*.
165// L2) on a `lifetime.start`, a stack slot is marked as *in-scope* and
166// the stack slot is overwritten with `undef`.
167// L3) on a `lifetime.end`, a stack slot is marked as *out-of-scope*.
168// L4) on function exit, all stack slots are marked as *out-of-scope*.
169// L5) `lifetime.end` is a no-op when called on a slot that is already
170// *out-of-scope*.
171// L6) memory accesses to *out-of-scope* stack slots are UB.
172// L7) when a stack-slot is marked as *out-of-scope*, all pointers to it
173// are invalidated, unless the slot is "degenerate". This is used to
174// justify not marking slots as in-use until the pointer to them is
175// used, but feels a bit hacky in the presence of things like LICM. See
176// the "Degenerate Slots" section for more details.
177//
178// Now, let's ground stack coloring on these rules. We'll define a slot
179// as *in-use* at a (dynamic) point in execution if it either can be
180// written to at that point, or if it has a live and non-undef content
181// at that point.
182//
183// Obviously, slots that are never *in-use* together can be merged, and
184// in our example `foo`, the slots for `x`, `y` and `z` are never
185// in-use together (of course, sometimes slots that *are* in-use together
186// might still be mergable, but we don't care about that here).
187//
188// In this implementation, we successively merge pairs of slots that are
189// not *in-use* together. We could be smarter - for example, we could merge
190// a single large slot with 2 small slots, or we could construct the
191// interference graph and run a "smart" graph coloring algorithm, but with
192// that aside, how do we find out whether a pair of slots might be *in-use*
193// together?
194//
195// From our rules, we see that *out-of-scope* slots are never *in-use*,
196// and from (L7) we see that "non-degenerate" slots remain non-*in-use*
197// until their address is taken. Therefore, we can approximate slot activity
198// using dataflow.
199//
200// A subtle point: naively, we might try to figure out which pairs of
201// stack-slots interfere by propagating `S in-use` through the CFG for every
202// stack-slot `S`, and having `S` and `T` interfere if there is a CFG point in
203// which they are both *in-use*.
204//
205// That is sound, but overly conservative in some cases: in our (artificial)
206// example `foo`, either `x` or `y` might be in use at the label `B:`, but
207// as `x` is only in use if we came in from the `var` edge and `y` only
208// if we came from the `!var` edge, they still can't be in use together.
209// See PR32488 for an important real-life case.
210//
211// If we wanted to find all points of interference precisely, we could
212// propagate `S in-use` and `S&T in-use` predicates through the CFG. That
213// would be precise, but requires propagating `O(n^2)` dataflow facts.
214//
215// However, we aren't interested in the *set* of points of interference
216// between 2 stack slots, only *whether* there *is* such a point. So we
217// can rely on a little trick: for `S` and `T` to be in-use together,
218// one of them needs to become in-use while the other is in-use (or
219// they might both become in use simultaneously). We can check this
220// by also keeping track of the points at which a stack slot might *start*
221// being in-use.
222//
223// Exact first use:
224// ----------------
225//
226// Consider the following motivating example:
227//
228// int foo() {
229// char b1[1024], b2[1024];
230// if (...) {
231// char b3[1024];
232// <uses of b1, b3>;
233// return x;
234// } else {
235// char b4[1024], b5[1024];
236// <uses of b2, b4, b5>;
237// return y;
238// }
239// }
240//
241// In the code above, "b3" and "b4" are declared in distinct lexical
242// scopes, meaning that it is easy to prove that they can share the
243// same stack slot. Variables "b1" and "b2" are declared in the same
244// scope, meaning that from a lexical point of view, their lifetimes
245// overlap. From a control flow pointer of view, however, the two
246// variables are accessed in disjoint regions of the CFG, thus it
247// should be possible for them to share the same stack slot. An ideal
248// stack allocation for the function above would look like:
249//
250// slot 0: b1, b2
251// slot 1: b3, b4
252// slot 2: b5
253//
254// Achieving this allocation is tricky, however, due to the way
255// lifetime markers are inserted. Here is a simplified view of the
256// control flow graph for the code above:
257//
258// +------ block 0 -------+
259// 0| LIFETIME_START b1, b2 |
260// 1| <test 'if' condition> |
261// +-----------------------+
262// ./ \.
263// +------ block 1 -------+ +------ block 2 -------+
264// 2| LIFETIME_START b3 | 5| LIFETIME_START b4, b5 |
265// 3| <uses of b1, b3> | 6| <uses of b2, b4, b5> |
266// 4| LIFETIME_END b3 | 7| LIFETIME_END b4, b5 |
267// +-----------------------+ +-----------------------+
268// \. /.
269// +------ block 3 -------+
270// 8| <cleanupcode> |
271// 9| LIFETIME_END b1, b2 |
272// 10| return |
273// +-----------------------+
274//
275// If we create live intervals for the variables above strictly based
276// on the lifetime markers, we'll get the set of intervals on the
277// left. If we ignore the lifetime start markers and instead treat a
278// variable's lifetime as beginning with the first reference to the
279// var, then we get the intervals on the right.
280//
281// LIFETIME_START First Use
282// b1: [0,9] [3,4] [8,9]
283// b2: [0,9] [6,9]
284// b3: [2,4] [3,4]
285// b4: [5,7] [6,7]
286// b5: [5,7] [6,7]
287//
288// For the intervals on the left, the best we can do is overlap two
289// variables (b3 and b4, for example); this gives us a stack size of
290// 4*1024 bytes, not ideal. When treating first-use as the start of a
291// lifetime, we can additionally overlap b1 and b5, giving us a 3*1024
292// byte stack (better).
293//
294// Degenerate Slots:
295// -----------------
296//
297// Relying entirely on first-use of stack slots is problematic,
298// however, due to the fact that optimizations can sometimes migrate
299// uses of a variable outside of its lifetime start/end region. Here
300// is an example:
301//
302// int bar() {
303// char b1[1024], b2[1024];
304// if (...) {
305// <uses of b2>
306// return y;
307// } else {
308// <uses of b1>
309// while (...) {
310// char b3[1024];
311// <uses of b3>
312// }
313// }
314// }
315//
316// Before optimization, the control flow graph for the code above
317// might look like the following:
318//
319// +------ block 0 -------+
320// 0| LIFETIME_START b1, b2 |
321// 1| <test 'if' condition> |
322// +-----------------------+
323// ./ \.
324// +------ block 1 -------+ +------- block 2 -------+
325// 2| <uses of b2> | 3| <uses of b1> |
326// +-----------------------+ +-----------------------+
327// | |
328// | +------- block 3 -------+ <-\.
329// | 4| <while condition> | |
330// | +-----------------------+ |
331// | / | |
332// | / +------- block 4 -------+
333// \ / 5| LIFETIME_START b3 | |
334// \ / 6| <uses of b3> | |
335// \ / 7| LIFETIME_END b3 | |
336// \ | +------------------------+ |
337// \ | \ /
338// +------ block 5 -----+ \---------------
339// 8| <cleanupcode> |
340// 9| LIFETIME_END b1, b2 |
341// 10| return |
342// +---------------------+
343//
344// During optimization, however, it can happen that an instruction
345// computing an address in "b3" (for example, a loop-invariant GEP) is
346// hoisted up out of the loop from block 4 to block 2. [Note that
347// this is not an actual load from the stack, only an instruction that
348// computes the address to be loaded]. If this happens, there is now a
349// path leading from the first use of b3 to the return instruction
350// that does not encounter the b3 LIFETIME_END, hence b3's lifetime is
351// now larger than if we were computing live intervals strictly based
352// on lifetime markers. In the example above, this lengthened lifetime
353// would mean that it would appear illegal to overlap b3 with b2.
354//
355// To deal with this such cases, the code in ::collectMarkers() below
356// tries to identify "degenerate" slots -- those slots where on a single
357// forward pass through the CFG we encounter a first reference to slot
358// K before we hit the slot K lifetime start marker. For such slots,
359// we fall back on using the lifetime start marker as the beginning of
360// the variable's lifetime. NB: with this implementation, slots can
361// appear degenerate in cases where there is unstructured control flow:
362//
363// if (q) goto mid;
364// if (x > 9) {
365// int b[100];
366// memcpy(&b[0], ...);
367// mid: b[k] = ...;
368// abc(&b);
369// }
370//
371// If in RPO ordering chosen to walk the CFG we happen to visit the b[k]
372// before visiting the memcpy block (which will contain the lifetime start
373// for "b" then it will appear that 'b' has a degenerate lifetime.
374
375namespace {
376
377/// StackColoring - A machine pass for merging disjoint stack allocations,
378/// marked by the LIFETIME_START and LIFETIME_END pseudo instructions.
379class StackColoring : public MachineFunctionPass {
380 MachineFrameInfo *MFI = nullptr;
381 MachineFunction *MF = nullptr;
382
383 /// A class representing liveness information for a single basic block.
384 /// Each bit in the BitVector represents the liveness property
385 /// for a different stack slot.
386 struct BlockLifetimeInfo {
387 /// Which slots BEGINs in each basic block.
388 BitVector Begin;
389
390 /// Which slots ENDs in each basic block.
392
393 /// Which slots are marked as LIVE_IN, coming into each basic block.
394 BitVector LiveIn;
395
396 /// Which slots are marked as LIVE_OUT, coming out of each basic block.
397 BitVector LiveOut;
398 };
399
400 /// Maps active slots (per bit) for each basic block.
402 LivenessMap BlockLiveness;
403
404 /// Maps serial numbers to basic blocks.
406
407 /// Maps basic blocks to a serial number.
409
410 /// Maps slots to their use interval. Outside of this interval, slots
411 /// values are either dead or `undef` and they will not be written to.
413
414 /// Maps slots to the points where they can become in-use.
416
417 /// VNInfo is used for the construction of LiveIntervals.
418 VNInfo::Allocator VNInfoAllocator;
419
420 /// SlotIndex analysis object.
421 SlotIndexes *Indexes = nullptr;
422
423 /// The list of lifetime markers found. These markers are to be removed
424 /// once the coloring is done.
426
427 /// Record the FI slots for which we have seen some sort of
428 /// lifetime marker (either start or end).
429 BitVector InterestingSlots;
430
431 /// FI slots that need to be handled conservatively (for these
432 /// slots lifetime-start-on-first-use is disabled).
433 BitVector ConservativeSlots;
434
435 /// Number of iterations taken during data flow analysis.
436 unsigned NumIterations;
437
438public:
439 static char ID;
440
441 StackColoring() : MachineFunctionPass(ID) {
443 }
444
445 void getAnalysisUsage(AnalysisUsage &AU) const override;
446 bool runOnMachineFunction(MachineFunction &Func) override;
447
448private:
449 /// Used in collectMarkers
451
452 /// Debug.
453 void dump() const;
454 void dumpIntervals() const;
455 void dumpBB(MachineBasicBlock *MBB) const;
456 void dumpBV(const char *tag, const BitVector &BV) const;
457
458 /// Removes all of the lifetime marker instructions from the function.
459 /// \returns true if any markers were removed.
460 bool removeAllMarkers();
461
462 /// Scan the machine function and find all of the lifetime markers.
463 /// Record the findings in the BEGIN and END vectors.
464 /// \returns the number of markers found.
465 unsigned collectMarkers(unsigned NumSlot);
466
467 /// Perform the dataflow calculation and calculate the lifetime for each of
468 /// the slots, based on the BEGIN/END vectors. Set the LifetimeLIVE_IN and
469 /// LifetimeLIVE_OUT maps that represent which stack slots are live coming
470 /// in and out blocks.
471 void calculateLocalLiveness();
472
473 /// Returns TRUE if we're using the first-use-begins-lifetime method for
474 /// this slot (if FALSE, then the start marker is treated as start of lifetime).
475 bool applyFirstUse(int Slot) {
477 return false;
478 if (ConservativeSlots.test(Slot))
479 return false;
480 return true;
481 }
482
483 /// Examines the specified instruction and returns TRUE if the instruction
484 /// represents the start or end of an interesting lifetime. The slot or slots
485 /// starting or ending are added to the vector "slots" and "isStart" is set
486 /// accordingly.
487 /// \returns True if inst contains a lifetime start or end
488 bool isLifetimeStartOrEnd(const MachineInstr &MI,
490 bool &isStart);
491
492 /// Construct the LiveIntervals for the slots.
493 void calculateLiveIntervals(unsigned NumSlots);
494
495 /// Go over the machine function and change instructions which use stack
496 /// slots to use the joint slots.
497 void remapInstructions(DenseMap<int, int> &SlotRemap);
498
499 /// The input program may contain instructions which are not inside lifetime
500 /// markers. This can happen due to a bug in the compiler or due to a bug in
501 /// user code (for example, returning a reference to a local variable).
502 /// This procedure checks all of the instructions in the function and
503 /// invalidates lifetime ranges which do not contain all of the instructions
504 /// which access that frame slot.
505 void removeInvalidSlotRanges();
506
507 /// Map entries which point to other entries to their destination.
508 /// A->B->C becomes A->C.
509 void expungeSlotMap(DenseMap<int, int> &SlotRemap, unsigned NumSlots);
510};
511
512} // end anonymous namespace
513
514char StackColoring::ID = 0;
515
516char &llvm::StackColoringID = StackColoring::ID;
517
519 "Merge disjoint stack slots", false, false)
522 "Merge disjoint stack slots", false, false)
523
524void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const {
525 AU.addRequired<SlotIndexesWrapperPass>();
527}
528
529#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
530LLVM_DUMP_METHOD void StackColoring::dumpBV(const char *tag,
531 const BitVector &BV) const {
532 dbgs() << tag << " : { ";
533 for (unsigned I = 0, E = BV.size(); I != E; ++I)
534 dbgs() << BV.test(I) << " ";
535 dbgs() << "}\n";
536}
537
538LLVM_DUMP_METHOD void StackColoring::dumpBB(MachineBasicBlock *MBB) const {
539 LivenessMap::const_iterator BI = BlockLiveness.find(MBB);
540 assert(BI != BlockLiveness.end() && "Block not found");
541 const BlockLifetimeInfo &BlockInfo = BI->second;
542
543 dumpBV("BEGIN", BlockInfo.Begin);
544 dumpBV("END", BlockInfo.End);
545 dumpBV("LIVE_IN", BlockInfo.LiveIn);
546 dumpBV("LIVE_OUT", BlockInfo.LiveOut);
547}
548
549LLVM_DUMP_METHOD void StackColoring::dump() const {
550 for (MachineBasicBlock *MBB : depth_first(MF)) {
551 dbgs() << "Inspecting block #" << MBB->getNumber() << " ["
552 << MBB->getName() << "]\n";
553 dumpBB(MBB);
554 }
555}
556
557LLVM_DUMP_METHOD void StackColoring::dumpIntervals() const {
558 for (unsigned I = 0, E = Intervals.size(); I != E; ++I) {
559 dbgs() << "Interval[" << I << "]:\n";
560 Intervals[I]->dump();
561 }
562}
563#endif
564
565static inline int getStartOrEndSlot(const MachineInstr &MI)
566{
567 assert((MI.getOpcode() == TargetOpcode::LIFETIME_START ||
568 MI.getOpcode() == TargetOpcode::LIFETIME_END) &&
569 "Expected LIFETIME_START or LIFETIME_END op");
570 const MachineOperand &MO = MI.getOperand(0);
571 int Slot = MO.getIndex();
572 if (Slot >= 0)
573 return Slot;
574 return -1;
575}
576
577// At the moment the only way to end a variable lifetime is with
578// a VARIABLE_LIFETIME op (which can't contain a start). If things
579// change and the IR allows for a single inst that both begins
580// and ends lifetime(s), this interface will need to be reworked.
581bool StackColoring::isLifetimeStartOrEnd(const MachineInstr &MI,
583 bool &isStart) {
584 if (MI.getOpcode() == TargetOpcode::LIFETIME_START ||
585 MI.getOpcode() == TargetOpcode::LIFETIME_END) {
587 if (Slot < 0)
588 return false;
589 if (!InterestingSlots.test(Slot))
590 return false;
591 slots.push_back(Slot);
592 if (MI.getOpcode() == TargetOpcode::LIFETIME_END) {
593 isStart = false;
594 return true;
595 }
596 if (!applyFirstUse(Slot)) {
597 isStart = true;
598 return true;
599 }
601 if (!MI.isDebugInstr()) {
602 bool found = false;
603 for (const MachineOperand &MO : MI.operands()) {
604 if (!MO.isFI())
605 continue;
606 int Slot = MO.getIndex();
607 if (Slot<0)
608 continue;
609 if (InterestingSlots.test(Slot) && applyFirstUse(Slot)) {
610 slots.push_back(Slot);
611 found = true;
612 }
613 }
614 if (found) {
615 isStart = true;
616 return true;
617 }
618 }
619 }
620 return false;
621}
622
623unsigned StackColoring::collectMarkers(unsigned NumSlot) {
624 unsigned MarkersFound = 0;
625 BlockBitVecMap SeenStartMap;
626 InterestingSlots.clear();
627 InterestingSlots.resize(NumSlot);
628 ConservativeSlots.clear();
629 ConservativeSlots.resize(NumSlot);
630
631 // number of start and end lifetime ops for each slot
632 SmallVector<int, 8> NumStartLifetimes(NumSlot, 0);
633 SmallVector<int, 8> NumEndLifetimes(NumSlot, 0);
634
635 // Step 1: collect markers and populate the "InterestingSlots"
636 // and "ConservativeSlots" sets.
637 for (MachineBasicBlock *MBB : depth_first(MF)) {
638 // Compute the set of slots for which we've seen a START marker but have
639 // not yet seen an END marker at this point in the walk (e.g. on entry
640 // to this bb).
641 BitVector BetweenStartEnd;
642 BetweenStartEnd.resize(NumSlot);
643 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
644 BlockBitVecMap::const_iterator I = SeenStartMap.find(Pred);
645 if (I != SeenStartMap.end()) {
646 BetweenStartEnd |= I->second;
647 }
648 }
649
650 // Walk the instructions in the block to look for start/end ops.
651 for (MachineInstr &MI : *MBB) {
652 if (MI.isDebugInstr())
653 continue;
654 if (MI.getOpcode() == TargetOpcode::LIFETIME_START ||
655 MI.getOpcode() == TargetOpcode::LIFETIME_END) {
657 if (Slot < 0)
658 continue;
659 InterestingSlots.set(Slot);
660 if (MI.getOpcode() == TargetOpcode::LIFETIME_START) {
661 BetweenStartEnd.set(Slot);
662 NumStartLifetimes[Slot] += 1;
663 } else {
664 BetweenStartEnd.reset(Slot);
665 NumEndLifetimes[Slot] += 1;
666 }
667 const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
668 if (Allocation) {
669 LLVM_DEBUG(dbgs() << "Found a lifetime ");
670 LLVM_DEBUG(dbgs() << (MI.getOpcode() == TargetOpcode::LIFETIME_START
671 ? "start"
672 : "end"));
673 LLVM_DEBUG(dbgs() << " marker for slot #" << Slot);
675 << " with allocation: " << Allocation->getName() << "\n");
676 }
677 Markers.push_back(&MI);
678 MarkersFound += 1;
679 } else {
680 for (const MachineOperand &MO : MI.operands()) {
681 if (!MO.isFI())
682 continue;
683 int Slot = MO.getIndex();
684 if (Slot < 0)
685 continue;
686 if (! BetweenStartEnd.test(Slot)) {
687 ConservativeSlots.set(Slot);
688 }
689 }
690 }
691 }
692 BitVector &SeenStart = SeenStartMap[MBB];
693 SeenStart |= BetweenStartEnd;
694 }
695 if (!MarkersFound) {
696 return 0;
697 }
698
699 // PR27903: slots with multiple start or end lifetime ops are not
700 // safe to enable for "lifetime-start-on-first-use".
701 for (unsigned slot = 0; slot < NumSlot; ++slot) {
702 if (NumStartLifetimes[slot] > 1 || NumEndLifetimes[slot] > 1)
703 ConservativeSlots.set(slot);
704 }
705
706 // The write to the catch object by the personality function is not propely
707 // modeled in IR: It happens before any cleanuppads are executed, even if the
708 // first mention of the catch object is in a catchpad. As such, mark catch
709 // object slots as conservative, so they are excluded from first-use analysis.
710 if (WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo())
711 for (WinEHTryBlockMapEntry &TBME : EHInfo->TryBlockMap)
712 for (WinEHHandlerType &H : TBME.HandlerArray)
713 if (H.CatchObj.FrameIndex != std::numeric_limits<int>::max() &&
714 H.CatchObj.FrameIndex >= 0)
715 ConservativeSlots.set(H.CatchObj.FrameIndex);
716
717 LLVM_DEBUG(dumpBV("Conservative slots", ConservativeSlots));
718
719 // Step 2: compute begin/end sets for each block
720
721 // NOTE: We use a depth-first iteration to ensure that we obtain a
722 // deterministic numbering.
723 for (MachineBasicBlock *MBB : depth_first(MF)) {
724 // Assign a serial number to this basic block.
725 BasicBlocks[MBB] = BasicBlockNumbering.size();
726 BasicBlockNumbering.push_back(MBB);
727
728 // Keep a reference to avoid repeated lookups.
729 BlockLifetimeInfo &BlockInfo = BlockLiveness[MBB];
730
731 BlockInfo.Begin.resize(NumSlot);
732 BlockInfo.End.resize(NumSlot);
733
735 for (MachineInstr &MI : *MBB) {
736 bool isStart = false;
737 slots.clear();
738 if (isLifetimeStartOrEnd(MI, slots, isStart)) {
739 if (!isStart) {
740 assert(slots.size() == 1 && "unexpected: MI ends multiple slots");
741 int Slot = slots[0];
742 if (BlockInfo.Begin.test(Slot)) {
743 BlockInfo.Begin.reset(Slot);
744 }
745 BlockInfo.End.set(Slot);
746 } else {
747 for (auto Slot : slots) {
748 LLVM_DEBUG(dbgs() << "Found a use of slot #" << Slot);
750 << " at " << printMBBReference(*MBB) << " index ");
752 const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
753 if (Allocation) {
755 << " with allocation: " << Allocation->getName());
756 }
757 LLVM_DEBUG(dbgs() << "\n");
758 if (BlockInfo.End.test(Slot)) {
759 BlockInfo.End.reset(Slot);
760 }
761 BlockInfo.Begin.set(Slot);
762 }
763 }
764 }
765 }
766 }
767
768 // Update statistics.
769 NumMarkerSeen += MarkersFound;
770 return MarkersFound;
771}
772
773void StackColoring::calculateLocalLiveness() {
774 unsigned NumIters = 0;
775 bool changed = true;
776 // Create BitVector outside the loop and reuse them to avoid repeated heap
777 // allocations.
778 BitVector LocalLiveIn;
779 BitVector LocalLiveOut;
780 while (changed) {
781 changed = false;
782 ++NumIters;
783
784 for (const MachineBasicBlock *BB : BasicBlockNumbering) {
785 // Use an iterator to avoid repeated lookups.
786 LivenessMap::iterator BI = BlockLiveness.find(BB);
787 assert(BI != BlockLiveness.end() && "Block not found");
788 BlockLifetimeInfo &BlockInfo = BI->second;
789
790 // Compute LiveIn by unioning together the LiveOut sets of all preds.
791 LocalLiveIn.clear();
792 for (MachineBasicBlock *Pred : BB->predecessors()) {
793 LivenessMap::const_iterator I = BlockLiveness.find(Pred);
794 // PR37130: transformations prior to stack coloring can
795 // sometimes leave behind statically unreachable blocks; these
796 // can be safely skipped here.
797 if (I != BlockLiveness.end())
798 LocalLiveIn |= I->second.LiveOut;
799 }
800
801 // Compute LiveOut by subtracting out lifetimes that end in this
802 // block, then adding in lifetimes that begin in this block. If
803 // we have both BEGIN and END markers in the same basic block
804 // then we know that the BEGIN marker comes after the END,
805 // because we already handle the case where the BEGIN comes
806 // before the END when collecting the markers (and building the
807 // BEGIN/END vectors).
808 LocalLiveOut = LocalLiveIn;
809 LocalLiveOut.reset(BlockInfo.End);
810 LocalLiveOut |= BlockInfo.Begin;
811
812 // Update block LiveIn set, noting whether it has changed.
813 if (LocalLiveIn.test(BlockInfo.LiveIn)) {
814 changed = true;
815 BlockInfo.LiveIn |= LocalLiveIn;
816 }
817
818 // Update block LiveOut set, noting whether it has changed.
819 if (LocalLiveOut.test(BlockInfo.LiveOut)) {
820 changed = true;
821 BlockInfo.LiveOut |= LocalLiveOut;
822 }
823 }
824 } // while changed.
825
826 NumIterations = NumIters;
827}
828
829void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
831 SmallVector<bool, 16> DefinitelyInUse;
832
833 // For each block, find which slots are active within this block
834 // and update the live intervals.
835 for (const MachineBasicBlock &MBB : *MF) {
836 Starts.clear();
837 Starts.resize(NumSlots);
838 DefinitelyInUse.clear();
839 DefinitelyInUse.resize(NumSlots);
840
841 // Start the interval of the slots that we previously found to be 'in-use'.
842 BlockLifetimeInfo &MBBLiveness = BlockLiveness[&MBB];
843 for (int pos = MBBLiveness.LiveIn.find_first(); pos != -1;
844 pos = MBBLiveness.LiveIn.find_next(pos)) {
845 Starts[pos] = Indexes->getMBBStartIdx(&MBB);
846 }
847
848 // Create the interval for the basic blocks containing lifetime begin/end.
849 for (const MachineInstr &MI : MBB) {
851 bool IsStart = false;
852 if (!isLifetimeStartOrEnd(MI, slots, IsStart))
853 continue;
854 SlotIndex ThisIndex = Indexes->getInstructionIndex(MI);
855 for (auto Slot : slots) {
856 if (IsStart) {
857 // If a slot is already definitely in use, we don't have to emit
858 // a new start marker because there is already a pre-existing
859 // one.
860 if (!DefinitelyInUse[Slot]) {
861 LiveStarts[Slot].push_back(ThisIndex);
862 DefinitelyInUse[Slot] = true;
863 }
864 if (!Starts[Slot].isValid())
865 Starts[Slot] = ThisIndex;
866 } else {
867 if (Starts[Slot].isValid()) {
868 VNInfo *VNI = Intervals[Slot]->getValNumInfo(0);
869 Intervals[Slot]->addSegment(
870 LiveInterval::Segment(Starts[Slot], ThisIndex, VNI));
871 Starts[Slot] = SlotIndex(); // Invalidate the start index
872 DefinitelyInUse[Slot] = false;
873 }
874 }
875 }
876 }
877
878 // Finish up started segments
879 for (unsigned i = 0; i < NumSlots; ++i) {
880 if (!Starts[i].isValid())
881 continue;
882
883 SlotIndex EndIdx = Indexes->getMBBEndIdx(&MBB);
884 VNInfo *VNI = Intervals[i]->getValNumInfo(0);
885 Intervals[i]->addSegment(LiveInterval::Segment(Starts[i], EndIdx, VNI));
886 }
887 }
888}
889
890bool StackColoring::removeAllMarkers() {
891 unsigned Count = 0;
892 for (MachineInstr *MI : Markers) {
893 MI->eraseFromParent();
894 Count++;
895 }
896 Markers.clear();
897
898 LLVM_DEBUG(dbgs() << "Removed " << Count << " markers.\n");
899 return Count;
900}
901
902void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
903 unsigned FixedInstr = 0;
904 unsigned FixedMemOp = 0;
905 unsigned FixedDbg = 0;
906
907 // Remap debug information that refers to stack slots.
908 for (auto &VI : MF->getVariableDbgInfo()) {
909 if (!VI.Var || !VI.inStackSlot())
910 continue;
911 int Slot = VI.getStackSlot();
912 if (SlotRemap.count(Slot)) {
913 LLVM_DEBUG(dbgs() << "Remapping debug info for ["
914 << cast<DILocalVariable>(VI.Var)->getName() << "].\n");
915 VI.updateStackSlot(SlotRemap[Slot]);
916 FixedDbg++;
917 }
918 }
919
920 // Keep a list of *allocas* which need to be remapped.
922
923 // Keep a list of allocas which has been affected by the remap.
925
926 for (const std::pair<int, int> &SI : SlotRemap) {
927 const AllocaInst *From = MFI->getObjectAllocation(SI.first);
928 const AllocaInst *To = MFI->getObjectAllocation(SI.second);
929 assert(To && From && "Invalid allocation object");
930 Allocas[From] = To;
931
932 // If From is before wo, its possible that there is a use of From between
933 // them.
934 if (From->comesBefore(To))
935 const_cast<AllocaInst*>(To)->moveBefore(const_cast<AllocaInst*>(From));
936
937 // AA might be used later for instruction scheduling, and we need it to be
938 // able to deduce the correct aliasing releationships between pointers
939 // derived from the alloca being remapped and the target of that remapping.
940 // The only safe way, without directly informing AA about the remapping
941 // somehow, is to directly update the IR to reflect the change being made
942 // here.
943 Instruction *Inst = const_cast<AllocaInst *>(To);
944 if (From->getType() != To->getType()) {
945 BitCastInst *Cast = new BitCastInst(Inst, From->getType());
946 Cast->insertAfter(Inst);
947 Inst = Cast;
948 }
949
950 // We keep both slots to maintain AliasAnalysis metadata later.
951 MergedAllocas.insert(From);
952 MergedAllocas.insert(To);
953
954 // Transfer the stack protector layout tag, but make sure that SSPLK_AddrOf
955 // does not overwrite SSPLK_SmallArray or SSPLK_LargeArray, and make sure
956 // that SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
958 = MFI->getObjectSSPLayout(SI.first);
960 if (FromKind != MachineFrameInfo::SSPLK_None &&
961 (ToKind == MachineFrameInfo::SSPLK_None ||
963 FromKind != MachineFrameInfo::SSPLK_AddrOf)))
964 MFI->setObjectSSPLayout(SI.second, FromKind);
965
966 // The new alloca might not be valid in a llvm.dbg.declare for this
967 // variable, so poison out the use to make the verifier happy.
968 AllocaInst *FromAI = const_cast<AllocaInst *>(From);
969 if (FromAI->isUsedByMetadata())
971 for (auto &Use : FromAI->uses()) {
972 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Use.get()))
973 if (BCI->isUsedByMetadata())
974 ValueAsMetadata::handleRAUW(BCI, PoisonValue::get(BCI->getType()));
975 }
976
977 // Note that this will not replace uses in MMOs (which we'll update below),
978 // or anywhere else (which is why we won't delete the original
979 // instruction).
980 FromAI->replaceAllUsesWith(Inst);
981 }
982
983 // Remap all instructions to the new stack slots.
984 std::vector<std::vector<MachineMemOperand *>> SSRefs(
985 MFI->getObjectIndexEnd());
986 for (MachineBasicBlock &BB : *MF)
987 for (MachineInstr &I : BB) {
988 // Skip lifetime markers. We'll remove them soon.
989 if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
990 I.getOpcode() == TargetOpcode::LIFETIME_END)
991 continue;
992
993 // Update the MachineMemOperand to use the new alloca.
994 for (MachineMemOperand *MMO : I.memoperands()) {
995 // We've replaced IR-level uses of the remapped allocas, so we only
996 // need to replace direct uses here.
997 const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(MMO->getValue());
998 if (!AI)
999 continue;
1000
1001 if (!Allocas.count(AI))
1002 continue;
1003
1004 MMO->setValue(Allocas[AI]);
1005 FixedMemOp++;
1006 }
1007
1008 // Update all of the machine instruction operands.
1009 for (MachineOperand &MO : I.operands()) {
1010 if (!MO.isFI())
1011 continue;
1012 int FromSlot = MO.getIndex();
1013
1014 // Don't touch arguments.
1015 if (FromSlot<0)
1016 continue;
1017
1018 // Only look at mapped slots.
1019 if (!SlotRemap.count(FromSlot))
1020 continue;
1021
1022 // In a debug build, check that the instruction that we are modifying is
1023 // inside the expected live range. If the instruction is not inside
1024 // the calculated range then it means that the alloca usage moved
1025 // outside of the lifetime markers, or that the user has a bug.
1026 // NOTE: Alloca address calculations which happen outside the lifetime
1027 // zone are okay, despite the fact that we don't have a good way
1028 // for validating all of the usages of the calculation.
1029#ifndef NDEBUG
1030 bool TouchesMemory = I.mayLoadOrStore();
1031 // If we *don't* protect the user from escaped allocas, don't bother
1032 // validating the instructions.
1033 if (!I.isDebugInstr() && TouchesMemory && ProtectFromEscapedAllocas) {
1035 const LiveInterval *Interval = &*Intervals[FromSlot];
1036 assert(Interval->find(Index) != Interval->end() &&
1037 "Found instruction usage outside of live range.");
1038 }
1039#endif
1040
1041 // Fix the machine instructions.
1042 int ToSlot = SlotRemap[FromSlot];
1043 MO.setIndex(ToSlot);
1044 FixedInstr++;
1045 }
1046
1047 // We adjust AliasAnalysis information for merged stack slots.
1049 bool ReplaceMemOps = false;
1050 for (MachineMemOperand *MMO : I.memoperands()) {
1051 // Collect MachineMemOperands which reference
1052 // FixedStackPseudoSourceValues with old frame indices.
1053 if (const auto *FSV = dyn_cast_or_null<FixedStackPseudoSourceValue>(
1054 MMO->getPseudoValue())) {
1055 int FI = FSV->getFrameIndex();
1056 auto To = SlotRemap.find(FI);
1057 if (To != SlotRemap.end())
1058 SSRefs[FI].push_back(MMO);
1059 }
1060
1061 // If this memory location can be a slot remapped here,
1062 // we remove AA information.
1063 bool MayHaveConflictingAAMD = false;
1064 if (MMO->getAAInfo()) {
1065 if (const Value *MMOV = MMO->getValue()) {
1068
1069 if (Objs.empty())
1070 MayHaveConflictingAAMD = true;
1071 else
1072 for (Value *V : Objs) {
1073 // If this memory location comes from a known stack slot
1074 // that is not remapped, we continue checking.
1075 // Otherwise, we need to invalidate AA infomation.
1076 const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(V);
1077 if (AI && MergedAllocas.count(AI)) {
1078 MayHaveConflictingAAMD = true;
1079 break;
1080 }
1081 }
1082 }
1083 }
1084 if (MayHaveConflictingAAMD) {
1085 NewMMOs.push_back(MF->getMachineMemOperand(MMO, AAMDNodes()));
1086 ReplaceMemOps = true;
1087 } else {
1088 NewMMOs.push_back(MMO);
1089 }
1090 }
1091
1092 // If any memory operand is updated, set memory references of
1093 // this instruction.
1094 if (ReplaceMemOps)
1095 I.setMemRefs(*MF, NewMMOs);
1096 }
1097
1098 // Rewrite MachineMemOperands that reference old frame indices.
1099 for (auto E : enumerate(SSRefs))
1100 if (!E.value().empty()) {
1101 const PseudoSourceValue *NewSV =
1102 MF->getPSVManager().getFixedStack(SlotRemap.find(E.index())->second);
1103 for (MachineMemOperand *Ref : E.value())
1104 Ref->setValue(NewSV);
1105 }
1106
1107 // Update the location of C++ catch objects for the MSVC personality routine.
1108 if (WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo())
1109 for (WinEHTryBlockMapEntry &TBME : EHInfo->TryBlockMap)
1110 for (WinEHHandlerType &H : TBME.HandlerArray)
1111 if (H.CatchObj.FrameIndex != std::numeric_limits<int>::max() &&
1112 SlotRemap.count(H.CatchObj.FrameIndex))
1113 H.CatchObj.FrameIndex = SlotRemap[H.CatchObj.FrameIndex];
1114
1115 LLVM_DEBUG(dbgs() << "Fixed " << FixedMemOp << " machine memory operands.\n");
1116 LLVM_DEBUG(dbgs() << "Fixed " << FixedDbg << " debug locations.\n");
1117 LLVM_DEBUG(dbgs() << "Fixed " << FixedInstr << " machine instructions.\n");
1118 (void) FixedMemOp;
1119 (void) FixedDbg;
1120 (void) FixedInstr;
1121}
1122
1123void StackColoring::removeInvalidSlotRanges() {
1124 for (MachineBasicBlock &BB : *MF)
1125 for (MachineInstr &I : BB) {
1126 if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
1127 I.getOpcode() == TargetOpcode::LIFETIME_END || I.isDebugInstr())
1128 continue;
1129
1130 // Some intervals are suspicious! In some cases we find address
1131 // calculations outside of the lifetime zone, but not actual memory
1132 // read or write. Memory accesses outside of the lifetime zone are a clear
1133 // violation, but address calculations are okay. This can happen when
1134 // GEPs are hoisted outside of the lifetime zone.
1135 // So, in here we only check instructions which can read or write memory.
1136 if (!I.mayLoad() && !I.mayStore())
1137 continue;
1138
1139 // Check all of the machine operands.
1140 for (const MachineOperand &MO : I.operands()) {
1141 if (!MO.isFI())
1142 continue;
1143
1144 int Slot = MO.getIndex();
1145
1146 if (Slot<0)
1147 continue;
1148
1149 if (Intervals[Slot]->empty())
1150 continue;
1151
1152 // Check that the used slot is inside the calculated lifetime range.
1153 // If it is not, warn about it and invalidate the range.
1154 LiveInterval *Interval = &*Intervals[Slot];
1156 if (Interval->find(Index) == Interval->end()) {
1157 Interval->clear();
1158 LLVM_DEBUG(dbgs() << "Invalidating range #" << Slot << "\n");
1159 EscapedAllocas++;
1160 }
1161 }
1162 }
1163}
1164
1165void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
1166 unsigned NumSlots) {
1167 // Expunge slot remap map.
1168 for (unsigned i=0; i < NumSlots; ++i) {
1169 // If we are remapping i
1170 if (SlotRemap.count(i)) {
1171 int Target = SlotRemap[i];
1172 // As long as our target is mapped to something else, follow it.
1173 while (SlotRemap.count(Target)) {
1174 Target = SlotRemap[Target];
1175 SlotRemap[i] = Target;
1176 }
1177 }
1178 }
1179}
1180
1181bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
1182 LLVM_DEBUG(dbgs() << "********** Stack Coloring **********\n"
1183 << "********** Function: " << Func.getName() << '\n');
1184 MF = &Func;
1185 MFI = &MF->getFrameInfo();
1186 Indexes = &getAnalysis<SlotIndexesWrapperPass>().getSI();
1187 BlockLiveness.clear();
1188 BasicBlocks.clear();
1189 BasicBlockNumbering.clear();
1190 Markers.clear();
1191 Intervals.clear();
1192 LiveStarts.clear();
1193 VNInfoAllocator.Reset();
1194
1195 unsigned NumSlots = MFI->getObjectIndexEnd();
1196
1197 // If there are no stack slots then there are no markers to remove.
1198 if (!NumSlots)
1199 return false;
1200
1201 SmallVector<int, 8> SortedSlots;
1202 SortedSlots.reserve(NumSlots);
1203 Intervals.reserve(NumSlots);
1204 LiveStarts.resize(NumSlots);
1205
1206 unsigned NumMarkers = collectMarkers(NumSlots);
1207
1208 unsigned TotalSize = 0;
1209 LLVM_DEBUG(dbgs() << "Found " << NumMarkers << " markers and " << NumSlots
1210 << " slots\n");
1211 LLVM_DEBUG(dbgs() << "Slot structure:\n");
1212
1213 for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
1214 LLVM_DEBUG(dbgs() << "Slot #" << i << " - " << MFI->getObjectSize(i)
1215 << " bytes.\n");
1216 TotalSize += MFI->getObjectSize(i);
1217 }
1218
1219 LLVM_DEBUG(dbgs() << "Total Stack size: " << TotalSize << " bytes\n\n");
1220
1221 // Don't continue because there are not enough lifetime markers, or the
1222 // stack is too small, or we are told not to optimize the slots.
1223 if (NumMarkers < 2 || TotalSize < 16 || DisableColoring ||
1224 skipFunction(Func.getFunction())) {
1225 LLVM_DEBUG(dbgs() << "Will not try to merge slots.\n");
1226 return removeAllMarkers();
1227 }
1228
1229 for (unsigned i=0; i < NumSlots; ++i) {
1230 std::unique_ptr<LiveInterval> LI(new LiveInterval(i, 0));
1231 LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
1232 Intervals.push_back(std::move(LI));
1233 SortedSlots.push_back(i);
1234 }
1235
1236 // Calculate the liveness of each block.
1237 calculateLocalLiveness();
1238 LLVM_DEBUG(dbgs() << "Dataflow iterations: " << NumIterations << "\n");
1239 LLVM_DEBUG(dump());
1240
1241 // Propagate the liveness information.
1242 calculateLiveIntervals(NumSlots);
1243 LLVM_DEBUG(dumpIntervals());
1244
1245 // Search for allocas which are used outside of the declared lifetime
1246 // markers.
1248 removeInvalidSlotRanges();
1249
1250 // Maps old slots to new slots.
1251 DenseMap<int, int> SlotRemap;
1252 unsigned RemovedSlots = 0;
1253 unsigned ReducedSize = 0;
1254
1255 // Do not bother looking at empty intervals.
1256 for (unsigned I = 0; I < NumSlots; ++I) {
1257 if (Intervals[SortedSlots[I]]->empty())
1258 SortedSlots[I] = -1;
1259 }
1260
1261 // This is a simple greedy algorithm for merging allocas. First, sort the
1262 // slots, placing the largest slots first. Next, perform an n^2 scan and look
1263 // for disjoint slots. When you find disjoint slots, merge the smaller one
1264 // into the bigger one and update the live interval. Remove the small alloca
1265 // and continue.
1266
1267 // Sort the slots according to their size. Place unused slots at the end.
1268 // Use stable sort to guarantee deterministic code generation.
1269 llvm::stable_sort(SortedSlots, [this](int LHS, int RHS) {
1270 // We use -1 to denote a uninteresting slot. Place these slots at the end.
1271 if (LHS == -1)
1272 return false;
1273 if (RHS == -1)
1274 return true;
1275 // Sort according to size.
1276 return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS);
1277 });
1278
1279 for (auto &s : LiveStarts)
1280 llvm::sort(s);
1281
1282 bool Changed = true;
1283 while (Changed) {
1284 Changed = false;
1285 for (unsigned I = 0; I < NumSlots; ++I) {
1286 if (SortedSlots[I] == -1)
1287 continue;
1288
1289 for (unsigned J=I+1; J < NumSlots; ++J) {
1290 if (SortedSlots[J] == -1)
1291 continue;
1292
1293 int FirstSlot = SortedSlots[I];
1294 int SecondSlot = SortedSlots[J];
1295
1296 // Objects with different stack IDs cannot be merged.
1297 if (MFI->getStackID(FirstSlot) != MFI->getStackID(SecondSlot))
1298 continue;
1299
1300 LiveInterval *First = &*Intervals[FirstSlot];
1301 LiveInterval *Second = &*Intervals[SecondSlot];
1302 auto &FirstS = LiveStarts[FirstSlot];
1303 auto &SecondS = LiveStarts[SecondSlot];
1304 assert(!First->empty() && !Second->empty() && "Found an empty range");
1305
1306 // Merge disjoint slots. This is a little bit tricky - see the
1307 // Implementation Notes section for an explanation.
1308 if (!First->isLiveAtIndexes(SecondS) &&
1309 !Second->isLiveAtIndexes(FirstS)) {
1310 Changed = true;
1311 First->MergeSegmentsInAsValue(*Second, First->getValNumInfo(0));
1312
1313 int OldSize = FirstS.size();
1314 FirstS.append(SecondS.begin(), SecondS.end());
1315 auto Mid = FirstS.begin() + OldSize;
1316 std::inplace_merge(FirstS.begin(), Mid, FirstS.end());
1317
1318 SlotRemap[SecondSlot] = FirstSlot;
1319 SortedSlots[J] = -1;
1320 LLVM_DEBUG(dbgs() << "Merging #" << FirstSlot << " and slots #"
1321 << SecondSlot << " together.\n");
1322 Align MaxAlignment = std::max(MFI->getObjectAlign(FirstSlot),
1323 MFI->getObjectAlign(SecondSlot));
1324
1325 assert(MFI->getObjectSize(FirstSlot) >=
1326 MFI->getObjectSize(SecondSlot) &&
1327 "Merging a small object into a larger one");
1328
1329 RemovedSlots+=1;
1330 ReducedSize += MFI->getObjectSize(SecondSlot);
1331 MFI->setObjectAlignment(FirstSlot, MaxAlignment);
1332 MFI->RemoveStackObject(SecondSlot);
1333 }
1334 }
1335 }
1336 }// While changed.
1337
1338 // Record statistics.
1339 StackSpaceSaved += ReducedSize;
1340 StackSlotMerged += RemovedSlots;
1341 LLVM_DEBUG(dbgs() << "Merge " << RemovedSlots << " slots. Saved "
1342 << ReducedSize << " bytes\n");
1343
1344 // Scan the entire function and update all machine operands that use frame
1345 // indices to use the remapped frame index.
1346 if (!SlotRemap.empty()) {
1347 expungeSlotMap(SlotRemap, NumSlots);
1348 remapInstructions(SlotRemap);
1349 }
1350
1351 return removeAllMarkers();
1352}
MachineBasicBlock & MBB
This file implements the BitVector class.
BlockVerifier::State From
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:533
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
bool End
Definition: ELF_riscv.cpp:480
IRTranslator LLVM IR MI
This defines the Use class.
#define I(x, y, z)
Definition: MD5.cpp:58
#define H(x, y, z)
Definition: MD5.cpp:57
std::pair< uint64_t, uint64_t > Interval
This file contains the declarations for metadata subclasses.
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:57
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
R600 Clause Merge
R600 Emit Clause Markers
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static int getStartOrEndSlot(const MachineInstr &MI)
static cl::opt< bool > DisableColoring("no-stack-coloring", cl::init(false), cl::Hidden, cl::desc("Disable stack coloring"))
static cl::opt< bool > ProtectFromEscapedAllocas("protect-from-escaped-allocas", cl::init(false), cl::Hidden, cl::desc("Do not optimize lifetime zones that " "are broken"))
The user may write code that uses allocas outside of the declared lifetime zone.
static cl::opt< bool > LifetimeStartOnFirstUse("stackcoloring-lifetime-start-on-first-use", cl::init(true), cl::Hidden, cl::desc("Treat stack lifetimes as starting on first use, not on START marker."))
Enable enhanced dataflow scheme for lifetime analysis (treat first use of stack slot as start of slot...
#define DEBUG_TYPE
Merge disjoint stack slots
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:166
an instruction to allocate memory on the stack
Definition: Instructions.h:61
PointerType * getType() const
Overload to return most specific pointer type.
Definition: Instructions.h:97
Represent the analysis usage information of a pass.
This class represents a no-op cast from one type to another.
bool test(unsigned Idx) const
Definition: BitVector.h:461
BitVector & reset()
Definition: BitVector.h:392
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
Definition: BitVector.h:341
void clear()
clear - Removes all bits from the bitvector.
Definition: BitVector.h:335
BitVector & set()
Definition: BitVector.h:351
size_type size() const
size - Returns the number of bits in this bitvector.
Definition: BitVector.h:159
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:66
void Reset()
Deallocate all but the current slab and reset the current pointer to the beginning of it,...
Definition: Allocator.h:123
bool empty() const
Definition: DenseMap.h:98
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:151
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:687
bool isLiveAtIndexes(ArrayRef< SlotIndex > Slots) const
bool empty() const
Definition: LiveInterval.h:382
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
iterator_range< pred_iterator > predecessors()
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
SSPLayoutKind getObjectSSPLayout(int ObjectIdx) const
const AllocaInst * getObjectAllocation(int ObjectIdx) const
Return the underlying Alloca of the specified stack object if it exists.
SSPLayoutKind
Stack Smashing Protection (SSP) rules require that vulnerable stack allocations are located close the...
@ SSPLK_LargeArray
Array or nested array >= SSP-buffer-size.
@ SSPLK_AddrOf
The address of this allocation is exposed and triggered protection.
@ SSPLK_None
Did not trigger a stack protector.
void setObjectSSPLayout(int ObjectIdx, SSPLayoutKind Kind)
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
void RemoveStackObject(int ObjectIdx)
Remove or mark dead a statically sized stack object.
int getObjectIndexEnd() const
Return one past the maximum frame object index.
uint8_t getStackID(int ObjectIdx) const
void setObjectAlignment(int ObjectIdx, Align Alignment)
setObjectAlignment - Change the alignment of the specified stack object.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const WinEHFuncInfo * getWinEHFuncInfo() const
getWinEHFuncInfo - Return information about how the current function uses Windows exception handling.
Representation of each machine instruction.
Definition: MachineInstr.h:69
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void dump() const
Definition: Pass.cpp:136
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1852
Special value supplied for machine level alias analysis.
SlotIndex - An opaque wrapper around machine indexes.
Definition: SlotIndexes.h:65
void print(raw_ostream &os) const
Print this index to the given raw_ostream.
SlotIndexes pass.
Definition: SlotIndexes.h:297
SlotIndex getMBBEndIdx(unsigned Num) const
Returns the last index in the given basic block number.
Definition: SlotIndexes.h:470
SlotIndex getInstructionIndex(const MachineInstr &MI, bool IgnoreBundle=false) const
Returns the base index for the given instruction.
Definition: SlotIndexes.h:379
SlotIndex getMBBStartIdx(unsigned Num) const
Returns the first index in the given basic block number.
Definition: SlotIndexes.h:460
SlotIndex getZeroIndex()
Returns the zero index for this analysis.
Definition: SlotIndexes.h:362
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:435
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:367
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:502
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
void reserve(size_type N)
Definition: SmallVector.h:676
void resize(size_type N)
Definition: SmallVector.h:651
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
Target - Wrapper for Target specific information.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
Value * get() const
Definition: Use.h:66
VNInfo - Value Number Information.
Definition: LiveInterval.h:53
static void handleRAUW(Value *From, Value *To)
Definition: Metadata.cpp:544
LLVM Value Representation.
Definition: Value.h:74
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
bool isUsedByMetadata() const
Return true if there is metadata referencing this value.
Definition: Value.h:557
iterator_range< use_iterator > uses()
Definition: Value.h:376
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
NodeAddr< FuncNode * > Func
Definition: RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
void stable_sort(R &&Range)
Definition: STLExtras.h:2020
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition: STLExtras.h:2431
void initializeStackColoringPass(PassRegistry &)
bool getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value * > &Objects)
This is a wrapper around getUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1647
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
char & StackColoringID
StackSlotColoring - This pass performs stack coloring and merging.
@ Ref
The access may reference the value stored in memory.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
iterator_range< df_iterator< T > > depth_first(const T &G)
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:760
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
This represents a simple continuous liveness interval for a value.
Definition: LiveInterval.h:162
SmallVector< WinEHHandlerType, 1 > HandlerArray
Definition: WinEHFuncInfo.h:76