12cab237bSDimitry Andric //===- StackColoring.cpp --------------------------------------------------===//
23861d79fSDimitry Andric //
33861d79fSDimitry Andric // The LLVM Compiler Infrastructure
43861d79fSDimitry Andric //
53861d79fSDimitry Andric // This file is distributed under the University of Illinois Open Source
63861d79fSDimitry Andric // License. See LICENSE.TXT for details.
73861d79fSDimitry Andric //
83861d79fSDimitry Andric //===----------------------------------------------------------------------===//
93861d79fSDimitry Andric //
103861d79fSDimitry Andric // This pass implements the stack-coloring optimization that looks for
113861d79fSDimitry Andric // lifetime markers machine instructions (LIFESTART_BEGIN and LIFESTART_END),
123861d79fSDimitry Andric // which represent the possible lifetime of stack slots. It attempts to
133861d79fSDimitry Andric // merge disjoint stack slots and reduce the used stack space.
143861d79fSDimitry Andric // NOTE: This pass is not StackSlotColoring, which optimizes spill slots.
153861d79fSDimitry Andric //
163861d79fSDimitry Andric // TODO: In the future we plan to improve stack coloring in the following ways:
173861d79fSDimitry Andric // 1. Allow merging multiple small slots into a single larger slot at different
183861d79fSDimitry Andric // offsets.
193861d79fSDimitry Andric // 2. Merge this pass with StackSlotColoring and allow merging of allocas with
203861d79fSDimitry Andric // spill slots.
213861d79fSDimitry Andric //
223861d79fSDimitry Andric //===----------------------------------------------------------------------===//
233861d79fSDimitry Andric
243861d79fSDimitry Andric #include "llvm/ADT/BitVector.h"
252cab237bSDimitry Andric #include "llvm/ADT/DenseMap.h"
263861d79fSDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
273861d79fSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
282cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
293861d79fSDimitry Andric #include "llvm/ADT/Statistic.h"
30139f7f9bSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
313861d79fSDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
32139f7f9bSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
33139f7f9bSDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
342cab237bSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
353861d79fSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
362cab237bSDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
37139f7f9bSDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
382cab237bSDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
393ca95b02SDimitry Andric #include "llvm/CodeGen/Passes.h"
409dc417c3SDimitry Andric #include "llvm/CodeGen/SelectionDAGNodes.h"
413861d79fSDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
422cab237bSDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
43444ed5c5SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h"
444ba319b5SDimitry Andric #include "llvm/Config/llvm-config.h"
452cab237bSDimitry Andric #include "llvm/IR/Constants.h"
462cab237bSDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
47139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
48139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
492cab237bSDimitry Andric #include "llvm/IR/Metadata.h"
502cab237bSDimitry Andric #include "llvm/IR/Use.h"
512cab237bSDimitry Andric #include "llvm/IR/Value.h"
522cab237bSDimitry Andric #include "llvm/Pass.h"
532cab237bSDimitry Andric #include "llvm/Support/Casting.h"
543861d79fSDimitry Andric #include "llvm/Support/CommandLine.h"
552cab237bSDimitry Andric #include "llvm/Support/Compiler.h"
563861d79fSDimitry Andric #include "llvm/Support/Debug.h"
573861d79fSDimitry Andric #include "llvm/Support/raw_ostream.h"
582cab237bSDimitry Andric #include <algorithm>
592cab237bSDimitry Andric #include <cassert>
602cab237bSDimitry Andric #include <limits>
612cab237bSDimitry Andric #include <memory>
622cab237bSDimitry Andric #include <utility>
633861d79fSDimitry Andric
643861d79fSDimitry Andric using namespace llvm;
653861d79fSDimitry Andric
66302affcbSDimitry Andric #define DEBUG_TYPE "stack-coloring"
6791bc56edSDimitry Andric
683861d79fSDimitry Andric static cl::opt<bool>
693861d79fSDimitry Andric DisableColoring("no-stack-coloring",
703861d79fSDimitry Andric cl::init(false), cl::Hidden,
713861d79fSDimitry Andric cl::desc("Disable stack coloring"));
723861d79fSDimitry Andric
733861d79fSDimitry Andric /// The user may write code that uses allocas outside of the declared lifetime
743861d79fSDimitry Andric /// zone. This can happen when the user returns a reference to a local
753861d79fSDimitry Andric /// data-structure. We can detect these cases and decide not to optimize the
763ca95b02SDimitry Andric /// code. If this flag is enabled, we try to save the user. This option
773ca95b02SDimitry Andric /// is treated as overriding LifetimeStartOnFirstUse below.
783861d79fSDimitry Andric static cl::opt<bool>
793861d79fSDimitry Andric ProtectFromEscapedAllocas("protect-from-escaped-allocas",
803861d79fSDimitry Andric cl::init(false), cl::Hidden,
81139f7f9bSDimitry Andric cl::desc("Do not optimize lifetime zones that "
82139f7f9bSDimitry Andric "are broken"));
833861d79fSDimitry Andric
843ca95b02SDimitry Andric /// Enable enhanced dataflow scheme for lifetime analysis (treat first
853ca95b02SDimitry Andric /// use of stack slot as start of slot lifetime, as opposed to looking
863ca95b02SDimitry Andric /// for LIFETIME_START marker). See "Implementation notes" below for
873ca95b02SDimitry Andric /// more info.
883ca95b02SDimitry Andric static cl::opt<bool>
893ca95b02SDimitry Andric LifetimeStartOnFirstUse("stackcoloring-lifetime-start-on-first-use",
903ca95b02SDimitry Andric cl::init(true), cl::Hidden,
913ca95b02SDimitry Andric cl::desc("Treat stack lifetimes as starting on first use, not on START marker."));
923ca95b02SDimitry Andric
933ca95b02SDimitry Andric
943861d79fSDimitry Andric STATISTIC(NumMarkerSeen, "Number of lifetime markers found.");
953861d79fSDimitry Andric STATISTIC(StackSpaceSaved, "Number of bytes saved due to merging slots.");
963861d79fSDimitry Andric STATISTIC(StackSlotMerged, "Number of stack slot merged.");
97139f7f9bSDimitry Andric STATISTIC(EscapedAllocas, "Number of allocas that escaped the lifetime region");
983861d79fSDimitry Andric
9924d58133SDimitry Andric //===----------------------------------------------------------------------===//
10024d58133SDimitry Andric // StackColoring Pass
10124d58133SDimitry Andric //===----------------------------------------------------------------------===//
10224d58133SDimitry Andric //
10324d58133SDimitry Andric // Stack Coloring reduces stack usage by merging stack slots when they
10424d58133SDimitry Andric // can't be used together. For example, consider the following C program:
10524d58133SDimitry Andric //
10624d58133SDimitry Andric // void bar(char *, int);
10724d58133SDimitry Andric // void foo(bool var) {
10824d58133SDimitry Andric // A: {
10924d58133SDimitry Andric // char z[4096];
11024d58133SDimitry Andric // bar(z, 0);
11124d58133SDimitry Andric // }
11224d58133SDimitry Andric //
11324d58133SDimitry Andric // char *p;
11424d58133SDimitry Andric // char x[4096];
11524d58133SDimitry Andric // char y[4096];
11624d58133SDimitry Andric // if (var) {
11724d58133SDimitry Andric // p = x;
11824d58133SDimitry Andric // } else {
11924d58133SDimitry Andric // bar(y, 1);
12024d58133SDimitry Andric // p = y + 1024;
12124d58133SDimitry Andric // }
12224d58133SDimitry Andric // B:
12324d58133SDimitry Andric // bar(p, 2);
12424d58133SDimitry Andric // }
12524d58133SDimitry Andric //
12624d58133SDimitry Andric // Naively-compiled, this program would use 12k of stack space. However, the
12724d58133SDimitry Andric // stack slot corresponding to `z` is always destroyed before either of the
12824d58133SDimitry Andric // stack slots for `x` or `y` are used, and then `x` is only used if `var`
12924d58133SDimitry Andric // is true, while `y` is only used if `var` is false. So in no time are 2
13024d58133SDimitry Andric // of the stack slots used together, and therefore we can merge them,
13124d58133SDimitry Andric // compiling the function using only a single 4k alloca:
13224d58133SDimitry Andric //
13324d58133SDimitry Andric // void foo(bool var) { // equivalent
13424d58133SDimitry Andric // char x[4096];
13524d58133SDimitry Andric // char *p;
13624d58133SDimitry Andric // bar(x, 0);
13724d58133SDimitry Andric // if (var) {
13824d58133SDimitry Andric // p = x;
13924d58133SDimitry Andric // } else {
14024d58133SDimitry Andric // bar(x, 1);
14124d58133SDimitry Andric // p = x + 1024;
14224d58133SDimitry Andric // }
14324d58133SDimitry Andric // bar(p, 2);
14424d58133SDimitry Andric // }
14524d58133SDimitry Andric //
14624d58133SDimitry Andric // This is an important optimization if we want stack space to be under
14724d58133SDimitry Andric // control in large functions, both open-coded ones and ones created by
14824d58133SDimitry Andric // inlining.
1493ca95b02SDimitry Andric //
1503ca95b02SDimitry Andric // Implementation Notes:
1513ca95b02SDimitry Andric // ---------------------
1523ca95b02SDimitry Andric //
15324d58133SDimitry Andric // An important part of the above reasoning is that `z` can't be accessed
15424d58133SDimitry Andric // while the latter 2 calls to `bar` are running. This is justified because
15524d58133SDimitry Andric // `z`'s lifetime is over after we exit from block `A:`, so any further
15624d58133SDimitry Andric // accesses to it would be UB. The way we represent this information
15724d58133SDimitry Andric // in LLVM is by having frontends delimit blocks with `lifetime.start`
15824d58133SDimitry Andric // and `lifetime.end` intrinsics.
15924d58133SDimitry Andric //
16024d58133SDimitry Andric // The effect of these intrinsics seems to be as follows (maybe I should
16124d58133SDimitry Andric // specify this in the reference?):
16224d58133SDimitry Andric //
16324d58133SDimitry Andric // L1) at start, each stack-slot is marked as *out-of-scope*, unless no
16424d58133SDimitry Andric // lifetime intrinsic refers to that stack slot, in which case
16524d58133SDimitry Andric // it is marked as *in-scope*.
16624d58133SDimitry Andric // L2) on a `lifetime.start`, a stack slot is marked as *in-scope* and
16724d58133SDimitry Andric // the stack slot is overwritten with `undef`.
16824d58133SDimitry Andric // L3) on a `lifetime.end`, a stack slot is marked as *out-of-scope*.
16924d58133SDimitry Andric // L4) on function exit, all stack slots are marked as *out-of-scope*.
17024d58133SDimitry Andric // L5) `lifetime.end` is a no-op when called on a slot that is already
17124d58133SDimitry Andric // *out-of-scope*.
17224d58133SDimitry Andric // L6) memory accesses to *out-of-scope* stack slots are UB.
17324d58133SDimitry Andric // L7) when a stack-slot is marked as *out-of-scope*, all pointers to it
17424d58133SDimitry Andric // are invalidated, unless the slot is "degenerate". This is used to
17524d58133SDimitry Andric // justify not marking slots as in-use until the pointer to them is
17624d58133SDimitry Andric // used, but feels a bit hacky in the presence of things like LICM. See
17724d58133SDimitry Andric // the "Degenerate Slots" section for more details.
17824d58133SDimitry Andric //
17924d58133SDimitry Andric // Now, let's ground stack coloring on these rules. We'll define a slot
18024d58133SDimitry Andric // as *in-use* at a (dynamic) point in execution if it either can be
18124d58133SDimitry Andric // written to at that point, or if it has a live and non-undef content
18224d58133SDimitry Andric // at that point.
18324d58133SDimitry Andric //
18424d58133SDimitry Andric // Obviously, slots that are never *in-use* together can be merged, and
18524d58133SDimitry Andric // in our example `foo`, the slots for `x`, `y` and `z` are never
18624d58133SDimitry Andric // in-use together (of course, sometimes slots that *are* in-use together
18724d58133SDimitry Andric // might still be mergable, but we don't care about that here).
18824d58133SDimitry Andric //
18924d58133SDimitry Andric // In this implementation, we successively merge pairs of slots that are
19024d58133SDimitry Andric // not *in-use* together. We could be smarter - for example, we could merge
19124d58133SDimitry Andric // a single large slot with 2 small slots, or we could construct the
19224d58133SDimitry Andric // interference graph and run a "smart" graph coloring algorithm, but with
19324d58133SDimitry Andric // that aside, how do we find out whether a pair of slots might be *in-use*
19424d58133SDimitry Andric // together?
19524d58133SDimitry Andric //
19624d58133SDimitry Andric // From our rules, we see that *out-of-scope* slots are never *in-use*,
19724d58133SDimitry Andric // and from (L7) we see that "non-degenerate" slots remain non-*in-use*
19824d58133SDimitry Andric // until their address is taken. Therefore, we can approximate slot activity
19924d58133SDimitry Andric // using dataflow.
20024d58133SDimitry Andric //
20124d58133SDimitry Andric // A subtle point: naively, we might try to figure out which pairs of
20224d58133SDimitry Andric // stack-slots interfere by propagating `S in-use` through the CFG for every
20324d58133SDimitry Andric // stack-slot `S`, and having `S` and `T` interfere if there is a CFG point in
20424d58133SDimitry Andric // which they are both *in-use*.
20524d58133SDimitry Andric //
20624d58133SDimitry Andric // That is sound, but overly conservative in some cases: in our (artificial)
20724d58133SDimitry Andric // example `foo`, either `x` or `y` might be in use at the label `B:`, but
20824d58133SDimitry Andric // as `x` is only in use if we came in from the `var` edge and `y` only
20924d58133SDimitry Andric // if we came from the `!var` edge, they still can't be in use together.
21024d58133SDimitry Andric // See PR32488 for an important real-life case.
21124d58133SDimitry Andric //
21224d58133SDimitry Andric // If we wanted to find all points of interference precisely, we could
21324d58133SDimitry Andric // propagate `S in-use` and `S&T in-use` predicates through the CFG. That
21424d58133SDimitry Andric // would be precise, but requires propagating `O(n^2)` dataflow facts.
21524d58133SDimitry Andric //
21624d58133SDimitry Andric // However, we aren't interested in the *set* of points of interference
21724d58133SDimitry Andric // between 2 stack slots, only *whether* there *is* such a point. So we
21824d58133SDimitry Andric // can rely on a little trick: for `S` and `T` to be in-use together,
21924d58133SDimitry Andric // one of them needs to become in-use while the other is in-use (or
22024d58133SDimitry Andric // they might both become in use simultaneously). We can check this
22124d58133SDimitry Andric // by also keeping track of the points at which a stack slot might *start*
22224d58133SDimitry Andric // being in-use.
22324d58133SDimitry Andric //
22424d58133SDimitry Andric // Exact first use:
22524d58133SDimitry Andric // ----------------
22624d58133SDimitry Andric //
2273ca95b02SDimitry Andric // Consider the following motivating example:
2283ca95b02SDimitry Andric //
2293ca95b02SDimitry Andric // int foo() {
2303ca95b02SDimitry Andric // char b1[1024], b2[1024];
2313ca95b02SDimitry Andric // if (...) {
2323ca95b02SDimitry Andric // char b3[1024];
2333ca95b02SDimitry Andric // <uses of b1, b3>;
2343ca95b02SDimitry Andric // return x;
2353ca95b02SDimitry Andric // } else {
2363ca95b02SDimitry Andric // char b4[1024], b5[1024];
2373ca95b02SDimitry Andric // <uses of b2, b4, b5>;
2383ca95b02SDimitry Andric // return y;
2393ca95b02SDimitry Andric // }
2403ca95b02SDimitry Andric // }
2413ca95b02SDimitry Andric //
2423ca95b02SDimitry Andric // In the code above, "b3" and "b4" are declared in distinct lexical
2433ca95b02SDimitry Andric // scopes, meaning that it is easy to prove that they can share the
2443ca95b02SDimitry Andric // same stack slot. Variables "b1" and "b2" are declared in the same
2453ca95b02SDimitry Andric // scope, meaning that from a lexical point of view, their lifetimes
2463ca95b02SDimitry Andric // overlap. From a control flow pointer of view, however, the two
2473ca95b02SDimitry Andric // variables are accessed in disjoint regions of the CFG, thus it
2483ca95b02SDimitry Andric // should be possible for them to share the same stack slot. An ideal
2493ca95b02SDimitry Andric // stack allocation for the function above would look like:
2503ca95b02SDimitry Andric //
2513ca95b02SDimitry Andric // slot 0: b1, b2
2523ca95b02SDimitry Andric // slot 1: b3, b4
2533ca95b02SDimitry Andric // slot 2: b5
2543ca95b02SDimitry Andric //
2553ca95b02SDimitry Andric // Achieving this allocation is tricky, however, due to the way
2563ca95b02SDimitry Andric // lifetime markers are inserted. Here is a simplified view of the
2573ca95b02SDimitry Andric // control flow graph for the code above:
2583ca95b02SDimitry Andric //
2593ca95b02SDimitry Andric // +------ block 0 -------+
2603ca95b02SDimitry Andric // 0| LIFETIME_START b1, b2 |
2613ca95b02SDimitry Andric // 1| <test 'if' condition> |
2623ca95b02SDimitry Andric // +-----------------------+
2633ca95b02SDimitry Andric // ./ \.
2643ca95b02SDimitry Andric // +------ block 1 -------+ +------ block 2 -------+
2653ca95b02SDimitry Andric // 2| LIFETIME_START b3 | 5| LIFETIME_START b4, b5 |
2663ca95b02SDimitry Andric // 3| <uses of b1, b3> | 6| <uses of b2, b4, b5> |
2673ca95b02SDimitry Andric // 4| LIFETIME_END b3 | 7| LIFETIME_END b4, b5 |
2683ca95b02SDimitry Andric // +-----------------------+ +-----------------------+
2693ca95b02SDimitry Andric // \. /.
2703ca95b02SDimitry Andric // +------ block 3 -------+
2713ca95b02SDimitry Andric // 8| <cleanupcode> |
2723ca95b02SDimitry Andric // 9| LIFETIME_END b1, b2 |
2733ca95b02SDimitry Andric // 10| return |
2743ca95b02SDimitry Andric // +-----------------------+
2753ca95b02SDimitry Andric //
2763ca95b02SDimitry Andric // If we create live intervals for the variables above strictly based
2773ca95b02SDimitry Andric // on the lifetime markers, we'll get the set of intervals on the
2783ca95b02SDimitry Andric // left. If we ignore the lifetime start markers and instead treat a
2793ca95b02SDimitry Andric // variable's lifetime as beginning with the first reference to the
2803ca95b02SDimitry Andric // var, then we get the intervals on the right.
2813ca95b02SDimitry Andric //
2823ca95b02SDimitry Andric // LIFETIME_START First Use
2833ca95b02SDimitry Andric // b1: [0,9] [3,4] [8,9]
2843ca95b02SDimitry Andric // b2: [0,9] [6,9]
2853ca95b02SDimitry Andric // b3: [2,4] [3,4]
2863ca95b02SDimitry Andric // b4: [5,7] [6,7]
2873ca95b02SDimitry Andric // b5: [5,7] [6,7]
2883ca95b02SDimitry Andric //
2893ca95b02SDimitry Andric // For the intervals on the left, the best we can do is overlap two
2903ca95b02SDimitry Andric // variables (b3 and b4, for example); this gives us a stack size of
2913ca95b02SDimitry Andric // 4*1024 bytes, not ideal. When treating first-use as the start of a
2923ca95b02SDimitry Andric // lifetime, we can additionally overlap b1 and b5, giving us a 3*1024
2933ca95b02SDimitry Andric // byte stack (better).
2943ca95b02SDimitry Andric //
29524d58133SDimitry Andric // Degenerate Slots:
29624d58133SDimitry Andric // -----------------
29724d58133SDimitry Andric //
2983ca95b02SDimitry Andric // Relying entirely on first-use of stack slots is problematic,
2993ca95b02SDimitry Andric // however, due to the fact that optimizations can sometimes migrate
3003ca95b02SDimitry Andric // uses of a variable outside of its lifetime start/end region. Here
3013ca95b02SDimitry Andric // is an example:
3023ca95b02SDimitry Andric //
3033ca95b02SDimitry Andric // int bar() {
3043ca95b02SDimitry Andric // char b1[1024], b2[1024];
3053ca95b02SDimitry Andric // if (...) {
3063ca95b02SDimitry Andric // <uses of b2>
3073ca95b02SDimitry Andric // return y;
3083ca95b02SDimitry Andric // } else {
3093ca95b02SDimitry Andric // <uses of b1>
3103ca95b02SDimitry Andric // while (...) {
3113ca95b02SDimitry Andric // char b3[1024];
3123ca95b02SDimitry Andric // <uses of b3>
3133ca95b02SDimitry Andric // }
3143ca95b02SDimitry Andric // }
3153ca95b02SDimitry Andric // }
3163ca95b02SDimitry Andric //
3173ca95b02SDimitry Andric // Before optimization, the control flow graph for the code above
3183ca95b02SDimitry Andric // might look like the following:
3193ca95b02SDimitry Andric //
3203ca95b02SDimitry Andric // +------ block 0 -------+
3213ca95b02SDimitry Andric // 0| LIFETIME_START b1, b2 |
3223ca95b02SDimitry Andric // 1| <test 'if' condition> |
3233ca95b02SDimitry Andric // +-----------------------+
3243ca95b02SDimitry Andric // ./ \.
3253ca95b02SDimitry Andric // +------ block 1 -------+ +------- block 2 -------+
3263ca95b02SDimitry Andric // 2| <uses of b2> | 3| <uses of b1> |
3273ca95b02SDimitry Andric // +-----------------------+ +-----------------------+
3283ca95b02SDimitry Andric // | |
3293ca95b02SDimitry Andric // | +------- block 3 -------+ <-\.
3303ca95b02SDimitry Andric // | 4| <while condition> | |
3313ca95b02SDimitry Andric // | +-----------------------+ |
3323ca95b02SDimitry Andric // | / | |
3333ca95b02SDimitry Andric // | / +------- block 4 -------+
3343ca95b02SDimitry Andric // \ / 5| LIFETIME_START b3 | |
3353ca95b02SDimitry Andric // \ / 6| <uses of b3> | |
3363ca95b02SDimitry Andric // \ / 7| LIFETIME_END b3 | |
3373ca95b02SDimitry Andric // \ | +------------------------+ |
3383ca95b02SDimitry Andric // \ | \ /
3393ca95b02SDimitry Andric // +------ block 5 -----+ \---------------
3403ca95b02SDimitry Andric // 8| <cleanupcode> |
3413ca95b02SDimitry Andric // 9| LIFETIME_END b1, b2 |
3423ca95b02SDimitry Andric // 10| return |
3433ca95b02SDimitry Andric // +---------------------+
3443ca95b02SDimitry Andric //
3453ca95b02SDimitry Andric // During optimization, however, it can happen that an instruction
3463ca95b02SDimitry Andric // computing an address in "b3" (for example, a loop-invariant GEP) is
3473ca95b02SDimitry Andric // hoisted up out of the loop from block 4 to block 2. [Note that
3483ca95b02SDimitry Andric // this is not an actual load from the stack, only an instruction that
3493ca95b02SDimitry Andric // computes the address to be loaded]. If this happens, there is now a
3503ca95b02SDimitry Andric // path leading from the first use of b3 to the return instruction
3513ca95b02SDimitry Andric // that does not encounter the b3 LIFETIME_END, hence b3's lifetime is
3523ca95b02SDimitry Andric // now larger than if we were computing live intervals strictly based
3533ca95b02SDimitry Andric // on lifetime markers. In the example above, this lengthened lifetime
3543ca95b02SDimitry Andric // would mean that it would appear illegal to overlap b3 with b2.
3553ca95b02SDimitry Andric //
3563ca95b02SDimitry Andric // To deal with this such cases, the code in ::collectMarkers() below
3573ca95b02SDimitry Andric // tries to identify "degenerate" slots -- those slots where on a single
3583ca95b02SDimitry Andric // forward pass through the CFG we encounter a first reference to slot
3593ca95b02SDimitry Andric // K before we hit the slot K lifetime start marker. For such slots,
3603ca95b02SDimitry Andric // we fall back on using the lifetime start marker as the beginning of
3613ca95b02SDimitry Andric // the variable's lifetime. NB: with this implementation, slots can
3623ca95b02SDimitry Andric // appear degenerate in cases where there is unstructured control flow:
3633ca95b02SDimitry Andric //
3643ca95b02SDimitry Andric // if (q) goto mid;
3653ca95b02SDimitry Andric // if (x > 9) {
3663ca95b02SDimitry Andric // int b[100];
3673ca95b02SDimitry Andric // memcpy(&b[0], ...);
3683ca95b02SDimitry Andric // mid: b[k] = ...;
3693ca95b02SDimitry Andric // abc(&b);
3703ca95b02SDimitry Andric // }
3713ca95b02SDimitry Andric //
3723ca95b02SDimitry Andric // If in RPO ordering chosen to walk the CFG we happen to visit the b[k]
3733ca95b02SDimitry Andric // before visiting the memcpy block (which will contain the lifetime start
3743ca95b02SDimitry Andric // for "b" then it will appear that 'b' has a degenerate lifetime.
3753ca95b02SDimitry Andric //
3763ca95b02SDimitry Andric
3773861d79fSDimitry Andric namespace {
3782cab237bSDimitry Andric
3793861d79fSDimitry Andric /// StackColoring - A machine pass for merging disjoint stack allocations,
3803861d79fSDimitry Andric /// marked by the LIFETIME_START and LIFETIME_END pseudo instructions.
3813861d79fSDimitry Andric class StackColoring : public MachineFunctionPass {
3823861d79fSDimitry Andric MachineFrameInfo *MFI;
3833861d79fSDimitry Andric MachineFunction *MF;
3843861d79fSDimitry Andric
3853861d79fSDimitry Andric /// A class representing liveness information for a single basic block.
3863861d79fSDimitry Andric /// Each bit in the BitVector represents the liveness property
3873861d79fSDimitry Andric /// for a different stack slot.
3883861d79fSDimitry Andric struct BlockLifetimeInfo {
3893861d79fSDimitry Andric /// Which slots BEGINs in each basic block.
3903861d79fSDimitry Andric BitVector Begin;
3912cab237bSDimitry Andric
3923861d79fSDimitry Andric /// Which slots ENDs in each basic block.
3933861d79fSDimitry Andric BitVector End;
3942cab237bSDimitry Andric
3953861d79fSDimitry Andric /// Which slots are marked as LIVE_IN, coming into each basic block.
3963861d79fSDimitry Andric BitVector LiveIn;
3972cab237bSDimitry Andric
3983861d79fSDimitry Andric /// Which slots are marked as LIVE_OUT, coming out of each basic block.
3993861d79fSDimitry Andric BitVector LiveOut;
4003861d79fSDimitry Andric };
4013861d79fSDimitry Andric
4023861d79fSDimitry Andric /// Maps active slots (per bit) for each basic block.
4032cab237bSDimitry Andric using LivenessMap = DenseMap<const MachineBasicBlock *, BlockLifetimeInfo>;
404139f7f9bSDimitry Andric LivenessMap BlockLiveness;
4053861d79fSDimitry Andric
4063861d79fSDimitry Andric /// Maps serial numbers to basic blocks.
407139f7f9bSDimitry Andric DenseMap<const MachineBasicBlock *, int> BasicBlocks;
4082cab237bSDimitry Andric
4093861d79fSDimitry Andric /// Maps basic blocks to a serial number.
410139f7f9bSDimitry Andric SmallVector<const MachineBasicBlock *, 8> BasicBlockNumbering;
4113861d79fSDimitry Andric
41224d58133SDimitry Andric /// Maps slots to their use interval. Outside of this interval, slots
41324d58133SDimitry Andric /// values are either dead or `undef` and they will not be written to.
41491bc56edSDimitry Andric SmallVector<std::unique_ptr<LiveInterval>, 16> Intervals;
4152cab237bSDimitry Andric
41624d58133SDimitry Andric /// Maps slots to the points where they can become in-use.
41724d58133SDimitry Andric SmallVector<SmallVector<SlotIndex, 4>, 16> LiveStarts;
4182cab237bSDimitry Andric
4193861d79fSDimitry Andric /// VNInfo is used for the construction of LiveIntervals.
4203861d79fSDimitry Andric VNInfo::Allocator VNInfoAllocator;
4212cab237bSDimitry Andric
4223861d79fSDimitry Andric /// SlotIndex analysis object.
4233861d79fSDimitry Andric SlotIndexes *Indexes;
4242cab237bSDimitry Andric
4253861d79fSDimitry Andric /// The list of lifetime markers found. These markers are to be removed
4263861d79fSDimitry Andric /// once the coloring is done.
4273861d79fSDimitry Andric SmallVector<MachineInstr*, 8> Markers;
4283861d79fSDimitry Andric
4293ca95b02SDimitry Andric /// Record the FI slots for which we have seen some sort of
4303ca95b02SDimitry Andric /// lifetime marker (either start or end).
4313ca95b02SDimitry Andric BitVector InterestingSlots;
4323ca95b02SDimitry Andric
4333ca95b02SDimitry Andric /// FI slots that need to be handled conservatively (for these
4343ca95b02SDimitry Andric /// slots lifetime-start-on-first-use is disabled).
4353ca95b02SDimitry Andric BitVector ConservativeSlots;
4363ca95b02SDimitry Andric
4373ca95b02SDimitry Andric /// Number of iterations taken during data flow analysis.
4383ca95b02SDimitry Andric unsigned NumIterations;
4393ca95b02SDimitry Andric
4403861d79fSDimitry Andric public:
4413861d79fSDimitry Andric static char ID;
4422cab237bSDimitry Andric
StackColoring()4433861d79fSDimitry Andric StackColoring() : MachineFunctionPass(ID) {
4443861d79fSDimitry Andric initializeStackColoringPass(*PassRegistry::getPassRegistry());
4453861d79fSDimitry Andric }
4462cab237bSDimitry Andric
44791bc56edSDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override;
4484ba319b5SDimitry Andric bool runOnMachineFunction(MachineFunction &Func) override;
4493861d79fSDimitry Andric
4503861d79fSDimitry Andric private:
4512cab237bSDimitry Andric /// Used in collectMarkers
4522cab237bSDimitry Andric using BlockBitVecMap = DenseMap<const MachineBasicBlock *, BitVector>;
4532cab237bSDimitry Andric
4543861d79fSDimitry Andric /// Debug.
455139f7f9bSDimitry Andric void dump() const;
4563ca95b02SDimitry Andric void dumpIntervals() const;
4573ca95b02SDimitry Andric void dumpBB(MachineBasicBlock *MBB) const;
4583ca95b02SDimitry Andric void dumpBV(const char *tag, const BitVector &BV) const;
4593861d79fSDimitry Andric
4603861d79fSDimitry Andric /// Removes all of the lifetime marker instructions from the function.
4613861d79fSDimitry Andric /// \returns true if any markers were removed.
4623861d79fSDimitry Andric bool removeAllMarkers();
4633861d79fSDimitry Andric
4643861d79fSDimitry Andric /// Scan the machine function and find all of the lifetime markers.
4653861d79fSDimitry Andric /// Record the findings in the BEGIN and END vectors.
4663861d79fSDimitry Andric /// \returns the number of markers found.
4673861d79fSDimitry Andric unsigned collectMarkers(unsigned NumSlot);
4683861d79fSDimitry Andric
4693861d79fSDimitry Andric /// Perform the dataflow calculation and calculate the lifetime for each of
4703861d79fSDimitry Andric /// the slots, based on the BEGIN/END vectors. Set the LifetimeLIVE_IN and
4713861d79fSDimitry Andric /// LifetimeLIVE_OUT maps that represent which stack slots are live coming
4723861d79fSDimitry Andric /// in and out blocks.
4733861d79fSDimitry Andric void calculateLocalLiveness();
4743861d79fSDimitry Andric
4753ca95b02SDimitry Andric /// Returns TRUE if we're using the first-use-begins-lifetime method for
4763ca95b02SDimitry Andric /// this slot (if FALSE, then the start marker is treated as start of lifetime).
applyFirstUse(int Slot)4773ca95b02SDimitry Andric bool applyFirstUse(int Slot) {
4783ca95b02SDimitry Andric if (!LifetimeStartOnFirstUse || ProtectFromEscapedAllocas)
4793ca95b02SDimitry Andric return false;
4803ca95b02SDimitry Andric if (ConservativeSlots.test(Slot))
4813ca95b02SDimitry Andric return false;
4823ca95b02SDimitry Andric return true;
4833ca95b02SDimitry Andric }
4843ca95b02SDimitry Andric
4853ca95b02SDimitry Andric /// Examines the specified instruction and returns TRUE if the instruction
4863ca95b02SDimitry Andric /// represents the start or end of an interesting lifetime. The slot or slots
4873ca95b02SDimitry Andric /// starting or ending are added to the vector "slots" and "isStart" is set
4883ca95b02SDimitry Andric /// accordingly.
4893ca95b02SDimitry Andric /// \returns True if inst contains a lifetime start or end
4903ca95b02SDimitry Andric bool isLifetimeStartOrEnd(const MachineInstr &MI,
4913ca95b02SDimitry Andric SmallVector<int, 4> &slots,
4923ca95b02SDimitry Andric bool &isStart);
4933ca95b02SDimitry Andric
4943861d79fSDimitry Andric /// Construct the LiveIntervals for the slots.
4953861d79fSDimitry Andric void calculateLiveIntervals(unsigned NumSlots);
4963861d79fSDimitry Andric
4973861d79fSDimitry Andric /// Go over the machine function and change instructions which use stack
4983861d79fSDimitry Andric /// slots to use the joint slots.
4993861d79fSDimitry Andric void remapInstructions(DenseMap<int, int> &SlotRemap);
5003861d79fSDimitry Andric
501f785676fSDimitry Andric /// The input program may contain instructions which are not inside lifetime
5023861d79fSDimitry Andric /// markers. This can happen due to a bug in the compiler or due to a bug in
5033861d79fSDimitry Andric /// user code (for example, returning a reference to a local variable).
5043861d79fSDimitry Andric /// This procedure checks all of the instructions in the function and
5053861d79fSDimitry Andric /// invalidates lifetime ranges which do not contain all of the instructions
5063861d79fSDimitry Andric /// which access that frame slot.
5073861d79fSDimitry Andric void removeInvalidSlotRanges();
5083861d79fSDimitry Andric
5093861d79fSDimitry Andric /// Map entries which point to other entries to their destination.
5103861d79fSDimitry Andric /// A->B->C becomes A->C.
5113861d79fSDimitry Andric void expungeSlotMap(DenseMap<int, int> &SlotRemap, unsigned NumSlots);
5123861d79fSDimitry Andric };
5132cab237bSDimitry Andric
5143861d79fSDimitry Andric } // end anonymous namespace
5153861d79fSDimitry Andric
5163861d79fSDimitry Andric char StackColoring::ID = 0;
5172cab237bSDimitry Andric
5183861d79fSDimitry Andric char &llvm::StackColoringID = StackColoring::ID;
5193861d79fSDimitry Andric
520302affcbSDimitry Andric INITIALIZE_PASS_BEGIN(StackColoring, DEBUG_TYPE,
521302affcbSDimitry Andric "Merge disjoint stack slots", false, false)
INITIALIZE_PASS_DEPENDENCY(SlotIndexes)5223861d79fSDimitry Andric INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
523302affcbSDimitry Andric INITIALIZE_PASS_END(StackColoring, DEBUG_TYPE,
524302affcbSDimitry Andric "Merge disjoint stack slots", false, false)
5253861d79fSDimitry Andric
5263861d79fSDimitry Andric void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const {
5273861d79fSDimitry Andric AU.addRequired<SlotIndexes>();
5283861d79fSDimitry Andric MachineFunctionPass::getAnalysisUsage(AU);
5293861d79fSDimitry Andric }
5303861d79fSDimitry Andric
5317a7e6055SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dumpBV(const char * tag,const BitVector & BV) const5323ca95b02SDimitry Andric LLVM_DUMP_METHOD void StackColoring::dumpBV(const char *tag,
5333ca95b02SDimitry Andric const BitVector &BV) const {
5347a7e6055SDimitry Andric dbgs() << tag << " : { ";
5353ca95b02SDimitry Andric for (unsigned I = 0, E = BV.size(); I != E; ++I)
5367a7e6055SDimitry Andric dbgs() << BV.test(I) << " ";
5377a7e6055SDimitry Andric dbgs() << "}\n";
5383ca95b02SDimitry Andric }
5393ca95b02SDimitry Andric
dumpBB(MachineBasicBlock * MBB) const5403ca95b02SDimitry Andric LLVM_DUMP_METHOD void StackColoring::dumpBB(MachineBasicBlock *MBB) const {
54191bc56edSDimitry Andric LivenessMap::const_iterator BI = BlockLiveness.find(MBB);
542139f7f9bSDimitry Andric assert(BI != BlockLiveness.end() && "Block not found");
543139f7f9bSDimitry Andric const BlockLifetimeInfo &BlockInfo = BI->second;
544139f7f9bSDimitry Andric
5453ca95b02SDimitry Andric dumpBV("BEGIN", BlockInfo.Begin);
5463ca95b02SDimitry Andric dumpBV("END", BlockInfo.End);
5473ca95b02SDimitry Andric dumpBV("LIVE_IN", BlockInfo.LiveIn);
5483ca95b02SDimitry Andric dumpBV("LIVE_OUT", BlockInfo.LiveOut);
5493ca95b02SDimitry Andric }
5503861d79fSDimitry Andric
dump() const5513ca95b02SDimitry Andric LLVM_DUMP_METHOD void StackColoring::dump() const {
5523ca95b02SDimitry Andric for (MachineBasicBlock *MBB : depth_first(MF)) {
5537a7e6055SDimitry Andric dbgs() << "Inspecting block #" << MBB->getNumber() << " ["
5547a7e6055SDimitry Andric << MBB->getName() << "]\n";
5557a7e6055SDimitry Andric dumpBB(MBB);
5563861d79fSDimitry Andric }
5573861d79fSDimitry Andric }
5583861d79fSDimitry Andric
dumpIntervals() const5593ca95b02SDimitry Andric LLVM_DUMP_METHOD void StackColoring::dumpIntervals() const {
5603ca95b02SDimitry Andric for (unsigned I = 0, E = Intervals.size(); I != E; ++I) {
5617a7e6055SDimitry Andric dbgs() << "Interval[" << I << "]:\n";
5627a7e6055SDimitry Andric Intervals[I]->dump();
5633ca95b02SDimitry Andric }
5643ca95b02SDimitry Andric }
5657a7e6055SDimitry Andric #endif
5663ca95b02SDimitry Andric
getStartOrEndSlot(const MachineInstr & MI)5673ca95b02SDimitry Andric static inline int getStartOrEndSlot(const MachineInstr &MI)
5683ca95b02SDimitry Andric {
5693ca95b02SDimitry Andric assert((MI.getOpcode() == TargetOpcode::LIFETIME_START ||
5703ca95b02SDimitry Andric MI.getOpcode() == TargetOpcode::LIFETIME_END) &&
5713ca95b02SDimitry Andric "Expected LIFETIME_START or LIFETIME_END op");
5723ca95b02SDimitry Andric const MachineOperand &MO = MI.getOperand(0);
5733ca95b02SDimitry Andric int Slot = MO.getIndex();
5743ca95b02SDimitry Andric if (Slot >= 0)
5753ca95b02SDimitry Andric return Slot;
5763ca95b02SDimitry Andric return -1;
5773ca95b02SDimitry Andric }
5783ca95b02SDimitry Andric
5793ca95b02SDimitry Andric // At the moment the only way to end a variable lifetime is with
5803ca95b02SDimitry Andric // a VARIABLE_LIFETIME op (which can't contain a start). If things
5813ca95b02SDimitry Andric // change and the IR allows for a single inst that both begins
5823ca95b02SDimitry Andric // and ends lifetime(s), this interface will need to be reworked.
isLifetimeStartOrEnd(const MachineInstr & MI,SmallVector<int,4> & slots,bool & isStart)5833ca95b02SDimitry Andric bool StackColoring::isLifetimeStartOrEnd(const MachineInstr &MI,
5843ca95b02SDimitry Andric SmallVector<int, 4> &slots,
5852cab237bSDimitry Andric bool &isStart) {
5863ca95b02SDimitry Andric if (MI.getOpcode() == TargetOpcode::LIFETIME_START ||
5873ca95b02SDimitry Andric MI.getOpcode() == TargetOpcode::LIFETIME_END) {
5883ca95b02SDimitry Andric int Slot = getStartOrEndSlot(MI);
5893ca95b02SDimitry Andric if (Slot < 0)
5903ca95b02SDimitry Andric return false;
5913ca95b02SDimitry Andric if (!InterestingSlots.test(Slot))
5923ca95b02SDimitry Andric return false;
5933ca95b02SDimitry Andric slots.push_back(Slot);
5943ca95b02SDimitry Andric if (MI.getOpcode() == TargetOpcode::LIFETIME_END) {
5953ca95b02SDimitry Andric isStart = false;
5963ca95b02SDimitry Andric return true;
5973ca95b02SDimitry Andric }
5983ca95b02SDimitry Andric if (!applyFirstUse(Slot)) {
5993ca95b02SDimitry Andric isStart = true;
6003ca95b02SDimitry Andric return true;
6013ca95b02SDimitry Andric }
6023ca95b02SDimitry Andric } else if (LifetimeStartOnFirstUse && !ProtectFromEscapedAllocas) {
6034ba319b5SDimitry Andric if (!MI.isDebugInstr()) {
6043ca95b02SDimitry Andric bool found = false;
6053ca95b02SDimitry Andric for (const MachineOperand &MO : MI.operands()) {
6063ca95b02SDimitry Andric if (!MO.isFI())
6073ca95b02SDimitry Andric continue;
6083ca95b02SDimitry Andric int Slot = MO.getIndex();
6093ca95b02SDimitry Andric if (Slot<0)
6103ca95b02SDimitry Andric continue;
6113ca95b02SDimitry Andric if (InterestingSlots.test(Slot) && applyFirstUse(Slot)) {
6123ca95b02SDimitry Andric slots.push_back(Slot);
6133ca95b02SDimitry Andric found = true;
6143ca95b02SDimitry Andric }
6153ca95b02SDimitry Andric }
6163ca95b02SDimitry Andric if (found) {
6173ca95b02SDimitry Andric isStart = true;
6183ca95b02SDimitry Andric return true;
6193ca95b02SDimitry Andric }
6203ca95b02SDimitry Andric }
6213ca95b02SDimitry Andric }
6223ca95b02SDimitry Andric return false;
6233ca95b02SDimitry Andric }
6243ca95b02SDimitry Andric
collectMarkers(unsigned NumSlot)6252cab237bSDimitry Andric unsigned StackColoring::collectMarkers(unsigned NumSlot) {
6263861d79fSDimitry Andric unsigned MarkersFound = 0;
6273ca95b02SDimitry Andric BlockBitVecMap SeenStartMap;
6283ca95b02SDimitry Andric InterestingSlots.clear();
6293ca95b02SDimitry Andric InterestingSlots.resize(NumSlot);
6303ca95b02SDimitry Andric ConservativeSlots.clear();
6313ca95b02SDimitry Andric ConservativeSlots.resize(NumSlot);
6323ca95b02SDimitry Andric
6333ca95b02SDimitry Andric // number of start and end lifetime ops for each slot
6343ca95b02SDimitry Andric SmallVector<int, 8> NumStartLifetimes(NumSlot, 0);
6353ca95b02SDimitry Andric SmallVector<int, 8> NumEndLifetimes(NumSlot, 0);
6363ca95b02SDimitry Andric
6373ca95b02SDimitry Andric // Step 1: collect markers and populate the "InterestingSlots"
6383ca95b02SDimitry Andric // and "ConservativeSlots" sets.
6393ca95b02SDimitry Andric for (MachineBasicBlock *MBB : depth_first(MF)) {
6403ca95b02SDimitry Andric // Compute the set of slots for which we've seen a START marker but have
6413ca95b02SDimitry Andric // not yet seen an END marker at this point in the walk (e.g. on entry
6423ca95b02SDimitry Andric // to this bb).
6433ca95b02SDimitry Andric BitVector BetweenStartEnd;
6443ca95b02SDimitry Andric BetweenStartEnd.resize(NumSlot);
6453ca95b02SDimitry Andric for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
6463ca95b02SDimitry Andric PE = MBB->pred_end(); PI != PE; ++PI) {
6473ca95b02SDimitry Andric BlockBitVecMap::const_iterator I = SeenStartMap.find(*PI);
6483ca95b02SDimitry Andric if (I != SeenStartMap.end()) {
6493ca95b02SDimitry Andric BetweenStartEnd |= I->second;
6503ca95b02SDimitry Andric }
6513ca95b02SDimitry Andric }
6523ca95b02SDimitry Andric
6533ca95b02SDimitry Andric // Walk the instructions in the block to look for start/end ops.
6543ca95b02SDimitry Andric for (MachineInstr &MI : *MBB) {
6553ca95b02SDimitry Andric if (MI.getOpcode() == TargetOpcode::LIFETIME_START ||
6563ca95b02SDimitry Andric MI.getOpcode() == TargetOpcode::LIFETIME_END) {
6573ca95b02SDimitry Andric int Slot = getStartOrEndSlot(MI);
6583ca95b02SDimitry Andric if (Slot < 0)
6593ca95b02SDimitry Andric continue;
6603ca95b02SDimitry Andric InterestingSlots.set(Slot);
6613ca95b02SDimitry Andric if (MI.getOpcode() == TargetOpcode::LIFETIME_START) {
6623ca95b02SDimitry Andric BetweenStartEnd.set(Slot);
6633ca95b02SDimitry Andric NumStartLifetimes[Slot] += 1;
6643ca95b02SDimitry Andric } else {
6653ca95b02SDimitry Andric BetweenStartEnd.reset(Slot);
6663ca95b02SDimitry Andric NumEndLifetimes[Slot] += 1;
6673ca95b02SDimitry Andric }
6683ca95b02SDimitry Andric const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
6693ca95b02SDimitry Andric if (Allocation) {
6704ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Found a lifetime ");
6714ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << (MI.getOpcode() == TargetOpcode::LIFETIME_START
6723ca95b02SDimitry Andric ? "start"
6733ca95b02SDimitry Andric : "end"));
6744ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " marker for slot #" << Slot);
6754ba319b5SDimitry Andric LLVM_DEBUG(dbgs()
6764ba319b5SDimitry Andric << " with allocation: " << Allocation->getName() << "\n");
6773ca95b02SDimitry Andric }
6783ca95b02SDimitry Andric Markers.push_back(&MI);
6793ca95b02SDimitry Andric MarkersFound += 1;
6803ca95b02SDimitry Andric } else {
6813ca95b02SDimitry Andric for (const MachineOperand &MO : MI.operands()) {
6823ca95b02SDimitry Andric if (!MO.isFI())
6833ca95b02SDimitry Andric continue;
6843ca95b02SDimitry Andric int Slot = MO.getIndex();
6853ca95b02SDimitry Andric if (Slot < 0)
6863ca95b02SDimitry Andric continue;
6873ca95b02SDimitry Andric if (! BetweenStartEnd.test(Slot)) {
6883ca95b02SDimitry Andric ConservativeSlots.set(Slot);
6893ca95b02SDimitry Andric }
6903ca95b02SDimitry Andric }
6913ca95b02SDimitry Andric }
6923ca95b02SDimitry Andric }
6933ca95b02SDimitry Andric BitVector &SeenStart = SeenStartMap[MBB];
6943ca95b02SDimitry Andric SeenStart |= BetweenStartEnd;
6953ca95b02SDimitry Andric }
6963ca95b02SDimitry Andric if (!MarkersFound) {
6973ca95b02SDimitry Andric return 0;
6983ca95b02SDimitry Andric }
6993ca95b02SDimitry Andric
7003ca95b02SDimitry Andric // PR27903: slots with multiple start or end lifetime ops are not
7013ca95b02SDimitry Andric // safe to enable for "lifetime-start-on-first-use".
7023ca95b02SDimitry Andric for (unsigned slot = 0; slot < NumSlot; ++slot)
7033ca95b02SDimitry Andric if (NumStartLifetimes[slot] > 1 || NumEndLifetimes[slot] > 1)
7043ca95b02SDimitry Andric ConservativeSlots.set(slot);
7054ba319b5SDimitry Andric LLVM_DEBUG(dumpBV("Conservative slots", ConservativeSlots));
7063ca95b02SDimitry Andric
7073ca95b02SDimitry Andric // Step 2: compute begin/end sets for each block
7083ca95b02SDimitry Andric
7097a7e6055SDimitry Andric // NOTE: We use a depth-first iteration to ensure that we obtain a
7107a7e6055SDimitry Andric // deterministic numbering.
71191bc56edSDimitry Andric for (MachineBasicBlock *MBB : depth_first(MF)) {
7123861d79fSDimitry Andric // Assign a serial number to this basic block.
71391bc56edSDimitry Andric BasicBlocks[MBB] = BasicBlockNumbering.size();
71491bc56edSDimitry Andric BasicBlockNumbering.push_back(MBB);
7153861d79fSDimitry Andric
716139f7f9bSDimitry Andric // Keep a reference to avoid repeated lookups.
71791bc56edSDimitry Andric BlockLifetimeInfo &BlockInfo = BlockLiveness[MBB];
718139f7f9bSDimitry Andric
719139f7f9bSDimitry Andric BlockInfo.Begin.resize(NumSlot);
720139f7f9bSDimitry Andric BlockInfo.End.resize(NumSlot);
7213861d79fSDimitry Andric
7223ca95b02SDimitry Andric SmallVector<int, 4> slots;
72391bc56edSDimitry Andric for (MachineInstr &MI : *MBB) {
7243ca95b02SDimitry Andric bool isStart = false;
7253ca95b02SDimitry Andric slots.clear();
7263ca95b02SDimitry Andric if (isLifetimeStartOrEnd(MI, slots, isStart)) {
7273ca95b02SDimitry Andric if (!isStart) {
7283ca95b02SDimitry Andric assert(slots.size() == 1 && "unexpected: MI ends multiple slots");
7293ca95b02SDimitry Andric int Slot = slots[0];
7303ca95b02SDimitry Andric if (BlockInfo.Begin.test(Slot)) {
7313ca95b02SDimitry Andric BlockInfo.Begin.reset(Slot);
7323ca95b02SDimitry Andric }
7333ca95b02SDimitry Andric BlockInfo.End.set(Slot);
7343ca95b02SDimitry Andric } else {
7353ca95b02SDimitry Andric for (auto Slot : slots) {
7364ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Found a use of slot #" << Slot);
7374ba319b5SDimitry Andric LLVM_DEBUG(dbgs()
7384ba319b5SDimitry Andric << " at " << printMBBReference(*MBB) << " index ");
7394ba319b5SDimitry Andric LLVM_DEBUG(Indexes->getInstructionIndex(MI).print(dbgs()));
7403861d79fSDimitry Andric const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
7413861d79fSDimitry Andric if (Allocation) {
7424ba319b5SDimitry Andric LLVM_DEBUG(dbgs()
7434ba319b5SDimitry Andric << " with allocation: " << Allocation->getName());
7443861d79fSDimitry Andric }
7454ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
7463ca95b02SDimitry Andric if (BlockInfo.End.test(Slot)) {
7473ca95b02SDimitry Andric BlockInfo.End.reset(Slot);
7483ca95b02SDimitry Andric }
749139f7f9bSDimitry Andric BlockInfo.Begin.set(Slot);
7503ca95b02SDimitry Andric }
7513861d79fSDimitry Andric }
7523861d79fSDimitry Andric }
7533861d79fSDimitry Andric }
7543861d79fSDimitry Andric }
7553861d79fSDimitry Andric
7563861d79fSDimitry Andric // Update statistics.
7573861d79fSDimitry Andric NumMarkerSeen += MarkersFound;
7583861d79fSDimitry Andric return MarkersFound;
7593861d79fSDimitry Andric }
7603861d79fSDimitry Andric
calculateLocalLiveness()7612cab237bSDimitry Andric void StackColoring::calculateLocalLiveness() {
7623ca95b02SDimitry Andric unsigned NumIters = 0;
7633861d79fSDimitry Andric bool changed = true;
7643861d79fSDimitry Andric while (changed) {
7653861d79fSDimitry Andric changed = false;
7663ca95b02SDimitry Andric ++NumIters;
7673861d79fSDimitry Andric
76891bc56edSDimitry Andric for (const MachineBasicBlock *BB : BasicBlockNumbering) {
769139f7f9bSDimitry Andric // Use an iterator to avoid repeated lookups.
770139f7f9bSDimitry Andric LivenessMap::iterator BI = BlockLiveness.find(BB);
771139f7f9bSDimitry Andric assert(BI != BlockLiveness.end() && "Block not found");
772139f7f9bSDimitry Andric BlockLifetimeInfo &BlockInfo = BI->second;
773139f7f9bSDimitry Andric
7743ca95b02SDimitry Andric // Compute LiveIn by unioning together the LiveOut sets of all preds.
7753861d79fSDimitry Andric BitVector LocalLiveIn;
776139f7f9bSDimitry Andric for (MachineBasicBlock::const_pred_iterator PI = BB->pred_begin(),
777139f7f9bSDimitry Andric PE = BB->pred_end(); PI != PE; ++PI) {
778139f7f9bSDimitry Andric LivenessMap::const_iterator I = BlockLiveness.find(*PI);
7794ba319b5SDimitry Andric // PR37130: transformations prior to stack coloring can
7804ba319b5SDimitry Andric // sometimes leave behind statically unreachable blocks; these
7814ba319b5SDimitry Andric // can be safely skipped here.
7824ba319b5SDimitry Andric if (I != BlockLiveness.end())
783139f7f9bSDimitry Andric LocalLiveIn |= I->second.LiveOut;
784139f7f9bSDimitry Andric }
7853861d79fSDimitry Andric
7863ca95b02SDimitry Andric // Compute LiveOut by subtracting out lifetimes that end in this
7873ca95b02SDimitry Andric // block, then adding in lifetimes that begin in this block. If
7883ca95b02SDimitry Andric // we have both BEGIN and END markers in the same basic block
7893ca95b02SDimitry Andric // then we know that the BEGIN marker comes after the END,
7903ca95b02SDimitry Andric // because we already handle the case where the BEGIN comes
7913ca95b02SDimitry Andric // before the END when collecting the markers (and building the
7923ca95b02SDimitry Andric // BEGIN/END vectors).
7933ca95b02SDimitry Andric BitVector LocalLiveOut = LocalLiveIn;
7943ca95b02SDimitry Andric LocalLiveOut.reset(BlockInfo.End);
795139f7f9bSDimitry Andric LocalLiveOut |= BlockInfo.Begin;
7963861d79fSDimitry Andric
7973ca95b02SDimitry Andric // Update block LiveIn set, noting whether it has changed.
798139f7f9bSDimitry Andric if (LocalLiveIn.test(BlockInfo.LiveIn)) {
7993861d79fSDimitry Andric changed = true;
800139f7f9bSDimitry Andric BlockInfo.LiveIn |= LocalLiveIn;
8013861d79fSDimitry Andric }
8023861d79fSDimitry Andric
8033ca95b02SDimitry Andric // Update block LiveOut set, noting whether it has changed.
804139f7f9bSDimitry Andric if (LocalLiveOut.test(BlockInfo.LiveOut)) {
8053861d79fSDimitry Andric changed = true;
806139f7f9bSDimitry Andric BlockInfo.LiveOut |= LocalLiveOut;
8073861d79fSDimitry Andric }
8083861d79fSDimitry Andric }
8093861d79fSDimitry Andric } // while changed.
8103ca95b02SDimitry Andric
8113ca95b02SDimitry Andric NumIterations = NumIters;
8123861d79fSDimitry Andric }
8133861d79fSDimitry Andric
calculateLiveIntervals(unsigned NumSlots)8143861d79fSDimitry Andric void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
8153861d79fSDimitry Andric SmallVector<SlotIndex, 16> Starts;
81624d58133SDimitry Andric SmallVector<bool, 16> DefinitelyInUse;
8173861d79fSDimitry Andric
8183861d79fSDimitry Andric // For each block, find which slots are active within this block
8193861d79fSDimitry Andric // and update the live intervals.
82091bc56edSDimitry Andric for (const MachineBasicBlock &MBB : *MF) {
8213861d79fSDimitry Andric Starts.clear();
8223861d79fSDimitry Andric Starts.resize(NumSlots);
82324d58133SDimitry Andric DefinitelyInUse.clear();
82424d58133SDimitry Andric DefinitelyInUse.resize(NumSlots);
82524d58133SDimitry Andric
82624d58133SDimitry Andric // Start the interval of the slots that we previously found to be 'in-use'.
82724d58133SDimitry Andric BlockLifetimeInfo &MBBLiveness = BlockLiveness[&MBB];
82824d58133SDimitry Andric for (int pos = MBBLiveness.LiveIn.find_first(); pos != -1;
82924d58133SDimitry Andric pos = MBBLiveness.LiveIn.find_next(pos)) {
83024d58133SDimitry Andric Starts[pos] = Indexes->getMBBStartIdx(&MBB);
83124d58133SDimitry Andric }
8323861d79fSDimitry Andric
8333ca95b02SDimitry Andric // Create the interval for the basic blocks containing lifetime begin/end.
8343ca95b02SDimitry Andric for (const MachineInstr &MI : MBB) {
8353ca95b02SDimitry Andric SmallVector<int, 4> slots;
8363ca95b02SDimitry Andric bool IsStart = false;
8373ca95b02SDimitry Andric if (!isLifetimeStartOrEnd(MI, slots, IsStart))
8383861d79fSDimitry Andric continue;
8393861d79fSDimitry Andric SlotIndex ThisIndex = Indexes->getInstructionIndex(MI);
8403ca95b02SDimitry Andric for (auto Slot : slots) {
8413861d79fSDimitry Andric if (IsStart) {
84224d58133SDimitry Andric // If a slot is already definitely in use, we don't have to emit
84324d58133SDimitry Andric // a new start marker because there is already a pre-existing
84424d58133SDimitry Andric // one.
84524d58133SDimitry Andric if (!DefinitelyInUse[Slot]) {
84624d58133SDimitry Andric LiveStarts[Slot].push_back(ThisIndex);
84724d58133SDimitry Andric DefinitelyInUse[Slot] = true;
84824d58133SDimitry Andric }
84924d58133SDimitry Andric if (!Starts[Slot].isValid())
8503861d79fSDimitry Andric Starts[Slot] = ThisIndex;
8513861d79fSDimitry Andric } else {
85224d58133SDimitry Andric if (Starts[Slot].isValid()) {
85324d58133SDimitry Andric VNInfo *VNI = Intervals[Slot]->getValNumInfo(0);
85424d58133SDimitry Andric Intervals[Slot]->addSegment(
85524d58133SDimitry Andric LiveInterval::Segment(Starts[Slot], ThisIndex, VNI));
85624d58133SDimitry Andric Starts[Slot] = SlotIndex(); // Invalidate the start index
85724d58133SDimitry Andric DefinitelyInUse[Slot] = false;
85824d58133SDimitry Andric }
8593861d79fSDimitry Andric }
8603861d79fSDimitry Andric }
8613ca95b02SDimitry Andric }
8623861d79fSDimitry Andric
86324d58133SDimitry Andric // Finish up started segments
8643861d79fSDimitry Andric for (unsigned i = 0; i < NumSlots; ++i) {
8653861d79fSDimitry Andric if (!Starts[i].isValid())
8663861d79fSDimitry Andric continue;
8673861d79fSDimitry Andric
86824d58133SDimitry Andric SlotIndex EndIdx = Indexes->getMBBEndIdx(&MBB);
86924d58133SDimitry Andric VNInfo *VNI = Intervals[i]->getValNumInfo(0);
87024d58133SDimitry Andric Intervals[i]->addSegment(LiveInterval::Segment(Starts[i], EndIdx, VNI));
8713861d79fSDimitry Andric }
8723861d79fSDimitry Andric }
8733861d79fSDimitry Andric }
8743861d79fSDimitry Andric
removeAllMarkers()8753861d79fSDimitry Andric bool StackColoring::removeAllMarkers() {
8763861d79fSDimitry Andric unsigned Count = 0;
87791bc56edSDimitry Andric for (MachineInstr *MI : Markers) {
87891bc56edSDimitry Andric MI->eraseFromParent();
8793861d79fSDimitry Andric Count++;
8803861d79fSDimitry Andric }
8813861d79fSDimitry Andric Markers.clear();
8823861d79fSDimitry Andric
8834ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Removed " << Count << " markers.\n");
8843861d79fSDimitry Andric return Count;
8853861d79fSDimitry Andric }
8863861d79fSDimitry Andric
remapInstructions(DenseMap<int,int> & SlotRemap)8873861d79fSDimitry Andric void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
8883861d79fSDimitry Andric unsigned FixedInstr = 0;
8893861d79fSDimitry Andric unsigned FixedMemOp = 0;
8903861d79fSDimitry Andric unsigned FixedDbg = 0;
8913861d79fSDimitry Andric
8923861d79fSDimitry Andric // Remap debug information that refers to stack slots.
893d88c1a5aSDimitry Andric for (auto &VI : MF->getVariableDbgInfo()) {
89491bc56edSDimitry Andric if (!VI.Var)
89591bc56edSDimitry Andric continue;
89691bc56edSDimitry Andric if (SlotRemap.count(VI.Slot)) {
8974ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Remapping debug info for ["
898ff0cc061SDimitry Andric << cast<DILocalVariable>(VI.Var)->getName() << "].\n");
89991bc56edSDimitry Andric VI.Slot = SlotRemap[VI.Slot];
9003861d79fSDimitry Andric FixedDbg++;
9013861d79fSDimitry Andric }
9023861d79fSDimitry Andric }
9033861d79fSDimitry Andric
9043861d79fSDimitry Andric // Keep a list of *allocas* which need to be remapped.
9053861d79fSDimitry Andric DenseMap<const AllocaInst*, const AllocaInst*> Allocas;
9069dc417c3SDimitry Andric
9079dc417c3SDimitry Andric // Keep a list of allocas which has been affected by the remap.
9089dc417c3SDimitry Andric SmallPtrSet<const AllocaInst*, 32> MergedAllocas;
9099dc417c3SDimitry Andric
91091bc56edSDimitry Andric for (const std::pair<int, int> &SI : SlotRemap) {
91191bc56edSDimitry Andric const AllocaInst *From = MFI->getObjectAllocation(SI.first);
91291bc56edSDimitry Andric const AllocaInst *To = MFI->getObjectAllocation(SI.second);
9133861d79fSDimitry Andric assert(To && From && "Invalid allocation object");
9143861d79fSDimitry Andric Allocas[From] = To;
91591bc56edSDimitry Andric
91691bc56edSDimitry Andric // AA might be used later for instruction scheduling, and we need it to be
91791bc56edSDimitry Andric // able to deduce the correct aliasing releationships between pointers
91891bc56edSDimitry Andric // derived from the alloca being remapped and the target of that remapping.
91991bc56edSDimitry Andric // The only safe way, without directly informing AA about the remapping
92091bc56edSDimitry Andric // somehow, is to directly update the IR to reflect the change being made
92191bc56edSDimitry Andric // here.
92291bc56edSDimitry Andric Instruction *Inst = const_cast<AllocaInst *>(To);
92391bc56edSDimitry Andric if (From->getType() != To->getType()) {
92491bc56edSDimitry Andric BitCastInst *Cast = new BitCastInst(Inst, From->getType());
92591bc56edSDimitry Andric Cast->insertAfter(Inst);
92691bc56edSDimitry Andric Inst = Cast;
92791bc56edSDimitry Andric }
92891bc56edSDimitry Andric
9299dc417c3SDimitry Andric // We keep both slots to maintain AliasAnalysis metadata later.
9309dc417c3SDimitry Andric MergedAllocas.insert(From);
9319dc417c3SDimitry Andric MergedAllocas.insert(To);
9329dc417c3SDimitry Andric
9334ba319b5SDimitry Andric // Transfer the stack protector layout tag, but make sure that SSPLK_AddrOf
9344ba319b5SDimitry Andric // does not overwrite SSPLK_SmallArray or SSPLK_LargeArray, and make sure
9354ba319b5SDimitry Andric // that SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
9364ba319b5SDimitry Andric MachineFrameInfo::SSPLayoutKind FromKind
9374ba319b5SDimitry Andric = MFI->getObjectSSPLayout(SI.first);
9384ba319b5SDimitry Andric MachineFrameInfo::SSPLayoutKind ToKind = MFI->getObjectSSPLayout(SI.second);
9394ba319b5SDimitry Andric if (FromKind != MachineFrameInfo::SSPLK_None &&
9404ba319b5SDimitry Andric (ToKind == MachineFrameInfo::SSPLK_None ||
9414ba319b5SDimitry Andric (ToKind != MachineFrameInfo::SSPLK_LargeArray &&
9424ba319b5SDimitry Andric FromKind != MachineFrameInfo::SSPLK_AddrOf)))
9434ba319b5SDimitry Andric MFI->setObjectSSPLayout(SI.second, FromKind);
94491bc56edSDimitry Andric
9453ca95b02SDimitry Andric // The new alloca might not be valid in a llvm.dbg.declare for this
9463ca95b02SDimitry Andric // variable, so undef out the use to make the verifier happy.
9473ca95b02SDimitry Andric AllocaInst *FromAI = const_cast<AllocaInst *>(From);
9483ca95b02SDimitry Andric if (FromAI->isUsedByMetadata())
9493ca95b02SDimitry Andric ValueAsMetadata::handleRAUW(FromAI, UndefValue::get(FromAI->getType()));
9503ca95b02SDimitry Andric for (auto &Use : FromAI->uses()) {
9513ca95b02SDimitry Andric if (BitCastInst *BCI = dyn_cast<BitCastInst>(Use.get()))
9523ca95b02SDimitry Andric if (BCI->isUsedByMetadata())
9533ca95b02SDimitry Andric ValueAsMetadata::handleRAUW(BCI, UndefValue::get(BCI->getType()));
9543ca95b02SDimitry Andric }
9553ca95b02SDimitry Andric
95691bc56edSDimitry Andric // Note that this will not replace uses in MMOs (which we'll update below),
95791bc56edSDimitry Andric // or anywhere else (which is why we won't delete the original
95891bc56edSDimitry Andric // instruction).
9593ca95b02SDimitry Andric FromAI->replaceAllUsesWith(Inst);
9603861d79fSDimitry Andric }
9613861d79fSDimitry Andric
9623861d79fSDimitry Andric // Remap all instructions to the new stack slots.
96391bc56edSDimitry Andric for (MachineBasicBlock &BB : *MF)
96491bc56edSDimitry Andric for (MachineInstr &I : BB) {
9653861d79fSDimitry Andric // Skip lifetime markers. We'll remove them soon.
96691bc56edSDimitry Andric if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
96791bc56edSDimitry Andric I.getOpcode() == TargetOpcode::LIFETIME_END)
9683861d79fSDimitry Andric continue;
9693861d79fSDimitry Andric
9703861d79fSDimitry Andric // Update the MachineMemOperand to use the new alloca.
97191bc56edSDimitry Andric for (MachineMemOperand *MMO : I.memoperands()) {
97291bc56edSDimitry Andric // We've replaced IR-level uses of the remapped allocas, so we only
97391bc56edSDimitry Andric // need to replace direct uses here.
97491bc56edSDimitry Andric const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(MMO->getValue());
97591bc56edSDimitry Andric if (!AI)
9763861d79fSDimitry Andric continue;
9773861d79fSDimitry Andric
9783861d79fSDimitry Andric if (!Allocas.count(AI))
9793861d79fSDimitry Andric continue;
9803861d79fSDimitry Andric
9813861d79fSDimitry Andric MMO->setValue(Allocas[AI]);
9823861d79fSDimitry Andric FixedMemOp++;
9833861d79fSDimitry Andric }
9843861d79fSDimitry Andric
9853861d79fSDimitry Andric // Update all of the machine instruction operands.
98691bc56edSDimitry Andric for (MachineOperand &MO : I.operands()) {
9873861d79fSDimitry Andric if (!MO.isFI())
9883861d79fSDimitry Andric continue;
9893861d79fSDimitry Andric int FromSlot = MO.getIndex();
9903861d79fSDimitry Andric
9913861d79fSDimitry Andric // Don't touch arguments.
9923861d79fSDimitry Andric if (FromSlot<0)
9933861d79fSDimitry Andric continue;
9943861d79fSDimitry Andric
9953861d79fSDimitry Andric // Only look at mapped slots.
9963861d79fSDimitry Andric if (!SlotRemap.count(FromSlot))
9973861d79fSDimitry Andric continue;
9983861d79fSDimitry Andric
9993861d79fSDimitry Andric // In a debug build, check that the instruction that we are modifying is
10003861d79fSDimitry Andric // inside the expected live range. If the instruction is not inside
10013861d79fSDimitry Andric // the calculated range then it means that the alloca usage moved
10023861d79fSDimitry Andric // outside of the lifetime markers, or that the user has a bug.
10033861d79fSDimitry Andric // NOTE: Alloca address calculations which happen outside the lifetime
10044ba319b5SDimitry Andric // zone are okay, despite the fact that we don't have a good way
10053861d79fSDimitry Andric // for validating all of the usages of the calculation.
10063861d79fSDimitry Andric #ifndef NDEBUG
100791bc56edSDimitry Andric bool TouchesMemory = I.mayLoad() || I.mayStore();
10083861d79fSDimitry Andric // If we *don't* protect the user from escaped allocas, don't bother
10093861d79fSDimitry Andric // validating the instructions.
10104ba319b5SDimitry Andric if (!I.isDebugInstr() && TouchesMemory && ProtectFromEscapedAllocas) {
10113ca95b02SDimitry Andric SlotIndex Index = Indexes->getInstructionIndex(I);
101291bc56edSDimitry Andric const LiveInterval *Interval = &*Intervals[FromSlot];
10133861d79fSDimitry Andric assert(Interval->find(Index) != Interval->end() &&
10143861d79fSDimitry Andric "Found instruction usage outside of live range.");
10153861d79fSDimitry Andric }
10163861d79fSDimitry Andric #endif
10173861d79fSDimitry Andric
10183861d79fSDimitry Andric // Fix the machine instructions.
10193861d79fSDimitry Andric int ToSlot = SlotRemap[FromSlot];
10203861d79fSDimitry Andric MO.setIndex(ToSlot);
10213861d79fSDimitry Andric FixedInstr++;
10223861d79fSDimitry Andric }
10239dc417c3SDimitry Andric
10249dc417c3SDimitry Andric // We adjust AliasAnalysis information for merged stack slots.
1025*b5893f02SDimitry Andric SmallVector<MachineMemOperand *, 2> NewMMOs;
10269dc417c3SDimitry Andric bool ReplaceMemOps = false;
10279dc417c3SDimitry Andric for (MachineMemOperand *MMO : I.memoperands()) {
10289dc417c3SDimitry Andric // If this memory location can be a slot remapped here,
10299dc417c3SDimitry Andric // we remove AA information.
10309dc417c3SDimitry Andric bool MayHaveConflictingAAMD = false;
10319dc417c3SDimitry Andric if (MMO->getAAInfo()) {
10329dc417c3SDimitry Andric if (const Value *MMOV = MMO->getValue()) {
10339dc417c3SDimitry Andric SmallVector<Value *, 4> Objs;
10349dc417c3SDimitry Andric getUnderlyingObjectsForCodeGen(MMOV, Objs, MF->getDataLayout());
10359dc417c3SDimitry Andric
10369dc417c3SDimitry Andric if (Objs.empty())
10379dc417c3SDimitry Andric MayHaveConflictingAAMD = true;
10389dc417c3SDimitry Andric else
10399dc417c3SDimitry Andric for (Value *V : Objs) {
10409dc417c3SDimitry Andric // If this memory location comes from a known stack slot
10419dc417c3SDimitry Andric // that is not remapped, we continue checking.
10429dc417c3SDimitry Andric // Otherwise, we need to invalidate AA infomation.
10439dc417c3SDimitry Andric const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(V);
10449dc417c3SDimitry Andric if (AI && MergedAllocas.count(AI)) {
10459dc417c3SDimitry Andric MayHaveConflictingAAMD = true;
10469dc417c3SDimitry Andric break;
10479dc417c3SDimitry Andric }
10489dc417c3SDimitry Andric }
10499dc417c3SDimitry Andric }
10509dc417c3SDimitry Andric }
10519dc417c3SDimitry Andric if (MayHaveConflictingAAMD) {
1052*b5893f02SDimitry Andric NewMMOs.push_back(MF->getMachineMemOperand(MMO, AAMDNodes()));
10539dc417c3SDimitry Andric ReplaceMemOps = true;
1054*b5893f02SDimitry Andric } else {
1055*b5893f02SDimitry Andric NewMMOs.push_back(MMO);
10569dc417c3SDimitry Andric }
10579dc417c3SDimitry Andric }
10589dc417c3SDimitry Andric
10599dc417c3SDimitry Andric // If any memory operand is updated, set memory references of
10609dc417c3SDimitry Andric // this instruction.
10619dc417c3SDimitry Andric if (ReplaceMemOps)
1062*b5893f02SDimitry Andric I.setMemRefs(*MF, NewMMOs);
10633861d79fSDimitry Andric }
10643861d79fSDimitry Andric
1065444ed5c5SDimitry Andric // Update the location of C++ catch objects for the MSVC personality routine.
1066444ed5c5SDimitry Andric if (WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo())
1067444ed5c5SDimitry Andric for (WinEHTryBlockMapEntry &TBME : EHInfo->TryBlockMap)
1068444ed5c5SDimitry Andric for (WinEHHandlerType &H : TBME.HandlerArray)
10692cab237bSDimitry Andric if (H.CatchObj.FrameIndex != std::numeric_limits<int>::max() &&
1070444ed5c5SDimitry Andric SlotRemap.count(H.CatchObj.FrameIndex))
1071444ed5c5SDimitry Andric H.CatchObj.FrameIndex = SlotRemap[H.CatchObj.FrameIndex];
1072444ed5c5SDimitry Andric
10734ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Fixed " << FixedMemOp << " machine memory operands.\n");
10744ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Fixed " << FixedDbg << " debug locations.\n");
10754ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Fixed " << FixedInstr << " machine instructions.\n");
10763861d79fSDimitry Andric }
10773861d79fSDimitry Andric
removeInvalidSlotRanges()10783861d79fSDimitry Andric void StackColoring::removeInvalidSlotRanges() {
107991bc56edSDimitry Andric for (MachineBasicBlock &BB : *MF)
108091bc56edSDimitry Andric for (MachineInstr &I : BB) {
108191bc56edSDimitry Andric if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
10824ba319b5SDimitry Andric I.getOpcode() == TargetOpcode::LIFETIME_END || I.isDebugInstr())
10833861d79fSDimitry Andric continue;
10843861d79fSDimitry Andric
10853861d79fSDimitry Andric // Some intervals are suspicious! In some cases we find address
10863861d79fSDimitry Andric // calculations outside of the lifetime zone, but not actual memory
10873861d79fSDimitry Andric // read or write. Memory accesses outside of the lifetime zone are a clear
10883861d79fSDimitry Andric // violation, but address calculations are okay. This can happen when
10893861d79fSDimitry Andric // GEPs are hoisted outside of the lifetime zone.
10903861d79fSDimitry Andric // So, in here we only check instructions which can read or write memory.
109191bc56edSDimitry Andric if (!I.mayLoad() && !I.mayStore())
10923861d79fSDimitry Andric continue;
10933861d79fSDimitry Andric
10943861d79fSDimitry Andric // Check all of the machine operands.
109591bc56edSDimitry Andric for (const MachineOperand &MO : I.operands()) {
10963861d79fSDimitry Andric if (!MO.isFI())
10973861d79fSDimitry Andric continue;
10983861d79fSDimitry Andric
10993861d79fSDimitry Andric int Slot = MO.getIndex();
11003861d79fSDimitry Andric
11013861d79fSDimitry Andric if (Slot<0)
11023861d79fSDimitry Andric continue;
11033861d79fSDimitry Andric
11043861d79fSDimitry Andric if (Intervals[Slot]->empty())
11053861d79fSDimitry Andric continue;
11063861d79fSDimitry Andric
11073861d79fSDimitry Andric // Check that the used slot is inside the calculated lifetime range.
11083861d79fSDimitry Andric // If it is not, warn about it and invalidate the range.
110991bc56edSDimitry Andric LiveInterval *Interval = &*Intervals[Slot];
11103ca95b02SDimitry Andric SlotIndex Index = Indexes->getInstructionIndex(I);
11113861d79fSDimitry Andric if (Interval->find(Index) == Interval->end()) {
111291bc56edSDimitry Andric Interval->clear();
11134ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Invalidating range #" << Slot << "\n");
11143861d79fSDimitry Andric EscapedAllocas++;
11153861d79fSDimitry Andric }
11163861d79fSDimitry Andric }
11173861d79fSDimitry Andric }
11183861d79fSDimitry Andric }
11193861d79fSDimitry Andric
expungeSlotMap(DenseMap<int,int> & SlotRemap,unsigned NumSlots)11203861d79fSDimitry Andric void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
11213861d79fSDimitry Andric unsigned NumSlots) {
11223861d79fSDimitry Andric // Expunge slot remap map.
11233861d79fSDimitry Andric for (unsigned i=0; i < NumSlots; ++i) {
11243861d79fSDimitry Andric // If we are remapping i
11253861d79fSDimitry Andric if (SlotRemap.count(i)) {
11263861d79fSDimitry Andric int Target = SlotRemap[i];
11273861d79fSDimitry Andric // As long as our target is mapped to something else, follow it.
11283861d79fSDimitry Andric while (SlotRemap.count(Target)) {
11293861d79fSDimitry Andric Target = SlotRemap[Target];
11303861d79fSDimitry Andric SlotRemap[i] = Target;
11313861d79fSDimitry Andric }
11323861d79fSDimitry Andric }
11333861d79fSDimitry Andric }
11343861d79fSDimitry Andric }
11353861d79fSDimitry Andric
runOnMachineFunction(MachineFunction & Func)11363861d79fSDimitry Andric bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
11374ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "********** Stack Coloring **********\n"
11382cab237bSDimitry Andric << "********** Function: " << Func.getName() << '\n');
11393861d79fSDimitry Andric MF = &Func;
1140d88c1a5aSDimitry Andric MFI = &MF->getFrameInfo();
11413861d79fSDimitry Andric Indexes = &getAnalysis<SlotIndexes>();
11423861d79fSDimitry Andric BlockLiveness.clear();
11433861d79fSDimitry Andric BasicBlocks.clear();
11443861d79fSDimitry Andric BasicBlockNumbering.clear();
11453861d79fSDimitry Andric Markers.clear();
11463861d79fSDimitry Andric Intervals.clear();
114724d58133SDimitry Andric LiveStarts.clear();
11483861d79fSDimitry Andric VNInfoAllocator.Reset();
11493861d79fSDimitry Andric
11503861d79fSDimitry Andric unsigned NumSlots = MFI->getObjectIndexEnd();
11513861d79fSDimitry Andric
11523861d79fSDimitry Andric // If there are no stack slots then there are no markers to remove.
11533861d79fSDimitry Andric if (!NumSlots)
11543861d79fSDimitry Andric return false;
11553861d79fSDimitry Andric
11563861d79fSDimitry Andric SmallVector<int, 8> SortedSlots;
11573861d79fSDimitry Andric SortedSlots.reserve(NumSlots);
11583861d79fSDimitry Andric Intervals.reserve(NumSlots);
115924d58133SDimitry Andric LiveStarts.resize(NumSlots);
11603861d79fSDimitry Andric
11613861d79fSDimitry Andric unsigned NumMarkers = collectMarkers(NumSlots);
11623861d79fSDimitry Andric
11633861d79fSDimitry Andric unsigned TotalSize = 0;
11644ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Found " << NumMarkers << " markers and " << NumSlots
11654ba319b5SDimitry Andric << " slots\n");
11664ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Slot structure:\n");
11673861d79fSDimitry Andric
11683861d79fSDimitry Andric for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
11694ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Slot #" << i << " - " << MFI->getObjectSize(i)
11704ba319b5SDimitry Andric << " bytes.\n");
11713861d79fSDimitry Andric TotalSize += MFI->getObjectSize(i);
11723861d79fSDimitry Andric }
11733861d79fSDimitry Andric
11744ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Total Stack size: " << TotalSize << " bytes\n\n");
11753861d79fSDimitry Andric
11763861d79fSDimitry Andric // Don't continue because there are not enough lifetime markers, or the
11773861d79fSDimitry Andric // stack is too small, or we are told not to optimize the slots.
11783ca95b02SDimitry Andric if (NumMarkers < 2 || TotalSize < 16 || DisableColoring ||
11792cab237bSDimitry Andric skipFunction(Func.getFunction())) {
11804ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Will not try to merge slots.\n");
11813861d79fSDimitry Andric return removeAllMarkers();
11823861d79fSDimitry Andric }
11833861d79fSDimitry Andric
11843861d79fSDimitry Andric for (unsigned i=0; i < NumSlots; ++i) {
118591bc56edSDimitry Andric std::unique_ptr<LiveInterval> LI(new LiveInterval(i, 0));
11863861d79fSDimitry Andric LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
118791bc56edSDimitry Andric Intervals.push_back(std::move(LI));
11883861d79fSDimitry Andric SortedSlots.push_back(i);
11893861d79fSDimitry Andric }
11903861d79fSDimitry Andric
11913861d79fSDimitry Andric // Calculate the liveness of each block.
11923861d79fSDimitry Andric calculateLocalLiveness();
11934ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Dataflow iterations: " << NumIterations << "\n");
11944ba319b5SDimitry Andric LLVM_DEBUG(dump());
11953861d79fSDimitry Andric
11963861d79fSDimitry Andric // Propagate the liveness information.
11973861d79fSDimitry Andric calculateLiveIntervals(NumSlots);
11984ba319b5SDimitry Andric LLVM_DEBUG(dumpIntervals());
11993861d79fSDimitry Andric
12003861d79fSDimitry Andric // Search for allocas which are used outside of the declared lifetime
12013861d79fSDimitry Andric // markers.
12023861d79fSDimitry Andric if (ProtectFromEscapedAllocas)
12033861d79fSDimitry Andric removeInvalidSlotRanges();
12043861d79fSDimitry Andric
12053861d79fSDimitry Andric // Maps old slots to new slots.
12063861d79fSDimitry Andric DenseMap<int, int> SlotRemap;
12073861d79fSDimitry Andric unsigned RemovedSlots = 0;
12083861d79fSDimitry Andric unsigned ReducedSize = 0;
12093861d79fSDimitry Andric
12103861d79fSDimitry Andric // Do not bother looking at empty intervals.
12113861d79fSDimitry Andric for (unsigned I = 0; I < NumSlots; ++I) {
12123861d79fSDimitry Andric if (Intervals[SortedSlots[I]]->empty())
12133861d79fSDimitry Andric SortedSlots[I] = -1;
12143861d79fSDimitry Andric }
12153861d79fSDimitry Andric
12163861d79fSDimitry Andric // This is a simple greedy algorithm for merging allocas. First, sort the
12173861d79fSDimitry Andric // slots, placing the largest slots first. Next, perform an n^2 scan and look
12183861d79fSDimitry Andric // for disjoint slots. When you find disjoint slots, merge the samller one
12193861d79fSDimitry Andric // into the bigger one and update the live interval. Remove the small alloca
12203861d79fSDimitry Andric // and continue.
12213861d79fSDimitry Andric
12223861d79fSDimitry Andric // Sort the slots according to their size. Place unused slots at the end.
1223139f7f9bSDimitry Andric // Use stable sort to guarantee deterministic code generation.
1224139f7f9bSDimitry Andric std::stable_sort(SortedSlots.begin(), SortedSlots.end(),
122591bc56edSDimitry Andric [this](int LHS, int RHS) {
122691bc56edSDimitry Andric // We use -1 to denote a uninteresting slot. Place these slots at the end.
122791bc56edSDimitry Andric if (LHS == -1) return false;
122891bc56edSDimitry Andric if (RHS == -1) return true;
122991bc56edSDimitry Andric // Sort according to size.
123091bc56edSDimitry Andric return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS);
123191bc56edSDimitry Andric });
12323861d79fSDimitry Andric
123324d58133SDimitry Andric for (auto &s : LiveStarts)
1234*b5893f02SDimitry Andric llvm::sort(s);
123524d58133SDimitry Andric
1236139f7f9bSDimitry Andric bool Changed = true;
1237139f7f9bSDimitry Andric while (Changed) {
1238139f7f9bSDimitry Andric Changed = false;
12393861d79fSDimitry Andric for (unsigned I = 0; I < NumSlots; ++I) {
12403861d79fSDimitry Andric if (SortedSlots[I] == -1)
12413861d79fSDimitry Andric continue;
12423861d79fSDimitry Andric
12433861d79fSDimitry Andric for (unsigned J=I+1; J < NumSlots; ++J) {
12443861d79fSDimitry Andric if (SortedSlots[J] == -1)
12453861d79fSDimitry Andric continue;
12463861d79fSDimitry Andric
12473861d79fSDimitry Andric int FirstSlot = SortedSlots[I];
12483861d79fSDimitry Andric int SecondSlot = SortedSlots[J];
124991bc56edSDimitry Andric LiveInterval *First = &*Intervals[FirstSlot];
125091bc56edSDimitry Andric LiveInterval *Second = &*Intervals[SecondSlot];
125124d58133SDimitry Andric auto &FirstS = LiveStarts[FirstSlot];
125224d58133SDimitry Andric auto &SecondS = LiveStarts[SecondSlot];
12533861d79fSDimitry Andric assert(!First->empty() && !Second->empty() && "Found an empty range");
12543861d79fSDimitry Andric
125524d58133SDimitry Andric // Merge disjoint slots. This is a little bit tricky - see the
125624d58133SDimitry Andric // Implementation Notes section for an explanation.
125724d58133SDimitry Andric if (!First->isLiveAtIndexes(SecondS) &&
125824d58133SDimitry Andric !Second->isLiveAtIndexes(FirstS)) {
1259139f7f9bSDimitry Andric Changed = true;
1260f785676fSDimitry Andric First->MergeSegmentsInAsValue(*Second, First->getValNumInfo(0));
126124d58133SDimitry Andric
126224d58133SDimitry Andric int OldSize = FirstS.size();
126324d58133SDimitry Andric FirstS.append(SecondS.begin(), SecondS.end());
126424d58133SDimitry Andric auto Mid = FirstS.begin() + OldSize;
126524d58133SDimitry Andric std::inplace_merge(FirstS.begin(), Mid, FirstS.end());
126624d58133SDimitry Andric
12673861d79fSDimitry Andric SlotRemap[SecondSlot] = FirstSlot;
12683861d79fSDimitry Andric SortedSlots[J] = -1;
12694ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Merging #" << FirstSlot << " and slots #"
12704ba319b5SDimitry Andric << SecondSlot << " together.\n");
12713861d79fSDimitry Andric unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot),
12723861d79fSDimitry Andric MFI->getObjectAlignment(SecondSlot));
12733861d79fSDimitry Andric
12743861d79fSDimitry Andric assert(MFI->getObjectSize(FirstSlot) >=
12753861d79fSDimitry Andric MFI->getObjectSize(SecondSlot) &&
12763861d79fSDimitry Andric "Merging a small object into a larger one");
12773861d79fSDimitry Andric
12783861d79fSDimitry Andric RemovedSlots+=1;
12793861d79fSDimitry Andric ReducedSize += MFI->getObjectSize(SecondSlot);
12803861d79fSDimitry Andric MFI->setObjectAlignment(FirstSlot, MaxAlignment);
12813861d79fSDimitry Andric MFI->RemoveStackObject(SecondSlot);
12823861d79fSDimitry Andric }
12833861d79fSDimitry Andric }
12843861d79fSDimitry Andric }
12853861d79fSDimitry Andric }// While changed.
12863861d79fSDimitry Andric
12873861d79fSDimitry Andric // Record statistics.
12883861d79fSDimitry Andric StackSpaceSaved += ReducedSize;
12893861d79fSDimitry Andric StackSlotMerged += RemovedSlots;
12904ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Merge " << RemovedSlots << " slots. Saved "
12914ba319b5SDimitry Andric << ReducedSize << " bytes\n");
12923861d79fSDimitry Andric
12933861d79fSDimitry Andric // Scan the entire function and update all machine operands that use frame
12943861d79fSDimitry Andric // indices to use the remapped frame index.
12953861d79fSDimitry Andric expungeSlotMap(SlotRemap, NumSlots);
12963861d79fSDimitry Andric remapInstructions(SlotRemap);
12973861d79fSDimitry Andric
12983861d79fSDimitry Andric return removeAllMarkers();
12993861d79fSDimitry Andric }
1300