StackColoring.cpp 48 KB

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