MachineSink.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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/ADT/SmallSet.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/Analysis/AliasAnalysis.h"
  23. #include "llvm/CodeGen/MachineDominators.h"
  24. #include "llvm/CodeGen/MachineLoopInfo.h"
  25. #include "llvm/CodeGen/MachineRegisterInfo.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include "llvm/Target/TargetInstrInfo.h"
  30. #include "llvm/Target/TargetMachine.h"
  31. #include "llvm/Target/TargetRegisterInfo.h"
  32. using namespace llvm;
  33. static cl::opt<bool>
  34. SplitEdges("machine-sink-split",
  35. cl::desc("Split critical edges during machine sinking"),
  36. cl::init(true), cl::Hidden);
  37. STATISTIC(NumSunk, "Number of machine instructions sunk");
  38. STATISTIC(NumSplit, "Number of critical edges split");
  39. STATISTIC(NumCoalesces, "Number of copies coalesced");
  40. namespace {
  41. class MachineSinking : public MachineFunctionPass {
  42. const TargetInstrInfo *TII;
  43. const TargetRegisterInfo *TRI;
  44. MachineRegisterInfo *MRI; // Machine register information
  45. MachineDominatorTree *DT; // Machine dominator tree
  46. MachineLoopInfo *LI;
  47. AliasAnalysis *AA;
  48. // Remember which edges have been considered for breaking.
  49. SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8>
  50. CEBCandidates;
  51. public:
  52. static char ID; // Pass identification
  53. MachineSinking() : MachineFunctionPass(ID) {
  54. initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
  55. }
  56. virtual bool runOnMachineFunction(MachineFunction &MF);
  57. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  58. AU.setPreservesCFG();
  59. MachineFunctionPass::getAnalysisUsage(AU);
  60. AU.addRequired<AliasAnalysis>();
  61. AU.addRequired<MachineDominatorTree>();
  62. AU.addRequired<MachineLoopInfo>();
  63. AU.addPreserved<MachineDominatorTree>();
  64. AU.addPreserved<MachineLoopInfo>();
  65. }
  66. virtual void releaseMemory() {
  67. CEBCandidates.clear();
  68. }
  69. private:
  70. bool ProcessBlock(MachineBasicBlock &MBB);
  71. bool isWorthBreakingCriticalEdge(MachineInstr *MI,
  72. MachineBasicBlock *From,
  73. MachineBasicBlock *To);
  74. MachineBasicBlock *SplitCriticalEdge(MachineInstr *MI,
  75. MachineBasicBlock *From,
  76. MachineBasicBlock *To,
  77. bool BreakPHIEdge);
  78. bool SinkInstruction(MachineInstr *MI, bool &SawStore);
  79. bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
  80. MachineBasicBlock *DefMBB,
  81. bool &BreakPHIEdge, bool &LocalUse) const;
  82. MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, MachineBasicBlock *MBB,
  83. bool &BreakPHIEdge);
  84. bool isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
  85. MachineBasicBlock *MBB,
  86. MachineBasicBlock *SuccToSinkTo);
  87. bool PerformTrivialForwardCoalescing(MachineInstr *MI,
  88. MachineBasicBlock *MBB);
  89. };
  90. // SuccessorSorter - Sort Successors according to their loop depth.
  91. struct SuccessorSorter {
  92. SuccessorSorter(MachineLoopInfo *LoopInfo) : LI(LoopInfo) {}
  93. bool operator()(const MachineBasicBlock *LHS,
  94. const MachineBasicBlock *RHS) const {
  95. return LI->getLoopDepth(LHS) < LI->getLoopDepth(RHS);
  96. }
  97. MachineLoopInfo *LI;
  98. };
  99. } // end anonymous namespace
  100. char MachineSinking::ID = 0;
  101. char &llvm::MachineSinkingID = MachineSinking::ID;
  102. INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
  103. "Machine code sinking", false, false)
  104. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  105. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  106. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  107. INITIALIZE_PASS_END(MachineSinking, "machine-sink",
  108. "Machine code sinking", false, false)
  109. bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
  110. MachineBasicBlock *MBB) {
  111. if (!MI->isCopy())
  112. return false;
  113. unsigned SrcReg = MI->getOperand(1).getReg();
  114. unsigned DstReg = MI->getOperand(0).getReg();
  115. if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
  116. !TargetRegisterInfo::isVirtualRegister(DstReg) ||
  117. !MRI->hasOneNonDBGUse(SrcReg))
  118. return false;
  119. const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
  120. const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
  121. if (SRC != DRC)
  122. return false;
  123. MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
  124. if (DefMI->isCopyLike())
  125. return false;
  126. DEBUG(dbgs() << "Coalescing: " << *DefMI);
  127. DEBUG(dbgs() << "*** to: " << *MI);
  128. MRI->replaceRegWith(DstReg, SrcReg);
  129. MI->eraseFromParent();
  130. ++NumCoalesces;
  131. return true;
  132. }
  133. /// AllUsesDominatedByBlock - Return true if all uses of the specified register
  134. /// occur in blocks dominated by the specified block. If any use is in the
  135. /// definition block, then return false since it is never legal to move def
  136. /// after uses.
  137. bool
  138. MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
  139. MachineBasicBlock *MBB,
  140. MachineBasicBlock *DefMBB,
  141. bool &BreakPHIEdge,
  142. bool &LocalUse) const {
  143. assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
  144. "Only makes sense for vregs");
  145. // Ignore debug uses because debug info doesn't affect the code.
  146. if (MRI->use_nodbg_empty(Reg))
  147. return true;
  148. // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
  149. // into and they are all PHI nodes. In this case, machine-sink must break
  150. // the critical edge first. e.g.
  151. //
  152. // BB#1: derived from LLVM BB %bb4.preheader
  153. // Predecessors according to CFG: BB#0
  154. // ...
  155. // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
  156. // ...
  157. // JE_4 <BB#37>, %EFLAGS<imp-use>
  158. // Successors according to CFG: BB#37 BB#2
  159. //
  160. // BB#2: derived from LLVM BB %bb.nph
  161. // Predecessors according to CFG: BB#0 BB#1
  162. // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
  163. BreakPHIEdge = true;
  164. for (MachineRegisterInfo::use_nodbg_iterator
  165. I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
  166. I != E; ++I) {
  167. MachineInstr *UseInst = &*I;
  168. MachineBasicBlock *UseBlock = UseInst->getParent();
  169. if (!(UseBlock == MBB && UseInst->isPHI() &&
  170. UseInst->getOperand(I.getOperandNo()+1).getMBB() == DefMBB)) {
  171. BreakPHIEdge = false;
  172. break;
  173. }
  174. }
  175. if (BreakPHIEdge)
  176. return true;
  177. for (MachineRegisterInfo::use_nodbg_iterator
  178. I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
  179. I != E; ++I) {
  180. // Determine the block of the use.
  181. MachineInstr *UseInst = &*I;
  182. MachineBasicBlock *UseBlock = UseInst->getParent();
  183. if (UseInst->isPHI()) {
  184. // PHI nodes use the operand in the predecessor block, not the block with
  185. // the PHI.
  186. UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
  187. } else if (UseBlock == DefMBB) {
  188. LocalUse = true;
  189. return false;
  190. }
  191. // Check that it dominates.
  192. if (!DT->dominates(MBB, UseBlock))
  193. return false;
  194. }
  195. return true;
  196. }
  197. bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
  198. DEBUG(dbgs() << "******** Machine Sinking ********\n");
  199. const TargetMachine &TM = MF.getTarget();
  200. TII = TM.getInstrInfo();
  201. TRI = TM.getRegisterInfo();
  202. MRI = &MF.getRegInfo();
  203. DT = &getAnalysis<MachineDominatorTree>();
  204. LI = &getAnalysis<MachineLoopInfo>();
  205. AA = &getAnalysis<AliasAnalysis>();
  206. bool EverMadeChange = false;
  207. while (1) {
  208. bool MadeChange = false;
  209. // Process all basic blocks.
  210. CEBCandidates.clear();
  211. for (MachineFunction::iterator I = MF.begin(), E = MF.end();
  212. I != E; ++I)
  213. MadeChange |= ProcessBlock(*I);
  214. // If this iteration over the code changed anything, keep iterating.
  215. if (!MadeChange) break;
  216. EverMadeChange = true;
  217. }
  218. return EverMadeChange;
  219. }
  220. bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
  221. // Can't sink anything out of a block that has less than two successors.
  222. if (MBB.succ_size() <= 1 || MBB.empty()) return false;
  223. // Don't bother sinking code out of unreachable blocks. In addition to being
  224. // unprofitable, it can also lead to infinite looping, because in an
  225. // unreachable loop there may be nowhere to stop.
  226. if (!DT->isReachableFromEntry(&MBB)) return false;
  227. bool MadeChange = false;
  228. // Walk the basic block bottom-up. Remember if we saw a store.
  229. MachineBasicBlock::iterator I = MBB.end();
  230. --I;
  231. bool ProcessedBegin, SawStore = false;
  232. do {
  233. MachineInstr *MI = I; // The instruction to sink.
  234. // Predecrement I (if it's not begin) so that it isn't invalidated by
  235. // sinking.
  236. ProcessedBegin = I == MBB.begin();
  237. if (!ProcessedBegin)
  238. --I;
  239. if (MI->isDebugValue())
  240. continue;
  241. bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
  242. if (Joined) {
  243. MadeChange = true;
  244. continue;
  245. }
  246. if (SinkInstruction(MI, SawStore))
  247. ++NumSunk, MadeChange = true;
  248. // If we just processed the first instruction in the block, we're done.
  249. } while (!ProcessedBegin);
  250. return MadeChange;
  251. }
  252. bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
  253. MachineBasicBlock *From,
  254. MachineBasicBlock *To) {
  255. // FIXME: Need much better heuristics.
  256. // If the pass has already considered breaking this edge (during this pass
  257. // through the function), then let's go ahead and break it. This means
  258. // sinking multiple "cheap" instructions into the same block.
  259. if (!CEBCandidates.insert(std::make_pair(From, To)))
  260. return true;
  261. if (!MI->isCopy() && !MI->isAsCheapAsAMove())
  262. return true;
  263. // MI is cheap, we probably don't want to break the critical edge for it.
  264. // However, if this would allow some definitions of its source operands
  265. // to be sunk then it's probably worth it.
  266. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  267. const MachineOperand &MO = MI->getOperand(i);
  268. if (!MO.isReg()) continue;
  269. unsigned Reg = MO.getReg();
  270. if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg))
  271. continue;
  272. if (MRI->hasOneNonDBGUse(Reg))
  273. return true;
  274. }
  275. return false;
  276. }
  277. MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI,
  278. MachineBasicBlock *FromBB,
  279. MachineBasicBlock *ToBB,
  280. bool BreakPHIEdge) {
  281. if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
  282. return 0;
  283. // Avoid breaking back edge. From == To means backedge for single BB loop.
  284. if (!SplitEdges || FromBB == ToBB)
  285. return 0;
  286. // Check for backedges of more "complex" loops.
  287. if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
  288. LI->isLoopHeader(ToBB))
  289. return 0;
  290. // It's not always legal to break critical edges and sink the computation
  291. // to the edge.
  292. //
  293. // BB#1:
  294. // v1024
  295. // Beq BB#3
  296. // <fallthrough>
  297. // BB#2:
  298. // ... no uses of v1024
  299. // <fallthrough>
  300. // BB#3:
  301. // ...
  302. // = v1024
  303. //
  304. // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
  305. //
  306. // BB#1:
  307. // ...
  308. // Bne BB#2
  309. // BB#4:
  310. // v1024 =
  311. // B BB#3
  312. // BB#2:
  313. // ... no uses of v1024
  314. // <fallthrough>
  315. // BB#3:
  316. // ...
  317. // = v1024
  318. //
  319. // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
  320. // flow. We need to ensure the new basic block where the computation is
  321. // sunk to dominates all the uses.
  322. // It's only legal to break critical edge and sink the computation to the
  323. // new block if all the predecessors of "To", except for "From", are
  324. // not dominated by "From". Given SSA property, this means these
  325. // predecessors are dominated by "To".
  326. //
  327. // There is no need to do this check if all the uses are PHI nodes. PHI
  328. // sources are only defined on the specific predecessor edges.
  329. if (!BreakPHIEdge) {
  330. for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
  331. E = ToBB->pred_end(); PI != E; ++PI) {
  332. if (*PI == FromBB)
  333. continue;
  334. if (!DT->dominates(ToBB, *PI))
  335. return 0;
  336. }
  337. }
  338. return FromBB->SplitCriticalEdge(ToBB, this);
  339. }
  340. static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) {
  341. return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence();
  342. }
  343. /// collectDebgValues - Scan instructions following MI and collect any
  344. /// matching DBG_VALUEs.
  345. static void collectDebugValues(MachineInstr *MI,
  346. SmallVectorImpl<MachineInstr *> &DbgValues) {
  347. DbgValues.clear();
  348. if (!MI->getOperand(0).isReg())
  349. return;
  350. MachineBasicBlock::iterator DI = MI; ++DI;
  351. for (MachineBasicBlock::iterator DE = MI->getParent()->end();
  352. DI != DE; ++DI) {
  353. if (!DI->isDebugValue())
  354. return;
  355. if (DI->getOperand(0).isReg() &&
  356. DI->getOperand(0).getReg() == MI->getOperand(0).getReg())
  357. DbgValues.push_back(DI);
  358. }
  359. }
  360. /// isPostDominatedBy - Return true if A is post dominated by B.
  361. static bool isPostDominatedBy(MachineBasicBlock *A, MachineBasicBlock *B) {
  362. // FIXME - Use real post dominator.
  363. if (A->succ_size() != 2)
  364. return false;
  365. MachineBasicBlock::succ_iterator I = A->succ_begin();
  366. if (B == *I)
  367. ++I;
  368. MachineBasicBlock *OtherSuccBlock = *I;
  369. if (OtherSuccBlock->succ_size() != 1 ||
  370. *(OtherSuccBlock->succ_begin()) != B)
  371. return false;
  372. return true;
  373. }
  374. /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
  375. bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
  376. MachineBasicBlock *MBB,
  377. MachineBasicBlock *SuccToSinkTo) {
  378. assert (MI && "Invalid MachineInstr!");
  379. assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
  380. if (MBB == SuccToSinkTo)
  381. return false;
  382. // It is profitable if SuccToSinkTo does not post dominate current block.
  383. if (!isPostDominatedBy(MBB, SuccToSinkTo))
  384. return true;
  385. // Check if only use in post dominated block is PHI instruction.
  386. bool NonPHIUse = false;
  387. for (MachineRegisterInfo::use_nodbg_iterator
  388. I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
  389. I != E; ++I) {
  390. MachineInstr *UseInst = &*I;
  391. MachineBasicBlock *UseBlock = UseInst->getParent();
  392. if (UseBlock == SuccToSinkTo && !UseInst->isPHI())
  393. NonPHIUse = true;
  394. }
  395. if (!NonPHIUse)
  396. return true;
  397. // If SuccToSinkTo post dominates then also it may be profitable if MI
  398. // can further profitably sinked into another block in next round.
  399. bool BreakPHIEdge = false;
  400. // FIXME - If finding successor is compile time expensive then catch results.
  401. if (MachineBasicBlock *MBB2 = FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge))
  402. return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2);
  403. // If SuccToSinkTo is final destination and it is a post dominator of current
  404. // block then it is not profitable to sink MI into SuccToSinkTo block.
  405. return false;
  406. }
  407. /// FindSuccToSinkTo - Find a successor to sink this instruction to.
  408. MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI,
  409. MachineBasicBlock *MBB,
  410. bool &BreakPHIEdge) {
  411. assert (MI && "Invalid MachineInstr!");
  412. assert (MBB && "Invalid MachineBasicBlock!");
  413. // Loop over all the operands of the specified instruction. If there is
  414. // anything we can't handle, bail out.
  415. // SuccToSinkTo - This is the successor to sink this instruction to, once we
  416. // decide.
  417. MachineBasicBlock *SuccToSinkTo = 0;
  418. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  419. const MachineOperand &MO = MI->getOperand(i);
  420. if (!MO.isReg()) continue; // Ignore non-register operands.
  421. unsigned Reg = MO.getReg();
  422. if (Reg == 0) continue;
  423. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  424. if (MO.isUse()) {
  425. // If the physreg has no defs anywhere, it's just an ambient register
  426. // and we can freely move its uses. Alternatively, if it's allocatable,
  427. // it could get allocated to something with a def during allocation.
  428. if (!MRI->isConstantPhysReg(Reg, *MBB->getParent()))
  429. return NULL;
  430. } else if (!MO.isDead()) {
  431. // A def that isn't dead. We can't move it.
  432. return NULL;
  433. }
  434. } else {
  435. // Virtual register uses are always safe to sink.
  436. if (MO.isUse()) continue;
  437. // If it's not safe to move defs of the register class, then abort.
  438. if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
  439. return NULL;
  440. // FIXME: This picks a successor to sink into based on having one
  441. // successor that dominates all the uses. However, there are cases where
  442. // sinking can happen but where the sink point isn't a successor. For
  443. // example:
  444. //
  445. // x = computation
  446. // if () {} else {}
  447. // use x
  448. //
  449. // the instruction could be sunk over the whole diamond for the
  450. // if/then/else (or loop, etc), allowing it to be sunk into other blocks
  451. // after that.
  452. // Virtual register defs can only be sunk if all their uses are in blocks
  453. // dominated by one of the successors.
  454. if (SuccToSinkTo) {
  455. // If a previous operand picked a block to sink to, then this operand
  456. // must be sinkable to the same block.
  457. bool LocalUse = false;
  458. if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
  459. BreakPHIEdge, LocalUse))
  460. return NULL;
  461. continue;
  462. }
  463. // Otherwise, we should look at all the successors and decide which one
  464. // we should sink to.
  465. // We give successors with smaller loop depth higher priority.
  466. SmallVector<MachineBasicBlock*, 4> Succs(MBB->succ_begin(), MBB->succ_end());
  467. std::stable_sort(Succs.begin(), Succs.end(), SuccessorSorter(LI));
  468. for (SmallVectorImpl<MachineBasicBlock *>::iterator SI = Succs.begin(),
  469. E = Succs.end(); SI != E; ++SI) {
  470. MachineBasicBlock *SuccBlock = *SI;
  471. bool LocalUse = false;
  472. if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
  473. BreakPHIEdge, LocalUse)) {
  474. SuccToSinkTo = SuccBlock;
  475. break;
  476. }
  477. if (LocalUse)
  478. // Def is used locally, it's never safe to move this def.
  479. return NULL;
  480. }
  481. // If we couldn't find a block to sink to, ignore this instruction.
  482. if (SuccToSinkTo == 0)
  483. return NULL;
  484. else if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo))
  485. return NULL;
  486. }
  487. }
  488. // It is not possible to sink an instruction into its own block. This can
  489. // happen with loops.
  490. if (MBB == SuccToSinkTo)
  491. return NULL;
  492. // It's not safe to sink instructions to EH landing pad. Control flow into
  493. // landing pad is implicitly defined.
  494. if (SuccToSinkTo && SuccToSinkTo->isLandingPad())
  495. return NULL;
  496. return SuccToSinkTo;
  497. }
  498. /// SinkInstruction - Determine whether it is safe to sink the specified machine
  499. /// instruction out of its current block into a successor.
  500. bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
  501. // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to
  502. // be close to the source to make it easier to coalesce.
  503. if (AvoidsSinking(MI, MRI))
  504. return false;
  505. // Check if it's safe to move the instruction.
  506. if (!MI->isSafeToMove(TII, AA, SawStore))
  507. return false;
  508. // FIXME: This should include support for sinking instructions within the
  509. // block they are currently in to shorten the live ranges. We often get
  510. // instructions sunk into the top of a large block, but it would be better to
  511. // also sink them down before their first use in the block. This xform has to
  512. // be careful not to *increase* register pressure though, e.g. sinking
  513. // "x = y + z" down if it kills y and z would increase the live ranges of y
  514. // and z and only shrink the live range of x.
  515. bool BreakPHIEdge = false;
  516. MachineBasicBlock *ParentBlock = MI->getParent();
  517. MachineBasicBlock *SuccToSinkTo = FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge);
  518. // If there are no outputs, it must have side-effects.
  519. if (SuccToSinkTo == 0)
  520. return false;
  521. // If the instruction to move defines a dead physical register which is live
  522. // when leaving the basic block, don't move it because it could turn into a
  523. // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
  524. for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
  525. const MachineOperand &MO = MI->getOperand(I);
  526. if (!MO.isReg()) continue;
  527. unsigned Reg = MO.getReg();
  528. if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  529. if (SuccToSinkTo->isLiveIn(Reg))
  530. return false;
  531. }
  532. DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
  533. // If the block has multiple predecessors, this would introduce computation on
  534. // a path that it doesn't already exist. We could split the critical edge,
  535. // but for now we just punt.
  536. if (SuccToSinkTo->pred_size() > 1) {
  537. // We cannot sink a load across a critical edge - there may be stores in
  538. // other code paths.
  539. bool TryBreak = false;
  540. bool store = true;
  541. if (!MI->isSafeToMove(TII, AA, store)) {
  542. DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
  543. TryBreak = true;
  544. }
  545. // We don't want to sink across a critical edge if we don't dominate the
  546. // successor. We could be introducing calculations to new code paths.
  547. if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
  548. DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
  549. TryBreak = true;
  550. }
  551. // Don't sink instructions into a loop.
  552. if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
  553. DEBUG(dbgs() << " *** NOTE: Loop header found\n");
  554. TryBreak = true;
  555. }
  556. // Otherwise we are OK with sinking along a critical edge.
  557. if (!TryBreak)
  558. DEBUG(dbgs() << "Sinking along critical edge.\n");
  559. else {
  560. MachineBasicBlock *NewSucc =
  561. SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
  562. if (!NewSucc) {
  563. DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
  564. "break critical edge\n");
  565. return false;
  566. } else {
  567. DEBUG(dbgs() << " *** Splitting critical edge:"
  568. " BB#" << ParentBlock->getNumber()
  569. << " -- BB#" << NewSucc->getNumber()
  570. << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
  571. SuccToSinkTo = NewSucc;
  572. ++NumSplit;
  573. BreakPHIEdge = false;
  574. }
  575. }
  576. }
  577. if (BreakPHIEdge) {
  578. // BreakPHIEdge is true if all the uses are in the successor MBB being
  579. // sunken into and they are all PHI nodes. In this case, machine-sink must
  580. // break the critical edge first.
  581. MachineBasicBlock *NewSucc = SplitCriticalEdge(MI, ParentBlock,
  582. SuccToSinkTo, BreakPHIEdge);
  583. if (!NewSucc) {
  584. DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
  585. "break critical edge\n");
  586. return false;
  587. }
  588. DEBUG(dbgs() << " *** Splitting critical edge:"
  589. " BB#" << ParentBlock->getNumber()
  590. << " -- BB#" << NewSucc->getNumber()
  591. << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
  592. SuccToSinkTo = NewSucc;
  593. ++NumSplit;
  594. }
  595. // Determine where to insert into. Skip phi nodes.
  596. MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
  597. while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
  598. ++InsertPos;
  599. // collect matching debug values.
  600. SmallVector<MachineInstr *, 2> DbgValuesToSink;
  601. collectDebugValues(MI, DbgValuesToSink);
  602. // Move the instruction.
  603. SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
  604. ++MachineBasicBlock::iterator(MI));
  605. // Move debug values.
  606. for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
  607. DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
  608. MachineInstr *DbgMI = *DBI;
  609. SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI,
  610. ++MachineBasicBlock::iterator(DbgMI));
  611. }
  612. // Conservatively, clear any kill flags, since it's possible that they are no
  613. // longer correct.
  614. MI->clearKillInfo();
  615. return true;
  616. }