MachineSink.cpp 26 KB

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