StackSlotColoring.cpp 25 KB

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