MachineSink.cpp 33 KB

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