MachineSink.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. //===-- MachineSink.cpp - Sinking for machine instructions ----------------===//
  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 pass moves instructions into successor blocks, when possible, so that
  11. // they aren't executed on paths where their results aren't needed.
  12. //
  13. // This pass is not intended to be a replacement or a complete alternative
  14. // for an LLVM-IR-level sinking pass. It is only designed to sink simple
  15. // constructs that are not exposed before lowering and instruction selection.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #define DEBUG_TYPE "machine-sink"
  19. #include "llvm/CodeGen/Passes.h"
  20. #include "llvm/CodeGen/MachineRegisterInfo.h"
  21. #include "llvm/CodeGen/MachineDominators.h"
  22. #include "llvm/Analysis/AliasAnalysis.h"
  23. #include "llvm/Target/TargetRegisterInfo.h"
  24. #include "llvm/Target/TargetInstrInfo.h"
  25. #include "llvm/Target/TargetMachine.h"
  26. #include "llvm/ADT/Statistic.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. using namespace llvm;
  30. STATISTIC(NumSunk, "Number of machine instructions sunk");
  31. namespace {
  32. class MachineSinking : public MachineFunctionPass {
  33. const TargetInstrInfo *TII;
  34. const TargetRegisterInfo *TRI;
  35. MachineRegisterInfo *RegInfo; // Machine register information
  36. MachineDominatorTree *DT; // Machine dominator tree
  37. AliasAnalysis *AA;
  38. BitVector AllocatableSet; // Which physregs are allocatable?
  39. public:
  40. static char ID; // Pass identification
  41. MachineSinking() : MachineFunctionPass(&ID) {}
  42. virtual bool runOnMachineFunction(MachineFunction &MF);
  43. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  44. AU.setPreservesCFG();
  45. MachineFunctionPass::getAnalysisUsage(AU);
  46. AU.addRequired<AliasAnalysis>();
  47. AU.addRequired<MachineDominatorTree>();
  48. AU.addPreserved<MachineDominatorTree>();
  49. }
  50. private:
  51. bool ProcessBlock(MachineBasicBlock &MBB);
  52. bool SinkInstruction(MachineInstr *MI, bool &SawStore);
  53. bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB) const;
  54. };
  55. } // end anonymous namespace
  56. char MachineSinking::ID = 0;
  57. static RegisterPass<MachineSinking>
  58. X("machine-sink", "Machine code sinking");
  59. FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
  60. /// AllUsesDominatedByBlock - Return true if all uses of the specified register
  61. /// occur in blocks dominated by the specified block.
  62. bool MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
  63. MachineBasicBlock *MBB) const {
  64. assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
  65. "Only makes sense for vregs");
  66. for (MachineRegisterInfo::use_iterator I = RegInfo->use_begin(Reg),
  67. E = RegInfo->use_end(); I != E; ++I) {
  68. // Determine the block of the use.
  69. MachineInstr *UseInst = &*I;
  70. MachineBasicBlock *UseBlock = UseInst->getParent();
  71. if (UseInst->isPHI()) {
  72. // PHI nodes use the operand in the predecessor block, not the block with
  73. // the PHI.
  74. UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
  75. }
  76. // Check that it dominates.
  77. if (!DT->dominates(MBB, UseBlock))
  78. return false;
  79. }
  80. return true;
  81. }
  82. bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
  83. DEBUG(dbgs() << "******** Machine Sinking ********\n");
  84. const TargetMachine &TM = MF.getTarget();
  85. TII = TM.getInstrInfo();
  86. TRI = TM.getRegisterInfo();
  87. RegInfo = &MF.getRegInfo();
  88. DT = &getAnalysis<MachineDominatorTree>();
  89. AA = &getAnalysis<AliasAnalysis>();
  90. AllocatableSet = TRI->getAllocatableSet(MF);
  91. bool EverMadeChange = false;
  92. while (1) {
  93. bool MadeChange = false;
  94. // Process all basic blocks.
  95. for (MachineFunction::iterator I = MF.begin(), E = MF.end();
  96. I != E; ++I)
  97. MadeChange |= ProcessBlock(*I);
  98. // If this iteration over the code changed anything, keep iterating.
  99. if (!MadeChange) break;
  100. EverMadeChange = true;
  101. }
  102. return EverMadeChange;
  103. }
  104. bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
  105. // Can't sink anything out of a block that has less than two successors.
  106. if (MBB.succ_size() <= 1 || MBB.empty()) return false;
  107. bool MadeChange = false;
  108. // Walk the basic block bottom-up. Remember if we saw a store.
  109. MachineBasicBlock::iterator I = MBB.end();
  110. --I;
  111. bool ProcessedBegin, SawStore = false;
  112. do {
  113. MachineInstr *MI = I; // The instruction to sink.
  114. // Predecrement I (if it's not begin) so that it isn't invalidated by
  115. // sinking.
  116. ProcessedBegin = I == MBB.begin();
  117. if (!ProcessedBegin)
  118. --I;
  119. if (SinkInstruction(MI, SawStore))
  120. ++NumSunk, MadeChange = true;
  121. // If we just processed the first instruction in the block, we're done.
  122. } while (!ProcessedBegin);
  123. return MadeChange;
  124. }
  125. /// SinkInstruction - Determine whether it is safe to sink the specified machine
  126. /// instruction out of its current block into a successor.
  127. bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
  128. // Check if it's safe to move the instruction.
  129. if (!MI->isSafeToMove(TII, SawStore, AA))
  130. return false;
  131. // FIXME: This should include support for sinking instructions within the
  132. // block they are currently in to shorten the live ranges. We often get
  133. // instructions sunk into the top of a large block, but it would be better to
  134. // also sink them down before their first use in the block. This xform has to
  135. // be careful not to *increase* register pressure though, e.g. sinking
  136. // "x = y + z" down if it kills y and z would increase the live ranges of y
  137. // and z and only shrink the live range of x.
  138. // Loop over all the operands of the specified instruction. If there is
  139. // anything we can't handle, bail out.
  140. MachineBasicBlock *ParentBlock = MI->getParent();
  141. // SuccToSinkTo - This is the successor to sink this instruction to, once we
  142. // decide.
  143. MachineBasicBlock *SuccToSinkTo = 0;
  144. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  145. const MachineOperand &MO = MI->getOperand(i);
  146. if (!MO.isReg()) continue; // Ignore non-register operands.
  147. unsigned Reg = MO.getReg();
  148. if (Reg == 0) continue;
  149. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  150. if (MO.isUse()) {
  151. // If the physreg has no defs anywhere, it's just an ambient register
  152. // and we can freely move its uses. Alternatively, if it's allocatable,
  153. // it could get allocated to something with a def during allocation.
  154. if (!RegInfo->def_empty(Reg))
  155. return false;
  156. if (AllocatableSet.test(Reg))
  157. return false;
  158. // Check for a def among the register's aliases too.
  159. for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
  160. unsigned AliasReg = *Alias;
  161. if (!RegInfo->def_empty(AliasReg))
  162. return false;
  163. if (AllocatableSet.test(AliasReg))
  164. return false;
  165. }
  166. } else if (!MO.isDead()) {
  167. // A def that isn't dead. We can't move it.
  168. return false;
  169. }
  170. } else {
  171. // Virtual register uses are always safe to sink.
  172. if (MO.isUse()) continue;
  173. // If it's not safe to move defs of the register class, then abort.
  174. if (!TII->isSafeToMoveRegClassDefs(RegInfo->getRegClass(Reg)))
  175. return false;
  176. // FIXME: This picks a successor to sink into based on having one
  177. // successor that dominates all the uses. However, there are cases where
  178. // sinking can happen but where the sink point isn't a successor. For
  179. // example:
  180. // x = computation
  181. // if () {} else {}
  182. // use x
  183. // the instruction could be sunk over the whole diamond for the
  184. // if/then/else (or loop, etc), allowing it to be sunk into other blocks
  185. // after that.
  186. // Virtual register defs can only be sunk if all their uses are in blocks
  187. // dominated by one of the successors.
  188. if (SuccToSinkTo) {
  189. // If a previous operand picked a block to sink to, then this operand
  190. // must be sinkable to the same block.
  191. if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo))
  192. return false;
  193. continue;
  194. }
  195. // Otherwise, we should look at all the successors and decide which one
  196. // we should sink to.
  197. for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
  198. E = ParentBlock->succ_end(); SI != E; ++SI) {
  199. if (AllUsesDominatedByBlock(Reg, *SI)) {
  200. SuccToSinkTo = *SI;
  201. break;
  202. }
  203. }
  204. // If we couldn't find a block to sink to, ignore this instruction.
  205. if (SuccToSinkTo == 0)
  206. return false;
  207. }
  208. }
  209. // If there are no outputs, it must have side-effects.
  210. if (SuccToSinkTo == 0)
  211. return false;
  212. // It's not safe to sink instructions to EH landing pad. Control flow into
  213. // landing pad is implicitly defined.
  214. if (SuccToSinkTo->isLandingPad())
  215. return false;
  216. // It is not possible to sink an instruction into its own block. This can
  217. // happen with loops.
  218. if (MI->getParent() == SuccToSinkTo)
  219. return false;
  220. DEBUG(dbgs() << "Sink instr " << *MI);
  221. DEBUG(dbgs() << "to block " << *SuccToSinkTo);
  222. // If the block has multiple predecessors, this would introduce computation on
  223. // a path that it doesn't already exist. We could split the critical edge,
  224. // but for now we just punt.
  225. // FIXME: Split critical edges if not backedges.
  226. if (SuccToSinkTo->pred_size() > 1) {
  227. DEBUG(dbgs() << " *** PUNTING: Critical edge found\n");
  228. return false;
  229. }
  230. // Determine where to insert into. Skip phi nodes.
  231. MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
  232. while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
  233. ++InsertPos;
  234. // Move the instruction.
  235. SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
  236. ++MachineBasicBlock::iterator(MI));
  237. return true;
  238. }