StackSlotColoring.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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<bool>
  41. ColorWithRegsOpt("color-ss-with-regs",
  42. cl::init(false), cl::Hidden,
  43. cl::desc("Color stack slots with free registers"));
  44. static cl::opt<int> DCELimit("ssc-dce-limit", cl::init(-1), cl::Hidden);
  45. STATISTIC(NumEliminated, "Number of stack slots eliminated due to coloring");
  46. STATISTIC(NumRegRepl, "Number of stack slot refs replaced with reg refs");
  47. STATISTIC(NumLoadElim, "Number of loads eliminated");
  48. STATISTIC(NumStoreElim, "Number of stores eliminated");
  49. STATISTIC(NumDead, "Number of trivially dead stack accesses eliminated");
  50. namespace {
  51. class StackSlotColoring : public MachineFunctionPass {
  52. bool ColorWithRegs;
  53. LiveStacks* LS;
  54. VirtRegMap* VRM;
  55. MachineFrameInfo *MFI;
  56. MachineRegisterInfo *MRI;
  57. const TargetInstrInfo *TII;
  58. const TargetRegisterInfo *TRI;
  59. const MachineLoopInfo *loopInfo;
  60. // SSIntervals - Spill slot intervals.
  61. std::vector<LiveInterval*> SSIntervals;
  62. // SSRefs - Keep a list of frame index references for each spill slot.
  63. SmallVector<SmallVector<MachineInstr*, 8>, 16> SSRefs;
  64. // OrigAlignments - Alignments of stack objects before coloring.
  65. SmallVector<unsigned, 16> OrigAlignments;
  66. // OrigSizes - Sizess of stack objects before coloring.
  67. SmallVector<unsigned, 16> OrigSizes;
  68. // AllColors - If index is set, it's a spill slot, i.e. color.
  69. // FIXME: This assumes PEI locate spill slot with smaller indices
  70. // closest to stack pointer / frame pointer. Therefore, smaller
  71. // index == better color.
  72. BitVector AllColors;
  73. // NextColor - Next "color" that's not yet used.
  74. int NextColor;
  75. // UsedColors - "Colors" that have been assigned.
  76. BitVector UsedColors;
  77. // Assignments - Color to intervals mapping.
  78. SmallVector<SmallVector<LiveInterval*,4>, 16> Assignments;
  79. public:
  80. static char ID; // Pass identification
  81. StackSlotColoring() :
  82. MachineFunctionPass(ID), ColorWithRegs(false), NextColor(-1) {}
  83. StackSlotColoring(bool RegColor) :
  84. MachineFunctionPass(ID), ColorWithRegs(RegColor), NextColor(-1) {}
  85. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  86. AU.setPreservesCFG();
  87. AU.addRequired<SlotIndexes>();
  88. AU.addPreserved<SlotIndexes>();
  89. AU.addRequired<LiveStacks>();
  90. AU.addRequired<VirtRegMap>();
  91. AU.addPreserved<VirtRegMap>();
  92. AU.addRequired<MachineLoopInfo>();
  93. AU.addPreserved<MachineLoopInfo>();
  94. AU.addPreservedID(MachineDominatorsID);
  95. MachineFunctionPass::getAnalysisUsage(AU);
  96. }
  97. virtual bool runOnMachineFunction(MachineFunction &MF);
  98. virtual const char* getPassName() const {
  99. return "Stack Slot Coloring";
  100. }
  101. private:
  102. void InitializeSlots();
  103. void ScanForSpillSlotRefs(MachineFunction &MF);
  104. bool OverlapWithAssignments(LiveInterval *li, int Color) const;
  105. int ColorSlot(LiveInterval *li);
  106. bool ColorSlots(MachineFunction &MF);
  107. bool ColorSlotsWithFreeRegs(SmallVector<int, 16> &SlotMapping,
  108. SmallVector<SmallVector<int, 4>, 16> &RevMap,
  109. BitVector &SlotIsReg);
  110. void RewriteInstruction(MachineInstr *MI, int OldFI, int NewFI,
  111. MachineFunction &MF);
  112. bool PropagateBackward(MachineBasicBlock::iterator MII,
  113. MachineBasicBlock *MBB,
  114. unsigned OldReg, unsigned NewReg);
  115. bool PropagateForward(MachineBasicBlock::iterator MII,
  116. MachineBasicBlock *MBB,
  117. unsigned OldReg, unsigned NewReg);
  118. void UnfoldAndRewriteInstruction(MachineInstr *MI, int OldFI,
  119. unsigned Reg, const TargetRegisterClass *RC,
  120. SmallSet<unsigned, 4> &Defs,
  121. MachineFunction &MF);
  122. bool AllMemRefsCanBeUnfolded(int SS);
  123. bool RemoveDeadStores(MachineBasicBlock* MBB);
  124. };
  125. } // end anonymous namespace
  126. char StackSlotColoring::ID = 0;
  127. INITIALIZE_PASS_BEGIN(StackSlotColoring, "stack-slot-coloring",
  128. "Stack Slot Coloring", false, false)
  129. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  130. INITIALIZE_PASS_DEPENDENCY(LiveStacks)
  131. INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
  132. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  133. INITIALIZE_PASS_END(StackSlotColoring, "stack-slot-coloring",
  134. "Stack Slot Coloring", false, false)
  135. FunctionPass *llvm::createStackSlotColoringPass(bool RegColor) {
  136. return new StackSlotColoring(RegColor);
  137. }
  138. namespace {
  139. // IntervalSorter - Comparison predicate that sort live intervals by
  140. // their weight.
  141. struct IntervalSorter {
  142. bool operator()(LiveInterval* LHS, LiveInterval* RHS) const {
  143. return LHS->weight > RHS->weight;
  144. }
  145. };
  146. }
  147. /// ScanForSpillSlotRefs - Scan all the machine instructions for spill slot
  148. /// references and update spill slot weights.
  149. void StackSlotColoring::ScanForSpillSlotRefs(MachineFunction &MF) {
  150. SSRefs.resize(MFI->getObjectIndexEnd());
  151. // FIXME: Need the equivalent of MachineRegisterInfo for frameindex operands.
  152. for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
  153. MBBI != E; ++MBBI) {
  154. MachineBasicBlock *MBB = &*MBBI;
  155. unsigned loopDepth = loopInfo->getLoopDepth(MBB);
  156. for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
  157. MII != EE; ++MII) {
  158. MachineInstr *MI = &*MII;
  159. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  160. MachineOperand &MO = MI->getOperand(i);
  161. if (!MO.isFI())
  162. continue;
  163. int FI = MO.getIndex();
  164. if (FI < 0)
  165. continue;
  166. if (!LS->hasInterval(FI))
  167. continue;
  168. LiveInterval &li = LS->getInterval(FI);
  169. if (!MI->isDebugValue())
  170. li.weight += LiveIntervals::getSpillWeight(false, true, loopDepth);
  171. SSRefs[FI].push_back(MI);
  172. }
  173. }
  174. }
  175. }
  176. /// InitializeSlots - Process all spill stack slot liveintervals and add them
  177. /// to a sorted (by weight) list.
  178. void StackSlotColoring::InitializeSlots() {
  179. int LastFI = MFI->getObjectIndexEnd();
  180. OrigAlignments.resize(LastFI);
  181. OrigSizes.resize(LastFI);
  182. AllColors.resize(LastFI);
  183. UsedColors.resize(LastFI);
  184. Assignments.resize(LastFI);
  185. // Gather all spill slots into a list.
  186. DEBUG(dbgs() << "Spill slot intervals:\n");
  187. for (LiveStacks::iterator i = LS->begin(), e = LS->end(); i != e; ++i) {
  188. LiveInterval &li = i->second;
  189. DEBUG(li.dump());
  190. int FI = li.getStackSlotIndex();
  191. if (MFI->isDeadObjectIndex(FI))
  192. continue;
  193. SSIntervals.push_back(&li);
  194. OrigAlignments[FI] = MFI->getObjectAlignment(FI);
  195. OrigSizes[FI] = MFI->getObjectSize(FI);
  196. AllColors.set(FI);
  197. }
  198. DEBUG(dbgs() << '\n');
  199. // Sort them by weight.
  200. std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
  201. // Get first "color".
  202. NextColor = AllColors.find_first();
  203. }
  204. /// OverlapWithAssignments - Return true if LiveInterval overlaps with any
  205. /// LiveIntervals that have already been assigned to the specified color.
  206. bool
  207. StackSlotColoring::OverlapWithAssignments(LiveInterval *li, int Color) const {
  208. const SmallVector<LiveInterval*,4> &OtherLIs = Assignments[Color];
  209. for (unsigned i = 0, e = OtherLIs.size(); i != e; ++i) {
  210. LiveInterval *OtherLI = OtherLIs[i];
  211. if (OtherLI->overlaps(*li))
  212. return true;
  213. }
  214. return false;
  215. }
  216. /// ColorSlotsWithFreeRegs - If there are any free registers available, try
  217. /// replacing spill slots references with registers instead.
  218. bool
  219. StackSlotColoring::ColorSlotsWithFreeRegs(SmallVector<int, 16> &SlotMapping,
  220. SmallVector<SmallVector<int, 4>, 16> &RevMap,
  221. BitVector &SlotIsReg) {
  222. if (!(ColorWithRegs || ColorWithRegsOpt) || !VRM->HasUnusedRegisters())
  223. return false;
  224. bool Changed = false;
  225. DEBUG(dbgs() << "Assigning unused registers to spill slots:\n");
  226. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
  227. LiveInterval *li = SSIntervals[i];
  228. int SS = li->getStackSlotIndex();
  229. if (!UsedColors[SS] || li->weight < 20)
  230. // If the weight is < 20, i.e. two references in a loop with depth 1,
  231. // don't bother with it.
  232. continue;
  233. // These slots allow to share the same registers.
  234. bool AllColored = true;
  235. SmallVector<unsigned, 4> ColoredRegs;
  236. for (unsigned j = 0, ee = RevMap[SS].size(); j != ee; ++j) {
  237. int RSS = RevMap[SS][j];
  238. const TargetRegisterClass *RC = LS->getIntervalRegClass(RSS);
  239. // If it's not colored to another stack slot, try coloring it
  240. // to a "free" register.
  241. if (!RC) {
  242. AllColored = false;
  243. continue;
  244. }
  245. unsigned Reg = VRM->getFirstUnusedRegister(RC);
  246. if (!Reg) {
  247. AllColored = false;
  248. continue;
  249. }
  250. if (!AllMemRefsCanBeUnfolded(RSS)) {
  251. AllColored = false;
  252. continue;
  253. } else {
  254. DEBUG(dbgs() << "Assigning fi#" << RSS << " to "
  255. << TRI->getName(Reg) << '\n');
  256. ColoredRegs.push_back(Reg);
  257. SlotMapping[RSS] = Reg;
  258. SlotIsReg.set(RSS);
  259. Changed = true;
  260. }
  261. }
  262. // Register and its sub-registers are no longer free.
  263. while (!ColoredRegs.empty()) {
  264. unsigned Reg = ColoredRegs.back();
  265. ColoredRegs.pop_back();
  266. VRM->setRegisterUsed(Reg);
  267. // If reg is a callee-saved register, it will have to be spilled in
  268. // the prologue.
  269. MRI->setPhysRegUsed(Reg);
  270. for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
  271. VRM->setRegisterUsed(*AS);
  272. MRI->setPhysRegUsed(*AS);
  273. }
  274. }
  275. // This spill slot is dead after the rewrites
  276. if (AllColored) {
  277. MFI->RemoveStackObject(SS);
  278. ++NumEliminated;
  279. }
  280. }
  281. DEBUG(dbgs() << '\n');
  282. return Changed;
  283. }
  284. /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
  285. ///
  286. int StackSlotColoring::ColorSlot(LiveInterval *li) {
  287. int Color = -1;
  288. bool Share = false;
  289. if (!DisableSharing) {
  290. // Check if it's possible to reuse any of the used colors.
  291. Color = UsedColors.find_first();
  292. while (Color != -1) {
  293. if (!OverlapWithAssignments(li, Color)) {
  294. Share = true;
  295. ++NumEliminated;
  296. break;
  297. }
  298. Color = UsedColors.find_next(Color);
  299. }
  300. }
  301. // Assign it to the first available color (assumed to be the best) if it's
  302. // not possible to share a used color with other objects.
  303. if (!Share) {
  304. assert(NextColor != -1 && "No more spill slots?");
  305. Color = NextColor;
  306. UsedColors.set(Color);
  307. NextColor = AllColors.find_next(NextColor);
  308. }
  309. // Record the assignment.
  310. Assignments[Color].push_back(li);
  311. int FI = li->getStackSlotIndex();
  312. DEBUG(dbgs() << "Assigning fi#" << FI << " to fi#" << Color << "\n");
  313. // Change size and alignment of the allocated slot. If there are multiple
  314. // objects sharing the same slot, then make sure the size and alignment
  315. // are large enough for all.
  316. unsigned Align = OrigAlignments[FI];
  317. if (!Share || Align > MFI->getObjectAlignment(Color))
  318. MFI->setObjectAlignment(Color, Align);
  319. int64_t Size = OrigSizes[FI];
  320. if (!Share || Size > MFI->getObjectSize(Color))
  321. MFI->setObjectSize(Color, Size);
  322. return Color;
  323. }
  324. /// Colorslots - Color all spill stack slots and rewrite all frameindex machine
  325. /// operands in the function.
  326. bool StackSlotColoring::ColorSlots(MachineFunction &MF) {
  327. unsigned NumObjs = MFI->getObjectIndexEnd();
  328. SmallVector<int, 16> SlotMapping(NumObjs, -1);
  329. SmallVector<float, 16> SlotWeights(NumObjs, 0.0);
  330. SmallVector<SmallVector<int, 4>, 16> RevMap(NumObjs);
  331. BitVector SlotIsReg(NumObjs);
  332. BitVector UsedColors(NumObjs);
  333. DEBUG(dbgs() << "Color spill slot intervals:\n");
  334. bool Changed = false;
  335. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
  336. LiveInterval *li = SSIntervals[i];
  337. int SS = li->getStackSlotIndex();
  338. int NewSS = ColorSlot(li);
  339. assert(NewSS >= 0 && "Stack coloring failed?");
  340. SlotMapping[SS] = NewSS;
  341. RevMap[NewSS].push_back(SS);
  342. SlotWeights[NewSS] += li->weight;
  343. UsedColors.set(NewSS);
  344. Changed |= (SS != NewSS);
  345. }
  346. DEBUG(dbgs() << "\nSpill slots after coloring:\n");
  347. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
  348. LiveInterval *li = SSIntervals[i];
  349. int SS = li->getStackSlotIndex();
  350. li->weight = SlotWeights[SS];
  351. }
  352. // Sort them by new weight.
  353. std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
  354. #ifndef NDEBUG
  355. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i)
  356. DEBUG(SSIntervals[i]->dump());
  357. DEBUG(dbgs() << '\n');
  358. #endif
  359. // Can we "color" a stack slot with a unused register?
  360. Changed |= ColorSlotsWithFreeRegs(SlotMapping, RevMap, SlotIsReg);
  361. if (!Changed)
  362. return false;
  363. // Rewrite all MO_FrameIndex operands.
  364. SmallVector<SmallSet<unsigned, 4>, 4> NewDefs(MF.getNumBlockIDs());
  365. for (unsigned SS = 0, SE = SSRefs.size(); SS != SE; ++SS) {
  366. bool isReg = SlotIsReg[SS];
  367. int NewFI = SlotMapping[SS];
  368. if (NewFI == -1 || (NewFI == (int)SS && !isReg))
  369. continue;
  370. const TargetRegisterClass *RC = LS->getIntervalRegClass(SS);
  371. SmallVector<MachineInstr*, 8> &RefMIs = SSRefs[SS];
  372. for (unsigned i = 0, e = RefMIs.size(); i != e; ++i)
  373. if (!isReg)
  374. RewriteInstruction(RefMIs[i], SS, NewFI, MF);
  375. else {
  376. // Rewrite to use a register instead.
  377. unsigned MBBId = RefMIs[i]->getParent()->getNumber();
  378. SmallSet<unsigned, 4> &Defs = NewDefs[MBBId];
  379. UnfoldAndRewriteInstruction(RefMIs[i], SS, NewFI, RC, Defs, MF);
  380. }
  381. }
  382. // Delete unused stack slots.
  383. while (NextColor != -1) {
  384. DEBUG(dbgs() << "Removing unused stack object fi#" << NextColor << "\n");
  385. MFI->RemoveStackObject(NextColor);
  386. NextColor = AllColors.find_next(NextColor);
  387. }
  388. return true;
  389. }
  390. /// AllMemRefsCanBeUnfolded - Return true if all references of the specified
  391. /// spill slot index can be unfolded.
  392. bool StackSlotColoring::AllMemRefsCanBeUnfolded(int SS) {
  393. SmallVector<MachineInstr*, 8> &RefMIs = SSRefs[SS];
  394. for (unsigned i = 0, e = RefMIs.size(); i != e; ++i) {
  395. MachineInstr *MI = RefMIs[i];
  396. if (TII->isLoadFromStackSlot(MI, SS) ||
  397. TII->isStoreToStackSlot(MI, SS))
  398. // Restore and spill will become copies.
  399. return true;
  400. if (!TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(), false, false))
  401. return false;
  402. for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
  403. MachineOperand &MO = MI->getOperand(j);
  404. if (MO.isFI() && MO.getIndex() != SS)
  405. // If it uses another frameindex, we can, currently* unfold it.
  406. return false;
  407. }
  408. }
  409. return true;
  410. }
  411. /// RewriteInstruction - Rewrite specified instruction by replacing references
  412. /// to old frame index with new one.
  413. void StackSlotColoring::RewriteInstruction(MachineInstr *MI, int OldFI,
  414. int NewFI, MachineFunction &MF) {
  415. // Update the operands.
  416. for (unsigned i = 0, ee = MI->getNumOperands(); i != ee; ++i) {
  417. MachineOperand &MO = MI->getOperand(i);
  418. if (!MO.isFI())
  419. continue;
  420. int FI = MO.getIndex();
  421. if (FI != OldFI)
  422. continue;
  423. MO.setIndex(NewFI);
  424. }
  425. // Update the memory references. This changes the MachineMemOperands
  426. // directly. They may be in use by multiple instructions, however all
  427. // instructions using OldFI are being rewritten to use NewFI.
  428. const Value *OldSV = PseudoSourceValue::getFixedStack(OldFI);
  429. const Value *NewSV = PseudoSourceValue::getFixedStack(NewFI);
  430. for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
  431. E = MI->memoperands_end(); I != E; ++I)
  432. if ((*I)->getValue() == OldSV)
  433. (*I)->setValue(NewSV);
  434. }
  435. /// PropagateBackward - Traverse backward and look for the definition of
  436. /// OldReg. If it can successfully update all of the references with NewReg,
  437. /// do so and return true.
  438. bool StackSlotColoring::PropagateBackward(MachineBasicBlock::iterator MII,
  439. MachineBasicBlock *MBB,
  440. unsigned OldReg, unsigned NewReg) {
  441. if (MII == MBB->begin())
  442. return false;
  443. SmallVector<MachineOperand*, 4> Uses;
  444. SmallVector<MachineOperand*, 4> Refs;
  445. while (--MII != MBB->begin()) {
  446. bool FoundDef = false; // Not counting 2address def.
  447. Uses.clear();
  448. const TargetInstrDesc &TID = MII->getDesc();
  449. for (unsigned i = 0, e = MII->getNumOperands(); i != e; ++i) {
  450. MachineOperand &MO = MII->getOperand(i);
  451. if (!MO.isReg())
  452. continue;
  453. unsigned Reg = MO.getReg();
  454. if (Reg == 0)
  455. continue;
  456. if (Reg == OldReg) {
  457. if (MO.isImplicit())
  458. return false;
  459. // Abort the use is actually a sub-register def. We don't have enough
  460. // information to figure out if it is really legal.
  461. if (MO.getSubReg() || MII->isSubregToReg())
  462. return false;
  463. const TargetRegisterClass *RC = TID.OpInfo[i].getRegClass(TRI);
  464. if (RC && !RC->contains(NewReg))
  465. return false;
  466. if (MO.isUse()) {
  467. Uses.push_back(&MO);
  468. } else {
  469. Refs.push_back(&MO);
  470. if (!MII->isRegTiedToUseOperand(i))
  471. FoundDef = true;
  472. }
  473. } else if (TRI->regsOverlap(Reg, NewReg)) {
  474. return false;
  475. } else if (TRI->regsOverlap(Reg, OldReg)) {
  476. if (!MO.isUse() || !MO.isKill())
  477. return false;
  478. }
  479. }
  480. if (FoundDef) {
  481. // Found non-two-address def. Stop here.
  482. for (unsigned i = 0, e = Refs.size(); i != e; ++i)
  483. Refs[i]->setReg(NewReg);
  484. return true;
  485. }
  486. // Two-address uses must be updated as well.
  487. for (unsigned i = 0, e = Uses.size(); i != e; ++i)
  488. Refs.push_back(Uses[i]);
  489. }
  490. return false;
  491. }
  492. /// PropagateForward - Traverse forward and look for the kill of OldReg. If
  493. /// it can successfully update all of the uses with NewReg, do so and
  494. /// return true.
  495. bool StackSlotColoring::PropagateForward(MachineBasicBlock::iterator MII,
  496. MachineBasicBlock *MBB,
  497. unsigned OldReg, unsigned NewReg) {
  498. if (MII == MBB->end())
  499. return false;
  500. SmallVector<MachineOperand*, 4> Uses;
  501. while (++MII != MBB->end()) {
  502. bool FoundKill = false;
  503. const TargetInstrDesc &TID = MII->getDesc();
  504. for (unsigned i = 0, e = MII->getNumOperands(); i != e; ++i) {
  505. MachineOperand &MO = MII->getOperand(i);
  506. if (!MO.isReg())
  507. continue;
  508. unsigned Reg = MO.getReg();
  509. if (Reg == 0)
  510. continue;
  511. if (Reg == OldReg) {
  512. if (MO.isDef() || MO.isImplicit())
  513. return false;
  514. // Abort the use is actually a sub-register use. We don't have enough
  515. // information to figure out if it is really legal.
  516. if (MO.getSubReg())
  517. return false;
  518. const TargetRegisterClass *RC = TID.OpInfo[i].getRegClass(TRI);
  519. if (RC && !RC->contains(NewReg))
  520. return false;
  521. if (MO.isKill())
  522. FoundKill = true;
  523. Uses.push_back(&MO);
  524. } else if (TRI->regsOverlap(Reg, NewReg) ||
  525. TRI->regsOverlap(Reg, OldReg))
  526. return false;
  527. }
  528. if (FoundKill) {
  529. for (unsigned i = 0, e = Uses.size(); i != e; ++i)
  530. Uses[i]->setReg(NewReg);
  531. return true;
  532. }
  533. }
  534. return false;
  535. }
  536. /// UnfoldAndRewriteInstruction - Rewrite specified instruction by unfolding
  537. /// folded memory references and replacing those references with register
  538. /// references instead.
  539. void
  540. StackSlotColoring::UnfoldAndRewriteInstruction(MachineInstr *MI, int OldFI,
  541. unsigned Reg,
  542. const TargetRegisterClass *RC,
  543. SmallSet<unsigned, 4> &Defs,
  544. MachineFunction &MF) {
  545. MachineBasicBlock *MBB = MI->getParent();
  546. if (unsigned DstReg = TII->isLoadFromStackSlot(MI, OldFI)) {
  547. if (PropagateForward(MI, MBB, DstReg, Reg)) {
  548. DEBUG(dbgs() << "Eliminated load: ");
  549. DEBUG(MI->dump());
  550. ++NumLoadElim;
  551. } else {
  552. BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(TargetOpcode::COPY),
  553. DstReg).addReg(Reg);
  554. ++NumRegRepl;
  555. }
  556. if (!Defs.count(Reg)) {
  557. // If this is the first use of Reg in this MBB and it wasn't previously
  558. // defined in MBB, add it to livein.
  559. MBB->addLiveIn(Reg);
  560. Defs.insert(Reg);
  561. }
  562. } else if (unsigned SrcReg = TII->isStoreToStackSlot(MI, OldFI)) {
  563. if (MI->killsRegister(SrcReg) && PropagateBackward(MI, MBB, SrcReg, Reg)) {
  564. DEBUG(dbgs() << "Eliminated store: ");
  565. DEBUG(MI->dump());
  566. ++NumStoreElim;
  567. } else {
  568. BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(TargetOpcode::COPY), Reg)
  569. .addReg(SrcReg);
  570. ++NumRegRepl;
  571. }
  572. // Remember reg has been defined in MBB.
  573. Defs.insert(Reg);
  574. } else {
  575. SmallVector<MachineInstr*, 4> NewMIs;
  576. bool Success = TII->unfoldMemoryOperand(MF, MI, Reg, false, false, NewMIs);
  577. Success = Success; // Silence compiler warning.
  578. assert(Success && "Failed to unfold!");
  579. MachineInstr *NewMI = NewMIs[0];
  580. MBB->insert(MI, NewMI);
  581. ++NumRegRepl;
  582. if (NewMI->readsRegister(Reg)) {
  583. if (!Defs.count(Reg))
  584. // If this is the first use of Reg in this MBB and it wasn't previously
  585. // defined in MBB, add it to livein.
  586. MBB->addLiveIn(Reg);
  587. Defs.insert(Reg);
  588. }
  589. }
  590. MBB->erase(MI);
  591. }
  592. /// RemoveDeadStores - Scan through a basic block and look for loads followed
  593. /// by stores. If they're both using the same stack slot, then the store is
  594. /// definitely dead. This could obviously be much more aggressive (consider
  595. /// pairs with instructions between them), but such extensions might have a
  596. /// considerable compile time impact.
  597. bool StackSlotColoring::RemoveDeadStores(MachineBasicBlock* MBB) {
  598. // FIXME: This could be much more aggressive, but we need to investigate
  599. // the compile time impact of doing so.
  600. bool changed = false;
  601. SmallVector<MachineInstr*, 4> toErase;
  602. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
  603. I != E; ++I) {
  604. if (DCELimit != -1 && (int)NumDead >= DCELimit)
  605. break;
  606. MachineBasicBlock::iterator NextMI = llvm::next(I);
  607. if (NextMI == MBB->end()) continue;
  608. int FirstSS, SecondSS;
  609. unsigned LoadReg = 0;
  610. unsigned StoreReg = 0;
  611. if (!(LoadReg = TII->isLoadFromStackSlot(I, FirstSS))) continue;
  612. if (!(StoreReg = TII->isStoreToStackSlot(NextMI, SecondSS))) continue;
  613. if (FirstSS != SecondSS || LoadReg != StoreReg || FirstSS == -1) continue;
  614. ++NumDead;
  615. changed = true;
  616. if (NextMI->findRegisterUseOperandIdx(LoadReg, true, 0) != -1) {
  617. ++NumDead;
  618. toErase.push_back(I);
  619. }
  620. toErase.push_back(NextMI);
  621. ++I;
  622. }
  623. for (SmallVector<MachineInstr*, 4>::iterator I = toErase.begin(),
  624. E = toErase.end(); I != E; ++I)
  625. (*I)->eraseFromParent();
  626. return changed;
  627. }
  628. bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
  629. DEBUG({
  630. dbgs() << "********** Stack Slot Coloring **********\n"
  631. << "********** Function: "
  632. << MF.getFunction()->getName() << '\n';
  633. });
  634. MFI = MF.getFrameInfo();
  635. MRI = &MF.getRegInfo();
  636. TII = MF.getTarget().getInstrInfo();
  637. TRI = MF.getTarget().getRegisterInfo();
  638. LS = &getAnalysis<LiveStacks>();
  639. VRM = &getAnalysis<VirtRegMap>();
  640. loopInfo = &getAnalysis<MachineLoopInfo>();
  641. bool Changed = false;
  642. unsigned NumSlots = LS->getNumIntervals();
  643. if (NumSlots < 2) {
  644. if (NumSlots == 0 || !VRM->HasUnusedRegisters())
  645. // Nothing to do!
  646. return false;
  647. }
  648. // If there are calls to setjmp or sigsetjmp, don't perform stack slot
  649. // coloring. The stack could be modified before the longjmp is executed,
  650. // resulting in the wrong value being used afterwards. (See
  651. // <rdar://problem/8007500>.)
  652. if (MF.callsSetJmp())
  653. return false;
  654. // Gather spill slot references
  655. ScanForSpillSlotRefs(MF);
  656. InitializeSlots();
  657. Changed = ColorSlots(MF);
  658. NextColor = -1;
  659. SSIntervals.clear();
  660. for (unsigned i = 0, e = SSRefs.size(); i != e; ++i)
  661. SSRefs[i].clear();
  662. SSRefs.clear();
  663. OrigAlignments.clear();
  664. OrigSizes.clear();
  665. AllColors.clear();
  666. UsedColors.clear();
  667. for (unsigned i = 0, e = Assignments.size(); i != e; ++i)
  668. Assignments[i].clear();
  669. Assignments.clear();
  670. if (Changed) {
  671. for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
  672. Changed |= RemoveDeadStores(I);
  673. }
  674. return Changed;
  675. }