StackColoring.cpp 48 KB

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