MachineSink.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  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/SetVector.h"
  20. #include "llvm/ADT/SmallSet.h"
  21. #include "llvm/ADT/SparseBitVector.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/Analysis/AliasAnalysis.h"
  24. #include "llvm/CodeGen/MachineBasicBlock.h"
  25. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  26. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  27. #include "llvm/CodeGen/MachineDominators.h"
  28. #include "llvm/CodeGen/MachineFunction.h"
  29. #include "llvm/CodeGen/MachineFunctionPass.h"
  30. #include "llvm/CodeGen/MachineInstr.h"
  31. #include "llvm/CodeGen/MachineLoopInfo.h"
  32. #include "llvm/CodeGen/MachineOperand.h"
  33. #include "llvm/CodeGen/MachinePostDominators.h"
  34. #include "llvm/CodeGen/MachineRegisterInfo.h"
  35. #include "llvm/IR/LLVMContext.h"
  36. #include "llvm/Support/CommandLine.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. #include "llvm/Target/TargetInstrInfo.h"
  40. #include "llvm/Target/TargetRegisterInfo.h"
  41. #include "llvm/Target/TargetSubtargetInfo.h"
  42. #include <algorithm>
  43. #include <cassert>
  44. #include <cstdint>
  45. #include <map>
  46. #include <utility>
  47. #include <vector>
  48. using namespace llvm;
  49. #define DEBUG_TYPE "machine-sink"
  50. static cl::opt<bool>
  51. SplitEdges("machine-sink-split",
  52. cl::desc("Split critical edges during machine sinking"),
  53. cl::init(true), cl::Hidden);
  54. static cl::opt<bool>
  55. UseBlockFreqInfo("machine-sink-bfi",
  56. cl::desc("Use block frequency info to find successors to sink"),
  57. cl::init(true), cl::Hidden);
  58. static cl::opt<unsigned> SplitEdgeProbabilityThreshold(
  59. "machine-sink-split-probability-threshold",
  60. cl::desc(
  61. "Percentage threshold for splitting single-instruction critical edge. "
  62. "If the branch threshold is higher than this threshold, we allow "
  63. "speculative execution of up to 1 instruction to avoid branching to "
  64. "splitted critical edge"),
  65. cl::init(40), cl::Hidden);
  66. STATISTIC(NumSunk, "Number of machine instructions sunk");
  67. STATISTIC(NumSplit, "Number of critical edges split");
  68. STATISTIC(NumCoalesces, "Number of copies coalesced");
  69. namespace {
  70. class MachineSinking : public MachineFunctionPass {
  71. const TargetInstrInfo *TII;
  72. const TargetRegisterInfo *TRI;
  73. MachineRegisterInfo *MRI; // Machine register information
  74. MachineDominatorTree *DT; // Machine dominator tree
  75. MachinePostDominatorTree *PDT; // Machine post dominator tree
  76. MachineLoopInfo *LI;
  77. const MachineBlockFrequencyInfo *MBFI;
  78. const MachineBranchProbabilityInfo *MBPI;
  79. AliasAnalysis *AA;
  80. // Remember which edges have been considered for breaking.
  81. SmallSet<std::pair<MachineBasicBlock*, MachineBasicBlock*>, 8>
  82. CEBCandidates;
  83. // Remember which edges we are about to split.
  84. // This is different from CEBCandidates since those edges
  85. // will be split.
  86. SetVector<std::pair<MachineBasicBlock*, MachineBasicBlock*> > ToSplit;
  87. SparseBitVector<> RegsToClearKillFlags;
  88. typedef std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>
  89. AllSuccsCache;
  90. public:
  91. static char ID; // Pass identification
  92. MachineSinking() : MachineFunctionPass(ID) {
  93. initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
  94. }
  95. bool runOnMachineFunction(MachineFunction &MF) override;
  96. void getAnalysisUsage(AnalysisUsage &AU) const override {
  97. AU.setPreservesCFG();
  98. MachineFunctionPass::getAnalysisUsage(AU);
  99. AU.addRequired<AAResultsWrapperPass>();
  100. AU.addRequired<MachineDominatorTree>();
  101. AU.addRequired<MachinePostDominatorTree>();
  102. AU.addRequired<MachineLoopInfo>();
  103. AU.addRequired<MachineBranchProbabilityInfo>();
  104. AU.addPreserved<MachineDominatorTree>();
  105. AU.addPreserved<MachinePostDominatorTree>();
  106. AU.addPreserved<MachineLoopInfo>();
  107. if (UseBlockFreqInfo)
  108. AU.addRequired<MachineBlockFrequencyInfo>();
  109. }
  110. void releaseMemory() override {
  111. CEBCandidates.clear();
  112. }
  113. private:
  114. bool ProcessBlock(MachineBasicBlock &MBB);
  115. bool isWorthBreakingCriticalEdge(MachineInstr &MI,
  116. MachineBasicBlock *From,
  117. MachineBasicBlock *To);
  118. /// \brief Postpone the splitting of the given critical
  119. /// edge (\p From, \p To).
  120. ///
  121. /// We do not split the edges on the fly. Indeed, this invalidates
  122. /// the dominance information and thus triggers a lot of updates
  123. /// of that information underneath.
  124. /// Instead, we postpone all the splits after each iteration of
  125. /// the main loop. That way, the information is at least valid
  126. /// for the lifetime of an iteration.
  127. ///
  128. /// \return True if the edge is marked as toSplit, false otherwise.
  129. /// False can be returned if, for instance, this is not profitable.
  130. bool PostponeSplitCriticalEdge(MachineInstr &MI,
  131. MachineBasicBlock *From,
  132. MachineBasicBlock *To,
  133. bool BreakPHIEdge);
  134. bool SinkInstruction(MachineInstr &MI, bool &SawStore,
  135. AllSuccsCache &AllSuccessors);
  136. bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
  137. MachineBasicBlock *DefMBB,
  138. bool &BreakPHIEdge, bool &LocalUse) const;
  139. MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
  140. bool &BreakPHIEdge, AllSuccsCache &AllSuccessors);
  141. bool isProfitableToSinkTo(unsigned Reg, MachineInstr &MI,
  142. MachineBasicBlock *MBB,
  143. MachineBasicBlock *SuccToSinkTo,
  144. AllSuccsCache &AllSuccessors);
  145. bool PerformTrivialForwardCoalescing(MachineInstr &MI,
  146. MachineBasicBlock *MBB);
  147. SmallVector<MachineBasicBlock *, 4> &
  148. GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
  149. AllSuccsCache &AllSuccessors) const;
  150. };
  151. } // end anonymous namespace
  152. char MachineSinking::ID = 0;
  153. char &llvm::MachineSinkingID = MachineSinking::ID;
  154. INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
  155. "Machine code sinking", false, false)
  156. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  157. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  158. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  159. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  160. INITIALIZE_PASS_END(MachineSinking, "machine-sink",
  161. "Machine code sinking", false, false)
  162. bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI,
  163. MachineBasicBlock *MBB) {
  164. if (!MI.isCopy())
  165. return false;
  166. unsigned SrcReg = MI.getOperand(1).getReg();
  167. unsigned DstReg = MI.getOperand(0).getReg();
  168. if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
  169. !TargetRegisterInfo::isVirtualRegister(DstReg) ||
  170. !MRI->hasOneNonDBGUse(SrcReg))
  171. return false;
  172. const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
  173. const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
  174. if (SRC != DRC)
  175. return false;
  176. MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
  177. if (DefMI->isCopyLike())
  178. return false;
  179. DEBUG(dbgs() << "Coalescing: " << *DefMI);
  180. DEBUG(dbgs() << "*** to: " << MI);
  181. MRI->replaceRegWith(DstReg, SrcReg);
  182. MI.eraseFromParent();
  183. // Conservatively, clear any kill flags, since it's possible that they are no
  184. // longer correct.
  185. MRI->clearKillFlags(SrcReg);
  186. ++NumCoalesces;
  187. return true;
  188. }
  189. /// AllUsesDominatedByBlock - Return true if all uses of the specified register
  190. /// occur in blocks dominated by the specified block. If any use is in the
  191. /// definition block, then return false since it is never legal to move def
  192. /// after uses.
  193. bool
  194. MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
  195. MachineBasicBlock *MBB,
  196. MachineBasicBlock *DefMBB,
  197. bool &BreakPHIEdge,
  198. bool &LocalUse) const {
  199. assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
  200. "Only makes sense for vregs");
  201. // Ignore debug uses because debug info doesn't affect the code.
  202. if (MRI->use_nodbg_empty(Reg))
  203. return true;
  204. // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
  205. // into and they are all PHI nodes. In this case, machine-sink must break
  206. // the critical edge first. e.g.
  207. //
  208. // BB#1: derived from LLVM BB %bb4.preheader
  209. // Predecessors according to CFG: BB#0
  210. // ...
  211. // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
  212. // ...
  213. // JE_4 <BB#37>, %EFLAGS<imp-use>
  214. // Successors according to CFG: BB#37 BB#2
  215. //
  216. // BB#2: derived from LLVM BB %bb.nph
  217. // Predecessors according to CFG: BB#0 BB#1
  218. // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
  219. BreakPHIEdge = true;
  220. for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
  221. MachineInstr *UseInst = MO.getParent();
  222. unsigned OpNo = &MO - &UseInst->getOperand(0);
  223. MachineBasicBlock *UseBlock = UseInst->getParent();
  224. if (!(UseBlock == MBB && UseInst->isPHI() &&
  225. UseInst->getOperand(OpNo+1).getMBB() == DefMBB)) {
  226. BreakPHIEdge = false;
  227. break;
  228. }
  229. }
  230. if (BreakPHIEdge)
  231. return true;
  232. for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
  233. // Determine the block of the use.
  234. MachineInstr *UseInst = MO.getParent();
  235. unsigned OpNo = &MO - &UseInst->getOperand(0);
  236. MachineBasicBlock *UseBlock = UseInst->getParent();
  237. if (UseInst->isPHI()) {
  238. // PHI nodes use the operand in the predecessor block, not the block with
  239. // the PHI.
  240. UseBlock = UseInst->getOperand(OpNo+1).getMBB();
  241. } else if (UseBlock == DefMBB) {
  242. LocalUse = true;
  243. return false;
  244. }
  245. // Check that it dominates.
  246. if (!DT->dominates(MBB, UseBlock))
  247. return false;
  248. }
  249. return true;
  250. }
  251. bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
  252. if (skipFunction(*MF.getFunction()))
  253. return false;
  254. DEBUG(dbgs() << "******** Machine Sinking ********\n");
  255. TII = MF.getSubtarget().getInstrInfo();
  256. TRI = MF.getSubtarget().getRegisterInfo();
  257. MRI = &MF.getRegInfo();
  258. DT = &getAnalysis<MachineDominatorTree>();
  259. PDT = &getAnalysis<MachinePostDominatorTree>();
  260. LI = &getAnalysis<MachineLoopInfo>();
  261. MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr;
  262. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  263. AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  264. bool EverMadeChange = false;
  265. while (true) {
  266. bool MadeChange = false;
  267. // Process all basic blocks.
  268. CEBCandidates.clear();
  269. ToSplit.clear();
  270. for (auto &MBB: MF)
  271. MadeChange |= ProcessBlock(MBB);
  272. // If we have anything we marked as toSplit, split it now.
  273. for (auto &Pair : ToSplit) {
  274. auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this);
  275. if (NewSucc != nullptr) {
  276. DEBUG(dbgs() << " *** Splitting critical edge:"
  277. " BB#" << Pair.first->getNumber()
  278. << " -- BB#" << NewSucc->getNumber()
  279. << " -- BB#" << Pair.second->getNumber() << '\n');
  280. MadeChange = true;
  281. ++NumSplit;
  282. } else
  283. DEBUG(dbgs() << " *** Not legal to break critical edge\n");
  284. }
  285. // If this iteration over the code changed anything, keep iterating.
  286. if (!MadeChange) break;
  287. EverMadeChange = true;
  288. }
  289. // Now clear any kill flags for recorded registers.
  290. for (auto I : RegsToClearKillFlags)
  291. MRI->clearKillFlags(I);
  292. RegsToClearKillFlags.clear();
  293. return EverMadeChange;
  294. }
  295. bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
  296. // Can't sink anything out of a block that has less than two successors.
  297. if (MBB.succ_size() <= 1 || MBB.empty()) return false;
  298. // Don't bother sinking code out of unreachable blocks. In addition to being
  299. // unprofitable, it can also lead to infinite looping, because in an
  300. // unreachable loop there may be nowhere to stop.
  301. if (!DT->isReachableFromEntry(&MBB)) return false;
  302. bool MadeChange = false;
  303. // Cache all successors, sorted by frequency info and loop depth.
  304. AllSuccsCache AllSuccessors;
  305. // Walk the basic block bottom-up. Remember if we saw a store.
  306. MachineBasicBlock::iterator I = MBB.end();
  307. --I;
  308. bool ProcessedBegin, SawStore = false;
  309. do {
  310. MachineInstr &MI = *I; // The instruction to sink.
  311. // Predecrement I (if it's not begin) so that it isn't invalidated by
  312. // sinking.
  313. ProcessedBegin = I == MBB.begin();
  314. if (!ProcessedBegin)
  315. --I;
  316. if (MI.isDebugValue())
  317. continue;
  318. bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
  319. if (Joined) {
  320. MadeChange = true;
  321. continue;
  322. }
  323. if (SinkInstruction(MI, SawStore, AllSuccessors)) {
  324. ++NumSunk;
  325. MadeChange = true;
  326. }
  327. // If we just processed the first instruction in the block, we're done.
  328. } while (!ProcessedBegin);
  329. return MadeChange;
  330. }
  331. bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr &MI,
  332. MachineBasicBlock *From,
  333. MachineBasicBlock *To) {
  334. // FIXME: Need much better heuristics.
  335. // If the pass has already considered breaking this edge (during this pass
  336. // through the function), then let's go ahead and break it. This means
  337. // sinking multiple "cheap" instructions into the same block.
  338. if (!CEBCandidates.insert(std::make_pair(From, To)).second)
  339. return true;
  340. if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI))
  341. return true;
  342. if (From->isSuccessor(To) && MBPI->getEdgeProbability(From, To) <=
  343. BranchProbability(SplitEdgeProbabilityThreshold, 100))
  344. return true;
  345. // MI is cheap, we probably don't want to break the critical edge for it.
  346. // However, if this would allow some definitions of its source operands
  347. // to be sunk then it's probably worth it.
  348. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  349. const MachineOperand &MO = MI.getOperand(i);
  350. if (!MO.isReg() || !MO.isUse())
  351. continue;
  352. unsigned Reg = MO.getReg();
  353. if (Reg == 0)
  354. continue;
  355. // We don't move live definitions of physical registers,
  356. // so sinking their uses won't enable any opportunities.
  357. if (TargetRegisterInfo::isPhysicalRegister(Reg))
  358. continue;
  359. // If this instruction is the only user of a virtual register,
  360. // check if breaking the edge will enable sinking
  361. // both this instruction and the defining instruction.
  362. if (MRI->hasOneNonDBGUse(Reg)) {
  363. // If the definition resides in same MBB,
  364. // claim it's likely we can sink these together.
  365. // If definition resides elsewhere, we aren't
  366. // blocking it from being sunk so don't break the edge.
  367. MachineInstr *DefMI = MRI->getVRegDef(Reg);
  368. if (DefMI->getParent() == MI.getParent())
  369. return true;
  370. }
  371. }
  372. return false;
  373. }
  374. bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
  375. MachineBasicBlock *FromBB,
  376. MachineBasicBlock *ToBB,
  377. bool BreakPHIEdge) {
  378. if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
  379. return false;
  380. // Avoid breaking back edge. From == To means backedge for single BB loop.
  381. if (!SplitEdges || FromBB == ToBB)
  382. return false;
  383. // Check for backedges of more "complex" loops.
  384. if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
  385. LI->isLoopHeader(ToBB))
  386. return false;
  387. // It's not always legal to break critical edges and sink the computation
  388. // to the edge.
  389. //
  390. // BB#1:
  391. // v1024
  392. // Beq BB#3
  393. // <fallthrough>
  394. // BB#2:
  395. // ... no uses of v1024
  396. // <fallthrough>
  397. // BB#3:
  398. // ...
  399. // = v1024
  400. //
  401. // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
  402. //
  403. // BB#1:
  404. // ...
  405. // Bne BB#2
  406. // BB#4:
  407. // v1024 =
  408. // B BB#3
  409. // BB#2:
  410. // ... no uses of v1024
  411. // <fallthrough>
  412. // BB#3:
  413. // ...
  414. // = v1024
  415. //
  416. // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
  417. // flow. We need to ensure the new basic block where the computation is
  418. // sunk to dominates all the uses.
  419. // It's only legal to break critical edge and sink the computation to the
  420. // new block if all the predecessors of "To", except for "From", are
  421. // not dominated by "From". Given SSA property, this means these
  422. // predecessors are dominated by "To".
  423. //
  424. // There is no need to do this check if all the uses are PHI nodes. PHI
  425. // sources are only defined on the specific predecessor edges.
  426. if (!BreakPHIEdge) {
  427. for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
  428. E = ToBB->pred_end(); PI != E; ++PI) {
  429. if (*PI == FromBB)
  430. continue;
  431. if (!DT->dominates(ToBB, *PI))
  432. return false;
  433. }
  434. }
  435. ToSplit.insert(std::make_pair(FromBB, ToBB));
  436. return true;
  437. }
  438. /// collectDebgValues - Scan instructions following MI and collect any
  439. /// matching DBG_VALUEs.
  440. static void collectDebugValues(MachineInstr &MI,
  441. SmallVectorImpl<MachineInstr *> &DbgValues) {
  442. DbgValues.clear();
  443. if (!MI.getOperand(0).isReg())
  444. return;
  445. MachineBasicBlock::iterator DI = MI; ++DI;
  446. for (MachineBasicBlock::iterator DE = MI.getParent()->end();
  447. DI != DE; ++DI) {
  448. if (!DI->isDebugValue())
  449. return;
  450. if (DI->getOperand(0).isReg() &&
  451. DI->getOperand(0).getReg() == MI.getOperand(0).getReg())
  452. DbgValues.push_back(&*DI);
  453. }
  454. }
  455. /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
  456. bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr &MI,
  457. MachineBasicBlock *MBB,
  458. MachineBasicBlock *SuccToSinkTo,
  459. AllSuccsCache &AllSuccessors) {
  460. assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
  461. if (MBB == SuccToSinkTo)
  462. return false;
  463. // It is profitable if SuccToSinkTo does not post dominate current block.
  464. if (!PDT->dominates(SuccToSinkTo, MBB))
  465. return true;
  466. // It is profitable to sink an instruction from a deeper loop to a shallower
  467. // loop, even if the latter post-dominates the former (PR21115).
  468. if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo))
  469. return true;
  470. // Check if only use in post dominated block is PHI instruction.
  471. bool NonPHIUse = false;
  472. for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
  473. MachineBasicBlock *UseBlock = UseInst.getParent();
  474. if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
  475. NonPHIUse = true;
  476. }
  477. if (!NonPHIUse)
  478. return true;
  479. // If SuccToSinkTo post dominates then also it may be profitable if MI
  480. // can further profitably sinked into another block in next round.
  481. bool BreakPHIEdge = false;
  482. // FIXME - If finding successor is compile time expensive then cache results.
  483. if (MachineBasicBlock *MBB2 =
  484. FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
  485. return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
  486. // If SuccToSinkTo is final destination and it is a post dominator of current
  487. // block then it is not profitable to sink MI into SuccToSinkTo block.
  488. return false;
  489. }
  490. /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
  491. /// computing it if it was not already cached.
  492. SmallVector<MachineBasicBlock *, 4> &
  493. MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
  494. AllSuccsCache &AllSuccessors) const {
  495. // Do we have the sorted successors in cache ?
  496. auto Succs = AllSuccessors.find(MBB);
  497. if (Succs != AllSuccessors.end())
  498. return Succs->second;
  499. SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->succ_begin(),
  500. MBB->succ_end());
  501. // Handle cases where sinking can happen but where the sink point isn't a
  502. // successor. For example:
  503. //
  504. // x = computation
  505. // if () {} else {}
  506. // use x
  507. //
  508. const std::vector<MachineDomTreeNode *> &Children =
  509. DT->getNode(MBB)->getChildren();
  510. for (const auto &DTChild : Children)
  511. // DomTree children of MBB that have MBB as immediate dominator are added.
  512. if (DTChild->getIDom()->getBlock() == MI.getParent() &&
  513. // Skip MBBs already added to the AllSuccs vector above.
  514. !MBB->isSuccessor(DTChild->getBlock()))
  515. AllSuccs.push_back(DTChild->getBlock());
  516. // Sort Successors according to their loop depth or block frequency info.
  517. std::stable_sort(
  518. AllSuccs.begin(), AllSuccs.end(),
  519. [this](const MachineBasicBlock *L, const MachineBasicBlock *R) {
  520. uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
  521. uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
  522. bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0;
  523. return HasBlockFreq ? LHSFreq < RHSFreq
  524. : LI->getLoopDepth(L) < LI->getLoopDepth(R);
  525. });
  526. auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
  527. return it.first->second;
  528. }
  529. /// FindSuccToSinkTo - Find a successor to sink this instruction to.
  530. MachineBasicBlock *
  531. MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
  532. bool &BreakPHIEdge,
  533. AllSuccsCache &AllSuccessors) {
  534. assert (MBB && "Invalid MachineBasicBlock!");
  535. // Loop over all the operands of the specified instruction. If there is
  536. // anything we can't handle, bail out.
  537. // SuccToSinkTo - This is the successor to sink this instruction to, once we
  538. // decide.
  539. MachineBasicBlock *SuccToSinkTo = nullptr;
  540. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  541. const MachineOperand &MO = MI.getOperand(i);
  542. if (!MO.isReg()) continue; // Ignore non-register operands.
  543. unsigned Reg = MO.getReg();
  544. if (Reg == 0) continue;
  545. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  546. if (MO.isUse()) {
  547. // If the physreg has no defs anywhere, it's just an ambient register
  548. // and we can freely move its uses. Alternatively, if it's allocatable,
  549. // it could get allocated to something with a def during allocation.
  550. if (!MRI->isConstantPhysReg(Reg))
  551. return nullptr;
  552. } else if (!MO.isDead()) {
  553. // A def that isn't dead. We can't move it.
  554. return nullptr;
  555. }
  556. } else {
  557. // Virtual register uses are always safe to sink.
  558. if (MO.isUse()) continue;
  559. // If it's not safe to move defs of the register class, then abort.
  560. if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
  561. return nullptr;
  562. // Virtual register defs can only be sunk if all their uses are in blocks
  563. // dominated by one of the successors.
  564. if (SuccToSinkTo) {
  565. // If a previous operand picked a block to sink to, then this operand
  566. // must be sinkable to the same block.
  567. bool LocalUse = false;
  568. if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
  569. BreakPHIEdge, LocalUse))
  570. return nullptr;
  571. continue;
  572. }
  573. // Otherwise, we should look at all the successors and decide which one
  574. // we should sink to. If we have reliable block frequency information
  575. // (frequency != 0) available, give successors with smaller frequencies
  576. // higher priority, otherwise prioritize smaller loop depths.
  577. for (MachineBasicBlock *SuccBlock :
  578. GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
  579. bool LocalUse = false;
  580. if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
  581. BreakPHIEdge, LocalUse)) {
  582. SuccToSinkTo = SuccBlock;
  583. break;
  584. }
  585. if (LocalUse)
  586. // Def is used locally, it's never safe to move this def.
  587. return nullptr;
  588. }
  589. // If we couldn't find a block to sink to, ignore this instruction.
  590. if (!SuccToSinkTo)
  591. return nullptr;
  592. if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
  593. return nullptr;
  594. }
  595. }
  596. // It is not possible to sink an instruction into its own block. This can
  597. // happen with loops.
  598. if (MBB == SuccToSinkTo)
  599. return nullptr;
  600. // It's not safe to sink instructions to EH landing pad. Control flow into
  601. // landing pad is implicitly defined.
  602. if (SuccToSinkTo && SuccToSinkTo->isEHPad())
  603. return nullptr;
  604. return SuccToSinkTo;
  605. }
  606. /// \brief Return true if MI is likely to be usable as a memory operation by the
  607. /// implicit null check optimization.
  608. ///
  609. /// This is a "best effort" heuristic, and should not be relied upon for
  610. /// correctness. This returning true does not guarantee that the implicit null
  611. /// check optimization is legal over MI, and this returning false does not
  612. /// guarantee MI cannot possibly be used to do a null check.
  613. static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI,
  614. const TargetInstrInfo *TII,
  615. const TargetRegisterInfo *TRI) {
  616. typedef TargetInstrInfo::MachineBranchPredicate MachineBranchPredicate;
  617. auto *MBB = MI.getParent();
  618. if (MBB->pred_size() != 1)
  619. return false;
  620. auto *PredMBB = *MBB->pred_begin();
  621. auto *PredBB = PredMBB->getBasicBlock();
  622. // Frontends that don't use implicit null checks have no reason to emit
  623. // branches with make.implicit metadata, and this function should always
  624. // return false for them.
  625. if (!PredBB ||
  626. !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
  627. return false;
  628. unsigned BaseReg;
  629. int64_t Offset;
  630. if (!TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI))
  631. return false;
  632. if (!(MI.mayLoad() && !MI.isPredicable()))
  633. return false;
  634. MachineBranchPredicate MBP;
  635. if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
  636. return false;
  637. return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
  638. (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
  639. MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
  640. MBP.LHS.getReg() == BaseReg;
  641. }
  642. /// SinkInstruction - Determine whether it is safe to sink the specified machine
  643. /// instruction out of its current block into a successor.
  644. bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
  645. AllSuccsCache &AllSuccessors) {
  646. // Don't sink instructions that the target prefers not to sink.
  647. if (!TII->shouldSink(MI))
  648. return false;
  649. // Check if it's safe to move the instruction.
  650. if (!MI.isSafeToMove(AA, SawStore))
  651. return false;
  652. // Convergent operations may not be made control-dependent on additional
  653. // values.
  654. if (MI.isConvergent())
  655. return false;
  656. // Don't break implicit null checks. This is a performance heuristic, and not
  657. // required for correctness.
  658. if (SinkingPreventsImplicitNullCheck(MI, TII, TRI))
  659. return false;
  660. // FIXME: This should include support for sinking instructions within the
  661. // block they are currently in to shorten the live ranges. We often get
  662. // instructions sunk into the top of a large block, but it would be better to
  663. // also sink them down before their first use in the block. This xform has to
  664. // be careful not to *increase* register pressure though, e.g. sinking
  665. // "x = y + z" down if it kills y and z would increase the live ranges of y
  666. // and z and only shrink the live range of x.
  667. bool BreakPHIEdge = false;
  668. MachineBasicBlock *ParentBlock = MI.getParent();
  669. MachineBasicBlock *SuccToSinkTo =
  670. FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
  671. // If there are no outputs, it must have side-effects.
  672. if (!SuccToSinkTo)
  673. return false;
  674. // If the instruction to move defines a dead physical register which is live
  675. // when leaving the basic block, don't move it because it could turn into a
  676. // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
  677. for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
  678. const MachineOperand &MO = MI.getOperand(I);
  679. if (!MO.isReg()) continue;
  680. unsigned Reg = MO.getReg();
  681. if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  682. if (SuccToSinkTo->isLiveIn(Reg))
  683. return false;
  684. }
  685. DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
  686. // If the block has multiple predecessors, this is a critical edge.
  687. // Decide if we can sink along it or need to break the edge.
  688. if (SuccToSinkTo->pred_size() > 1) {
  689. // We cannot sink a load across a critical edge - there may be stores in
  690. // other code paths.
  691. bool TryBreak = false;
  692. bool store = true;
  693. if (!MI.isSafeToMove(AA, store)) {
  694. DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
  695. TryBreak = true;
  696. }
  697. // We don't want to sink across a critical edge if we don't dominate the
  698. // successor. We could be introducing calculations to new code paths.
  699. if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
  700. DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
  701. TryBreak = true;
  702. }
  703. // Don't sink instructions into a loop.
  704. if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
  705. DEBUG(dbgs() << " *** NOTE: Loop header found\n");
  706. TryBreak = true;
  707. }
  708. // Otherwise we are OK with sinking along a critical edge.
  709. if (!TryBreak)
  710. DEBUG(dbgs() << "Sinking along critical edge.\n");
  711. else {
  712. // Mark this edge as to be split.
  713. // If the edge can actually be split, the next iteration of the main loop
  714. // will sink MI in the newly created block.
  715. bool Status =
  716. PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
  717. if (!Status)
  718. DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
  719. "break critical edge\n");
  720. // The instruction will not be sunk this time.
  721. return false;
  722. }
  723. }
  724. if (BreakPHIEdge) {
  725. // BreakPHIEdge is true if all the uses are in the successor MBB being
  726. // sunken into and they are all PHI nodes. In this case, machine-sink must
  727. // break the critical edge first.
  728. bool Status = PostponeSplitCriticalEdge(MI, ParentBlock,
  729. SuccToSinkTo, BreakPHIEdge);
  730. if (!Status)
  731. DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
  732. "break critical edge\n");
  733. // The instruction will not be sunk this time.
  734. return false;
  735. }
  736. // Determine where to insert into. Skip phi nodes.
  737. MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
  738. while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
  739. ++InsertPos;
  740. // collect matching debug values.
  741. SmallVector<MachineInstr *, 2> DbgValuesToSink;
  742. collectDebugValues(MI, DbgValuesToSink);
  743. // Move the instruction.
  744. SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
  745. ++MachineBasicBlock::iterator(MI));
  746. // Move debug values.
  747. for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
  748. DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
  749. MachineInstr *DbgMI = *DBI;
  750. SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI,
  751. ++MachineBasicBlock::iterator(DbgMI));
  752. }
  753. // Conservatively, clear any kill flags, since it's possible that they are no
  754. // longer correct.
  755. // Note that we have to clear the kill flags for any register this instruction
  756. // uses as we may sink over another instruction which currently kills the
  757. // used registers.
  758. for (MachineOperand &MO : MI.operands()) {
  759. if (MO.isReg() && MO.isUse())
  760. RegsToClearKillFlags.set(MO.getReg()); // Remember to clear kill flags.
  761. }
  762. return true;
  763. }