StackSlotColoring.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. //===-- StackSlotColoring.cpp - Stack slot coloring pass. -----------------===//
  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 file implements the stack slot coloring pass.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #define DEBUG_TYPE "stackslotcoloring"
  14. #include "llvm/CodeGen/Passes.h"
  15. #include "llvm/ADT/BitVector.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  19. #include "llvm/CodeGen/LiveStackAnalysis.h"
  20. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  21. #include "llvm/CodeGen/MachineFrameInfo.h"
  22. #include "llvm/CodeGen/MachineInstrBuilder.h"
  23. #include "llvm/CodeGen/MachineMemOperand.h"
  24. #include "llvm/CodeGen/MachineRegisterInfo.h"
  25. #include "llvm/CodeGen/PseudoSourceValue.h"
  26. #include "llvm/IR/Module.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include "llvm/Target/TargetInstrInfo.h"
  31. #include "llvm/Target/TargetMachine.h"
  32. #include <vector>
  33. using namespace llvm;
  34. static cl::opt<bool>
  35. DisableSharing("no-stack-slot-sharing",
  36. cl::init(false), cl::Hidden,
  37. cl::desc("Suppress slot sharing during stack coloring"));
  38. static cl::opt<int> DCELimit("ssc-dce-limit", cl::init(-1), cl::Hidden);
  39. STATISTIC(NumEliminated, "Number of stack slots eliminated due to coloring");
  40. STATISTIC(NumDead, "Number of trivially dead stack accesses eliminated");
  41. namespace {
  42. class StackSlotColoring : public MachineFunctionPass {
  43. LiveStacks* LS;
  44. MachineFrameInfo *MFI;
  45. const TargetInstrInfo *TII;
  46. const MachineBlockFrequencyInfo *MBFI;
  47. // SSIntervals - Spill slot intervals.
  48. std::vector<LiveInterval*> SSIntervals;
  49. // SSRefs - Keep a list of MachineMemOperands for each spill slot.
  50. // MachineMemOperands can be shared between instructions, so we need
  51. // to be careful that renames like [FI0, FI1] -> [FI1, FI2] do not
  52. // become FI0 -> FI1 -> FI2.
  53. SmallVector<SmallVector<MachineMemOperand *, 8>, 16> SSRefs;
  54. // OrigAlignments - Alignments of stack objects before coloring.
  55. SmallVector<unsigned, 16> OrigAlignments;
  56. // OrigSizes - Sizess of stack objects before coloring.
  57. SmallVector<unsigned, 16> OrigSizes;
  58. // AllColors - If index is set, it's a spill slot, i.e. color.
  59. // FIXME: This assumes PEI locate spill slot with smaller indices
  60. // closest to stack pointer / frame pointer. Therefore, smaller
  61. // index == better color.
  62. BitVector AllColors;
  63. // NextColor - Next "color" that's not yet used.
  64. int NextColor;
  65. // UsedColors - "Colors" that have been assigned.
  66. BitVector UsedColors;
  67. // Assignments - Color to intervals mapping.
  68. SmallVector<SmallVector<LiveInterval*,4>, 16> Assignments;
  69. public:
  70. static char ID; // Pass identification
  71. StackSlotColoring() :
  72. MachineFunctionPass(ID), NextColor(-1) {
  73. initializeStackSlotColoringPass(*PassRegistry::getPassRegistry());
  74. }
  75. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  76. AU.setPreservesCFG();
  77. AU.addRequired<SlotIndexes>();
  78. AU.addPreserved<SlotIndexes>();
  79. AU.addRequired<LiveStacks>();
  80. AU.addRequired<MachineBlockFrequencyInfo>();
  81. AU.addPreserved<MachineBlockFrequencyInfo>();
  82. AU.addPreservedID(MachineDominatorsID);
  83. MachineFunctionPass::getAnalysisUsage(AU);
  84. }
  85. virtual bool runOnMachineFunction(MachineFunction &MF);
  86. private:
  87. void InitializeSlots();
  88. void ScanForSpillSlotRefs(MachineFunction &MF);
  89. bool OverlapWithAssignments(LiveInterval *li, int Color) const;
  90. int ColorSlot(LiveInterval *li);
  91. bool ColorSlots(MachineFunction &MF);
  92. void RewriteInstruction(MachineInstr *MI, SmallVectorImpl<int> &SlotMapping,
  93. MachineFunction &MF);
  94. bool RemoveDeadStores(MachineBasicBlock* MBB);
  95. };
  96. } // end anonymous namespace
  97. char StackSlotColoring::ID = 0;
  98. char &llvm::StackSlotColoringID = StackSlotColoring::ID;
  99. INITIALIZE_PASS_BEGIN(StackSlotColoring, "stack-slot-coloring",
  100. "Stack Slot Coloring", false, false)
  101. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  102. INITIALIZE_PASS_DEPENDENCY(LiveStacks)
  103. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  104. INITIALIZE_PASS_END(StackSlotColoring, "stack-slot-coloring",
  105. "Stack Slot Coloring", false, false)
  106. namespace {
  107. // IntervalSorter - Comparison predicate that sort live intervals by
  108. // their weight.
  109. struct IntervalSorter {
  110. bool operator()(LiveInterval* LHS, LiveInterval* RHS) const {
  111. return LHS->weight > RHS->weight;
  112. }
  113. };
  114. }
  115. /// ScanForSpillSlotRefs - Scan all the machine instructions for spill slot
  116. /// references and update spill slot weights.
  117. void StackSlotColoring::ScanForSpillSlotRefs(MachineFunction &MF) {
  118. SSRefs.resize(MFI->getObjectIndexEnd());
  119. // FIXME: Need the equivalent of MachineRegisterInfo for frameindex operands.
  120. for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
  121. MBBI != E; ++MBBI) {
  122. MachineBasicBlock *MBB = &*MBBI;
  123. BlockFrequency Freq = MBFI->getBlockFreq(MBB);
  124. for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
  125. MII != EE; ++MII) {
  126. MachineInstr *MI = &*MII;
  127. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  128. MachineOperand &MO = MI->getOperand(i);
  129. if (!MO.isFI())
  130. continue;
  131. int FI = MO.getIndex();
  132. if (FI < 0)
  133. continue;
  134. if (!LS->hasInterval(FI))
  135. continue;
  136. LiveInterval &li = LS->getInterval(FI);
  137. if (!MI->isDebugValue())
  138. li.weight += LiveIntervals::getSpillWeight(false, true, Freq);
  139. }
  140. for (MachineInstr::mmo_iterator MMOI = MI->memoperands_begin(),
  141. EE = MI->memoperands_end(); MMOI != EE; ++MMOI) {
  142. MachineMemOperand *MMO = *MMOI;
  143. if (const Value *V = MMO->getValue()) {
  144. if (const FixedStackPseudoSourceValue *FSV =
  145. dyn_cast<FixedStackPseudoSourceValue>(V)) {
  146. int FI = FSV->getFrameIndex();
  147. if (FI >= 0)
  148. SSRefs[FI].push_back(MMO);
  149. }
  150. }
  151. }
  152. }
  153. }
  154. }
  155. /// InitializeSlots - Process all spill stack slot liveintervals and add them
  156. /// to a sorted (by weight) list.
  157. void StackSlotColoring::InitializeSlots() {
  158. int LastFI = MFI->getObjectIndexEnd();
  159. OrigAlignments.resize(LastFI);
  160. OrigSizes.resize(LastFI);
  161. AllColors.resize(LastFI);
  162. UsedColors.resize(LastFI);
  163. Assignments.resize(LastFI);
  164. // Gather all spill slots into a list.
  165. DEBUG(dbgs() << "Spill slot intervals:\n");
  166. for (LiveStacks::iterator i = LS->begin(), e = LS->end(); i != e; ++i) {
  167. LiveInterval &li = i->second;
  168. DEBUG(li.dump());
  169. int FI = TargetRegisterInfo::stackSlot2Index(li.reg);
  170. if (MFI->isDeadObjectIndex(FI))
  171. continue;
  172. SSIntervals.push_back(&li);
  173. OrigAlignments[FI] = MFI->getObjectAlignment(FI);
  174. OrigSizes[FI] = MFI->getObjectSize(FI);
  175. AllColors.set(FI);
  176. }
  177. DEBUG(dbgs() << '\n');
  178. // Sort them by weight.
  179. std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
  180. // Get first "color".
  181. NextColor = AllColors.find_first();
  182. }
  183. /// OverlapWithAssignments - Return true if LiveInterval overlaps with any
  184. /// LiveIntervals that have already been assigned to the specified color.
  185. bool
  186. StackSlotColoring::OverlapWithAssignments(LiveInterval *li, int Color) const {
  187. const SmallVectorImpl<LiveInterval *> &OtherLIs = Assignments[Color];
  188. for (unsigned i = 0, e = OtherLIs.size(); i != e; ++i) {
  189. LiveInterval *OtherLI = OtherLIs[i];
  190. if (OtherLI->overlaps(*li))
  191. return true;
  192. }
  193. return false;
  194. }
  195. /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
  196. ///
  197. int StackSlotColoring::ColorSlot(LiveInterval *li) {
  198. int Color = -1;
  199. bool Share = false;
  200. if (!DisableSharing) {
  201. // Check if it's possible to reuse any of the used colors.
  202. Color = UsedColors.find_first();
  203. while (Color != -1) {
  204. if (!OverlapWithAssignments(li, Color)) {
  205. Share = true;
  206. ++NumEliminated;
  207. break;
  208. }
  209. Color = UsedColors.find_next(Color);
  210. }
  211. }
  212. // Assign it to the first available color (assumed to be the best) if it's
  213. // not possible to share a used color with other objects.
  214. if (!Share) {
  215. assert(NextColor != -1 && "No more spill slots?");
  216. Color = NextColor;
  217. UsedColors.set(Color);
  218. NextColor = AllColors.find_next(NextColor);
  219. }
  220. // Record the assignment.
  221. Assignments[Color].push_back(li);
  222. int FI = TargetRegisterInfo::stackSlot2Index(li->reg);
  223. DEBUG(dbgs() << "Assigning fi#" << FI << " to fi#" << Color << "\n");
  224. // Change size and alignment of the allocated slot. If there are multiple
  225. // objects sharing the same slot, then make sure the size and alignment
  226. // are large enough for all.
  227. unsigned Align = OrigAlignments[FI];
  228. if (!Share || Align > MFI->getObjectAlignment(Color))
  229. MFI->setObjectAlignment(Color, Align);
  230. int64_t Size = OrigSizes[FI];
  231. if (!Share || Size > MFI->getObjectSize(Color))
  232. MFI->setObjectSize(Color, Size);
  233. return Color;
  234. }
  235. /// Colorslots - Color all spill stack slots and rewrite all frameindex machine
  236. /// operands in the function.
  237. bool StackSlotColoring::ColorSlots(MachineFunction &MF) {
  238. unsigned NumObjs = MFI->getObjectIndexEnd();
  239. SmallVector<int, 16> SlotMapping(NumObjs, -1);
  240. SmallVector<float, 16> SlotWeights(NumObjs, 0.0);
  241. SmallVector<SmallVector<int, 4>, 16> RevMap(NumObjs);
  242. BitVector UsedColors(NumObjs);
  243. DEBUG(dbgs() << "Color spill slot intervals:\n");
  244. bool Changed = false;
  245. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
  246. LiveInterval *li = SSIntervals[i];
  247. int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
  248. int NewSS = ColorSlot(li);
  249. assert(NewSS >= 0 && "Stack coloring failed?");
  250. SlotMapping[SS] = NewSS;
  251. RevMap[NewSS].push_back(SS);
  252. SlotWeights[NewSS] += li->weight;
  253. UsedColors.set(NewSS);
  254. Changed |= (SS != NewSS);
  255. }
  256. DEBUG(dbgs() << "\nSpill slots after coloring:\n");
  257. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
  258. LiveInterval *li = SSIntervals[i];
  259. int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
  260. li->weight = SlotWeights[SS];
  261. }
  262. // Sort them by new weight.
  263. std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
  264. #ifndef NDEBUG
  265. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i)
  266. DEBUG(SSIntervals[i]->dump());
  267. DEBUG(dbgs() << '\n');
  268. #endif
  269. if (!Changed)
  270. return false;
  271. // Rewrite all MachineMemOperands.
  272. for (unsigned SS = 0, SE = SSRefs.size(); SS != SE; ++SS) {
  273. int NewFI = SlotMapping[SS];
  274. if (NewFI == -1 || (NewFI == (int)SS))
  275. continue;
  276. const Value *NewSV = PseudoSourceValue::getFixedStack(NewFI);
  277. SmallVectorImpl<MachineMemOperand *> &RefMMOs = SSRefs[SS];
  278. for (unsigned i = 0, e = RefMMOs.size(); i != e; ++i)
  279. RefMMOs[i]->setValue(NewSV);
  280. }
  281. // Rewrite all MO_FrameIndex operands. Look for dead stores.
  282. for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
  283. MBBI != E; ++MBBI) {
  284. MachineBasicBlock *MBB = &*MBBI;
  285. for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
  286. MII != EE; ++MII)
  287. RewriteInstruction(MII, SlotMapping, MF);
  288. RemoveDeadStores(MBB);
  289. }
  290. // Delete unused stack slots.
  291. while (NextColor != -1) {
  292. DEBUG(dbgs() << "Removing unused stack object fi#" << NextColor << "\n");
  293. MFI->RemoveStackObject(NextColor);
  294. NextColor = AllColors.find_next(NextColor);
  295. }
  296. return true;
  297. }
  298. /// RewriteInstruction - Rewrite specified instruction by replacing references
  299. /// to old frame index with new one.
  300. void StackSlotColoring::RewriteInstruction(MachineInstr *MI,
  301. SmallVectorImpl<int> &SlotMapping,
  302. MachineFunction &MF) {
  303. // Update the operands.
  304. for (unsigned i = 0, ee = MI->getNumOperands(); i != ee; ++i) {
  305. MachineOperand &MO = MI->getOperand(i);
  306. if (!MO.isFI())
  307. continue;
  308. int OldFI = MO.getIndex();
  309. if (OldFI < 0)
  310. continue;
  311. int NewFI = SlotMapping[OldFI];
  312. if (NewFI == -1 || NewFI == OldFI)
  313. continue;
  314. MO.setIndex(NewFI);
  315. }
  316. // The MachineMemOperands have already been updated.
  317. }
  318. /// RemoveDeadStores - Scan through a basic block and look for loads followed
  319. /// by stores. If they're both using the same stack slot, then the store is
  320. /// definitely dead. This could obviously be much more aggressive (consider
  321. /// pairs with instructions between them), but such extensions might have a
  322. /// considerable compile time impact.
  323. bool StackSlotColoring::RemoveDeadStores(MachineBasicBlock* MBB) {
  324. // FIXME: This could be much more aggressive, but we need to investigate
  325. // the compile time impact of doing so.
  326. bool changed = false;
  327. SmallVector<MachineInstr*, 4> toErase;
  328. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
  329. I != E; ++I) {
  330. if (DCELimit != -1 && (int)NumDead >= DCELimit)
  331. break;
  332. int FirstSS, SecondSS;
  333. if (TII->isStackSlotCopy(I, FirstSS, SecondSS) &&
  334. FirstSS == SecondSS &&
  335. FirstSS != -1) {
  336. ++NumDead;
  337. changed = true;
  338. toErase.push_back(I);
  339. continue;
  340. }
  341. MachineBasicBlock::iterator NextMI = llvm::next(I);
  342. if (NextMI == MBB->end()) continue;
  343. unsigned LoadReg = 0;
  344. unsigned StoreReg = 0;
  345. if (!(LoadReg = TII->isLoadFromStackSlot(I, FirstSS))) continue;
  346. if (!(StoreReg = TII->isStoreToStackSlot(NextMI, SecondSS))) continue;
  347. if (FirstSS != SecondSS || LoadReg != StoreReg || FirstSS == -1) continue;
  348. ++NumDead;
  349. changed = true;
  350. if (NextMI->findRegisterUseOperandIdx(LoadReg, true, 0) != -1) {
  351. ++NumDead;
  352. toErase.push_back(I);
  353. }
  354. toErase.push_back(NextMI);
  355. ++I;
  356. }
  357. for (SmallVectorImpl<MachineInstr *>::iterator I = toErase.begin(),
  358. E = toErase.end(); I != E; ++I)
  359. (*I)->eraseFromParent();
  360. return changed;
  361. }
  362. bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
  363. DEBUG({
  364. dbgs() << "********** Stack Slot Coloring **********\n"
  365. << "********** Function: " << MF.getName() << '\n';
  366. });
  367. MFI = MF.getFrameInfo();
  368. TII = MF.getTarget().getInstrInfo();
  369. LS = &getAnalysis<LiveStacks>();
  370. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  371. bool Changed = false;
  372. unsigned NumSlots = LS->getNumIntervals();
  373. if (NumSlots == 0)
  374. // Nothing to do!
  375. return false;
  376. // If there are calls to setjmp or sigsetjmp, don't perform stack slot
  377. // coloring. The stack could be modified before the longjmp is executed,
  378. // resulting in the wrong value being used afterwards. (See
  379. // <rdar://problem/8007500>.)
  380. if (MF.exposesReturnsTwice())
  381. return false;
  382. // Gather spill slot references
  383. ScanForSpillSlotRefs(MF);
  384. InitializeSlots();
  385. Changed = ColorSlots(MF);
  386. NextColor = -1;
  387. SSIntervals.clear();
  388. for (unsigned i = 0, e = SSRefs.size(); i != e; ++i)
  389. SSRefs[i].clear();
  390. SSRefs.clear();
  391. OrigAlignments.clear();
  392. OrigSizes.clear();
  393. AllColors.clear();
  394. UsedColors.clear();
  395. for (unsigned i = 0, e = Assignments.size(); i != e; ++i)
  396. Assignments[i].clear();
  397. Assignments.clear();
  398. return Changed;
  399. }