StackSlotColoring.cpp 15 KB

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