StackSlotColoring.cpp 15 KB

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