MachineSink.cpp 25 KB

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