StackSlotColoring.cpp 15 KB

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