MachineSink.cpp 32 KB

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