MachineSink.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845
  1. //===- MachineSink.cpp - Sinking for machine instructions -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass moves instructions into successor blocks when possible, so that
  10. // they aren't executed on paths where their results aren't needed.
  11. //
  12. // This pass is not intended to be a replacement or a complete alternative
  13. // for an LLVM-IR-level sinking pass. It is only designed to sink simple
  14. // constructs that are not exposed before lowering and instruction selection.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/ADT/DenseSet.h"
  18. #include "llvm/ADT/MapVector.h"
  19. #include "llvm/ADT/PointerIntPair.h"
  20. #include "llvm/ADT/PostOrderIterator.h"
  21. #include "llvm/ADT/SetVector.h"
  22. #include "llvm/ADT/SmallSet.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/SparseBitVector.h"
  25. #include "llvm/ADT/Statistic.h"
  26. #include "llvm/Analysis/AliasAnalysis.h"
  27. #include "llvm/Analysis/CFG.h"
  28. #include "llvm/CodeGen/MachineBasicBlock.h"
  29. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  30. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  31. #include "llvm/CodeGen/MachineDominators.h"
  32. #include "llvm/CodeGen/MachineFunction.h"
  33. #include "llvm/CodeGen/MachineFunctionPass.h"
  34. #include "llvm/CodeGen/MachineInstr.h"
  35. #include "llvm/CodeGen/MachineLoopInfo.h"
  36. #include "llvm/CodeGen/MachineOperand.h"
  37. #include "llvm/CodeGen/MachinePostDominators.h"
  38. #include "llvm/CodeGen/MachineRegisterInfo.h"
  39. #include "llvm/CodeGen/RegisterClassInfo.h"
  40. #include "llvm/CodeGen/RegisterPressure.h"
  41. #include "llvm/CodeGen/TargetInstrInfo.h"
  42. #include "llvm/CodeGen/TargetRegisterInfo.h"
  43. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  44. #include "llvm/IR/BasicBlock.h"
  45. #include "llvm/IR/DebugInfoMetadata.h"
  46. #include "llvm/IR/LLVMContext.h"
  47. #include "llvm/InitializePasses.h"
  48. #include "llvm/MC/MCRegisterInfo.h"
  49. #include "llvm/Pass.h"
  50. #include "llvm/Support/BranchProbability.h"
  51. #include "llvm/Support/CommandLine.h"
  52. #include "llvm/Support/Debug.h"
  53. #include "llvm/Support/raw_ostream.h"
  54. #include <algorithm>
  55. #include <cassert>
  56. #include <cstdint>
  57. #include <map>
  58. #include <utility>
  59. #include <vector>
  60. using namespace llvm;
  61. #define DEBUG_TYPE "machine-sink"
  62. static cl::opt<bool>
  63. SplitEdges("machine-sink-split",
  64. cl::desc("Split critical edges during machine sinking"),
  65. cl::init(true), cl::Hidden);
  66. static cl::opt<bool>
  67. UseBlockFreqInfo("machine-sink-bfi",
  68. cl::desc("Use block frequency info to find successors to sink"),
  69. cl::init(true), cl::Hidden);
  70. static cl::opt<unsigned> SplitEdgeProbabilityThreshold(
  71. "machine-sink-split-probability-threshold",
  72. cl::desc(
  73. "Percentage threshold for splitting single-instruction critical edge. "
  74. "If the branch threshold is higher than this threshold, we allow "
  75. "speculative execution of up to 1 instruction to avoid branching to "
  76. "splitted critical edge"),
  77. cl::init(40), cl::Hidden);
  78. static cl::opt<unsigned> SinkLoadInstsPerBlockThreshold(
  79. "machine-sink-load-instrs-threshold",
  80. cl::desc("Do not try to find alias store for a load if there is a in-path "
  81. "block whose instruction number is higher than this threshold."),
  82. cl::init(2000), cl::Hidden);
  83. static cl::opt<unsigned> SinkLoadBlocksThreshold(
  84. "machine-sink-load-blocks-threshold",
  85. cl::desc("Do not try to find alias store for a load if the block number in "
  86. "the straight line is higher than this threshold."),
  87. cl::init(20), cl::Hidden);
  88. static cl::opt<bool>
  89. SinkInstsIntoLoop("sink-insts-to-avoid-spills",
  90. cl::desc("Sink instructions into loops to avoid "
  91. "register spills"),
  92. cl::init(false), cl::Hidden);
  93. static cl::opt<unsigned> SinkIntoLoopLimit(
  94. "machine-sink-loop-limit",
  95. cl::desc("The maximum number of instructions considered for loop sinking."),
  96. cl::init(50), cl::Hidden);
  97. STATISTIC(NumSunk, "Number of machine instructions sunk");
  98. STATISTIC(NumLoopSunk, "Number of machine instructions sunk into a loop");
  99. STATISTIC(NumSplit, "Number of critical edges split");
  100. STATISTIC(NumCoalesces, "Number of copies coalesced");
  101. STATISTIC(NumPostRACopySink, "Number of copies sunk after RA");
  102. namespace {
  103. class MachineSinking : public MachineFunctionPass {
  104. const TargetInstrInfo *TII;
  105. const TargetRegisterInfo *TRI;
  106. MachineRegisterInfo *MRI; // Machine register information
  107. MachineDominatorTree *DT; // Machine dominator tree
  108. MachinePostDominatorTree *PDT; // Machine post dominator tree
  109. MachineLoopInfo *LI;
  110. MachineBlockFrequencyInfo *MBFI;
  111. const MachineBranchProbabilityInfo *MBPI;
  112. AliasAnalysis *AA;
  113. RegisterClassInfo RegClassInfo;
  114. // Remember which edges have been considered for breaking.
  115. SmallSet<std::pair<MachineBasicBlock*, MachineBasicBlock*>, 8>
  116. CEBCandidates;
  117. // Remember which edges we are about to split.
  118. // This is different from CEBCandidates since those edges
  119. // will be split.
  120. SetVector<std::pair<MachineBasicBlock *, MachineBasicBlock *>> ToSplit;
  121. DenseSet<Register> RegsToClearKillFlags;
  122. using AllSuccsCache =
  123. std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>;
  124. /// DBG_VALUE pointer and flag. The flag is true if this DBG_VALUE is
  125. /// post-dominated by another DBG_VALUE of the same variable location.
  126. /// This is necessary to detect sequences such as:
  127. /// %0 = someinst
  128. /// DBG_VALUE %0, !123, !DIExpression()
  129. /// %1 = anotherinst
  130. /// DBG_VALUE %1, !123, !DIExpression()
  131. /// Where if %0 were to sink, the DBG_VAUE should not sink with it, as that
  132. /// would re-order assignments.
  133. using SeenDbgUser = PointerIntPair<MachineInstr *, 1>;
  134. /// Record of DBG_VALUE uses of vregs in a block, so that we can identify
  135. /// debug instructions to sink.
  136. SmallDenseMap<unsigned, TinyPtrVector<SeenDbgUser>> SeenDbgUsers;
  137. /// Record of debug variables that have had their locations set in the
  138. /// current block.
  139. DenseSet<DebugVariable> SeenDbgVars;
  140. std::map<std::pair<MachineBasicBlock *, MachineBasicBlock *>, bool>
  141. HasStoreCache;
  142. std::map<std::pair<MachineBasicBlock *, MachineBasicBlock *>,
  143. std::vector<MachineInstr *>>
  144. StoreInstrCache;
  145. /// Cached BB's register pressure.
  146. std::map<MachineBasicBlock *, std::vector<unsigned>> CachedRegisterPressure;
  147. public:
  148. static char ID; // Pass identification
  149. MachineSinking() : MachineFunctionPass(ID) {
  150. initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
  151. }
  152. bool runOnMachineFunction(MachineFunction &MF) override;
  153. void getAnalysisUsage(AnalysisUsage &AU) const override {
  154. MachineFunctionPass::getAnalysisUsage(AU);
  155. AU.addRequired<AAResultsWrapperPass>();
  156. AU.addRequired<MachineDominatorTree>();
  157. AU.addRequired<MachinePostDominatorTree>();
  158. AU.addRequired<MachineLoopInfo>();
  159. AU.addRequired<MachineBranchProbabilityInfo>();
  160. AU.addPreserved<MachineLoopInfo>();
  161. if (UseBlockFreqInfo)
  162. AU.addRequired<MachineBlockFrequencyInfo>();
  163. }
  164. void releaseMemory() override {
  165. CEBCandidates.clear();
  166. }
  167. private:
  168. bool ProcessBlock(MachineBasicBlock &MBB);
  169. void ProcessDbgInst(MachineInstr &MI);
  170. bool isWorthBreakingCriticalEdge(MachineInstr &MI,
  171. MachineBasicBlock *From,
  172. MachineBasicBlock *To);
  173. bool hasStoreBetween(MachineBasicBlock *From, MachineBasicBlock *To,
  174. MachineInstr &MI);
  175. /// Postpone the splitting of the given critical
  176. /// edge (\p From, \p To).
  177. ///
  178. /// We do not split the edges on the fly. Indeed, this invalidates
  179. /// the dominance information and thus triggers a lot of updates
  180. /// of that information underneath.
  181. /// Instead, we postpone all the splits after each iteration of
  182. /// the main loop. That way, the information is at least valid
  183. /// for the lifetime of an iteration.
  184. ///
  185. /// \return True if the edge is marked as toSplit, false otherwise.
  186. /// False can be returned if, for instance, this is not profitable.
  187. bool PostponeSplitCriticalEdge(MachineInstr &MI,
  188. MachineBasicBlock *From,
  189. MachineBasicBlock *To,
  190. bool BreakPHIEdge);
  191. bool SinkInstruction(MachineInstr &MI, bool &SawStore,
  192. AllSuccsCache &AllSuccessors);
  193. /// If we sink a COPY inst, some debug users of it's destination may no
  194. /// longer be dominated by the COPY, and will eventually be dropped.
  195. /// This is easily rectified by forwarding the non-dominated debug uses
  196. /// to the copy source.
  197. void SalvageUnsunkDebugUsersOfCopy(MachineInstr &,
  198. MachineBasicBlock *TargetBlock);
  199. bool AllUsesDominatedByBlock(Register Reg, MachineBasicBlock *MBB,
  200. MachineBasicBlock *DefMBB, bool &BreakPHIEdge,
  201. bool &LocalUse) const;
  202. MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
  203. bool &BreakPHIEdge, AllSuccsCache &AllSuccessors);
  204. void FindLoopSinkCandidates(MachineLoop *L, MachineBasicBlock *BB,
  205. SmallVectorImpl<MachineInstr *> &Candidates);
  206. bool SinkIntoLoop(MachineLoop *L, MachineInstr &I);
  207. bool isProfitableToSinkTo(Register Reg, MachineInstr &MI,
  208. MachineBasicBlock *MBB,
  209. MachineBasicBlock *SuccToSinkTo,
  210. AllSuccsCache &AllSuccessors);
  211. bool PerformTrivialForwardCoalescing(MachineInstr &MI,
  212. MachineBasicBlock *MBB);
  213. SmallVector<MachineBasicBlock *, 4> &
  214. GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
  215. AllSuccsCache &AllSuccessors) const;
  216. std::vector<unsigned> &getBBRegisterPressure(MachineBasicBlock &MBB);
  217. };
  218. } // end anonymous namespace
  219. char MachineSinking::ID = 0;
  220. char &llvm::MachineSinkingID = MachineSinking::ID;
  221. INITIALIZE_PASS_BEGIN(MachineSinking, DEBUG_TYPE,
  222. "Machine code sinking", false, false)
  223. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  224. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  225. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  226. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  227. INITIALIZE_PASS_END(MachineSinking, DEBUG_TYPE,
  228. "Machine code sinking", false, false)
  229. bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI,
  230. MachineBasicBlock *MBB) {
  231. if (!MI.isCopy())
  232. return false;
  233. Register SrcReg = MI.getOperand(1).getReg();
  234. Register DstReg = MI.getOperand(0).getReg();
  235. if (!Register::isVirtualRegister(SrcReg) ||
  236. !Register::isVirtualRegister(DstReg) || !MRI->hasOneNonDBGUse(SrcReg))
  237. return false;
  238. const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
  239. const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
  240. if (SRC != DRC)
  241. return false;
  242. MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
  243. if (DefMI->isCopyLike())
  244. return false;
  245. LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
  246. LLVM_DEBUG(dbgs() << "*** to: " << MI);
  247. MRI->replaceRegWith(DstReg, SrcReg);
  248. MI.eraseFromParent();
  249. // Conservatively, clear any kill flags, since it's possible that they are no
  250. // longer correct.
  251. MRI->clearKillFlags(SrcReg);
  252. ++NumCoalesces;
  253. return true;
  254. }
  255. /// AllUsesDominatedByBlock - Return true if all uses of the specified register
  256. /// occur in blocks dominated by the specified block. If any use is in the
  257. /// definition block, then return false since it is never legal to move def
  258. /// after uses.
  259. bool MachineSinking::AllUsesDominatedByBlock(Register Reg,
  260. MachineBasicBlock *MBB,
  261. MachineBasicBlock *DefMBB,
  262. bool &BreakPHIEdge,
  263. bool &LocalUse) const {
  264. assert(Register::isVirtualRegister(Reg) && "Only makes sense for vregs");
  265. // Ignore debug uses because debug info doesn't affect the code.
  266. if (MRI->use_nodbg_empty(Reg))
  267. return true;
  268. // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
  269. // into and they are all PHI nodes. In this case, machine-sink must break
  270. // the critical edge first. e.g.
  271. //
  272. // %bb.1:
  273. // Predecessors according to CFG: %bb.0
  274. // ...
  275. // %def = DEC64_32r %x, implicit-def dead %eflags
  276. // ...
  277. // JE_4 <%bb.37>, implicit %eflags
  278. // Successors according to CFG: %bb.37 %bb.2
  279. //
  280. // %bb.2:
  281. // %p = PHI %y, %bb.0, %def, %bb.1
  282. if (all_of(MRI->use_nodbg_operands(Reg), [&](MachineOperand &MO) {
  283. MachineInstr *UseInst = MO.getParent();
  284. unsigned OpNo = UseInst->getOperandNo(&MO);
  285. MachineBasicBlock *UseBlock = UseInst->getParent();
  286. return UseBlock == MBB && UseInst->isPHI() &&
  287. UseInst->getOperand(OpNo + 1).getMBB() == DefMBB;
  288. })) {
  289. BreakPHIEdge = true;
  290. return true;
  291. }
  292. for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
  293. // Determine the block of the use.
  294. MachineInstr *UseInst = MO.getParent();
  295. unsigned OpNo = &MO - &UseInst->getOperand(0);
  296. MachineBasicBlock *UseBlock = UseInst->getParent();
  297. if (UseInst->isPHI()) {
  298. // PHI nodes use the operand in the predecessor block, not the block with
  299. // the PHI.
  300. UseBlock = UseInst->getOperand(OpNo+1).getMBB();
  301. } else if (UseBlock == DefMBB) {
  302. LocalUse = true;
  303. return false;
  304. }
  305. // Check that it dominates.
  306. if (!DT->dominates(MBB, UseBlock))
  307. return false;
  308. }
  309. return true;
  310. }
  311. /// Return true if this machine instruction loads from global offset table or
  312. /// constant pool.
  313. static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
  314. assert(MI.mayLoad() && "Expected MI that loads!");
  315. // If we lost memory operands, conservatively assume that the instruction
  316. // reads from everything..
  317. if (MI.memoperands_empty())
  318. return true;
  319. for (MachineMemOperand *MemOp : MI.memoperands())
  320. if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
  321. if (PSV->isGOT() || PSV->isConstantPool())
  322. return true;
  323. return false;
  324. }
  325. void MachineSinking::FindLoopSinkCandidates(MachineLoop *L, MachineBasicBlock *BB,
  326. SmallVectorImpl<MachineInstr *> &Candidates) {
  327. for (auto &MI : *BB) {
  328. LLVM_DEBUG(dbgs() << "LoopSink: Analysing candidate: " << MI);
  329. if (!TII->shouldSink(MI)) {
  330. LLVM_DEBUG(dbgs() << "LoopSink: Instruction not a candidate for this "
  331. "target\n");
  332. continue;
  333. }
  334. if (!L->isLoopInvariant(MI)) {
  335. LLVM_DEBUG(dbgs() << "LoopSink: Instruction is not loop invariant\n");
  336. continue;
  337. }
  338. bool DontMoveAcrossStore = true;
  339. if (!MI.isSafeToMove(AA, DontMoveAcrossStore)) {
  340. LLVM_DEBUG(dbgs() << "LoopSink: Instruction not safe to move.\n");
  341. continue;
  342. }
  343. if (MI.mayLoad() && !mayLoadFromGOTOrConstantPool(MI)) {
  344. LLVM_DEBUG(dbgs() << "LoopSink: Dont sink GOT or constant pool loads\n");
  345. continue;
  346. }
  347. if (MI.isConvergent())
  348. continue;
  349. const MachineOperand &MO = MI.getOperand(0);
  350. if (!MO.isReg() || !MO.getReg() || !MO.isDef())
  351. continue;
  352. if (!MRI->hasOneDef(MO.getReg()))
  353. continue;
  354. LLVM_DEBUG(dbgs() << "LoopSink: Instruction added as candidate.\n");
  355. Candidates.push_back(&MI);
  356. }
  357. }
  358. bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
  359. if (skipFunction(MF.getFunction()))
  360. return false;
  361. LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n");
  362. TII = MF.getSubtarget().getInstrInfo();
  363. TRI = MF.getSubtarget().getRegisterInfo();
  364. MRI = &MF.getRegInfo();
  365. DT = &getAnalysis<MachineDominatorTree>();
  366. PDT = &getAnalysis<MachinePostDominatorTree>();
  367. LI = &getAnalysis<MachineLoopInfo>();
  368. MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr;
  369. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  370. AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  371. RegClassInfo.runOnMachineFunction(MF);
  372. // MachineSink currently uses MachineLoopInfo, which only recognizes natural
  373. // loops. As such, we could sink instructions into irreducible cycles, which
  374. // would be non-profitable.
  375. // WARNING: The current implementation of hasStoreBetween() is incorrect for
  376. // sinking into irreducible cycles (PR53990), this bailout is currently
  377. // necessary for correctness, not just profitability.
  378. ReversePostOrderTraversal<MachineBasicBlock *> RPOT(&*MF.begin());
  379. if (containsIrreducibleCFG<MachineBasicBlock *>(RPOT, *LI))
  380. return false;
  381. bool EverMadeChange = false;
  382. while (true) {
  383. bool MadeChange = false;
  384. // Process all basic blocks.
  385. CEBCandidates.clear();
  386. ToSplit.clear();
  387. for (auto &MBB: MF)
  388. MadeChange |= ProcessBlock(MBB);
  389. // If we have anything we marked as toSplit, split it now.
  390. for (auto &Pair : ToSplit) {
  391. auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this);
  392. if (NewSucc != nullptr) {
  393. LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "
  394. << printMBBReference(*Pair.first) << " -- "
  395. << printMBBReference(*NewSucc) << " -- "
  396. << printMBBReference(*Pair.second) << '\n');
  397. if (MBFI)
  398. MBFI->onEdgeSplit(*Pair.first, *NewSucc, *MBPI);
  399. MadeChange = true;
  400. ++NumSplit;
  401. } else
  402. LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n");
  403. }
  404. // If this iteration over the code changed anything, keep iterating.
  405. if (!MadeChange) break;
  406. EverMadeChange = true;
  407. }
  408. if (SinkInstsIntoLoop) {
  409. SmallVector<MachineLoop *, 8> Loops(LI->begin(), LI->end());
  410. for (auto *L : Loops) {
  411. MachineBasicBlock *Preheader = LI->findLoopPreheader(L);
  412. if (!Preheader) {
  413. LLVM_DEBUG(dbgs() << "LoopSink: Can't find preheader\n");
  414. continue;
  415. }
  416. SmallVector<MachineInstr *, 8> Candidates;
  417. FindLoopSinkCandidates(L, Preheader, Candidates);
  418. // Walk the candidates in reverse order so that we start with the use
  419. // of a def-use chain, if there is any.
  420. // TODO: Sort the candidates using a cost-model.
  421. unsigned i = 0;
  422. for (MachineInstr *I : llvm::reverse(Candidates)) {
  423. if (i++ == SinkIntoLoopLimit) {
  424. LLVM_DEBUG(dbgs() << "LoopSink: Limit reached of instructions to "
  425. "be analysed.");
  426. break;
  427. }
  428. if (!SinkIntoLoop(L, *I))
  429. break;
  430. EverMadeChange = true;
  431. ++NumLoopSunk;
  432. }
  433. }
  434. }
  435. HasStoreCache.clear();
  436. StoreInstrCache.clear();
  437. // Now clear any kill flags for recorded registers.
  438. for (auto I : RegsToClearKillFlags)
  439. MRI->clearKillFlags(I);
  440. RegsToClearKillFlags.clear();
  441. return EverMadeChange;
  442. }
  443. bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
  444. // Can't sink anything out of a block that has less than two successors.
  445. if (MBB.succ_size() <= 1 || MBB.empty()) return false;
  446. // Don't bother sinking code out of unreachable blocks. In addition to being
  447. // unprofitable, it can also lead to infinite looping, because in an
  448. // unreachable loop there may be nowhere to stop.
  449. if (!DT->isReachableFromEntry(&MBB)) return false;
  450. bool MadeChange = false;
  451. // Cache all successors, sorted by frequency info and loop depth.
  452. AllSuccsCache AllSuccessors;
  453. // Walk the basic block bottom-up. Remember if we saw a store.
  454. MachineBasicBlock::iterator I = MBB.end();
  455. --I;
  456. bool ProcessedBegin, SawStore = false;
  457. do {
  458. MachineInstr &MI = *I; // The instruction to sink.
  459. // Predecrement I (if it's not begin) so that it isn't invalidated by
  460. // sinking.
  461. ProcessedBegin = I == MBB.begin();
  462. if (!ProcessedBegin)
  463. --I;
  464. if (MI.isDebugOrPseudoInstr()) {
  465. if (MI.isDebugValue())
  466. ProcessDbgInst(MI);
  467. continue;
  468. }
  469. bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
  470. if (Joined) {
  471. MadeChange = true;
  472. continue;
  473. }
  474. if (SinkInstruction(MI, SawStore, AllSuccessors)) {
  475. ++NumSunk;
  476. MadeChange = true;
  477. }
  478. // If we just processed the first instruction in the block, we're done.
  479. } while (!ProcessedBegin);
  480. SeenDbgUsers.clear();
  481. SeenDbgVars.clear();
  482. // recalculate the bb register pressure after sinking one BB.
  483. CachedRegisterPressure.clear();
  484. return MadeChange;
  485. }
  486. void MachineSinking::ProcessDbgInst(MachineInstr &MI) {
  487. // When we see DBG_VALUEs for registers, record any vreg it reads, so that
  488. // we know what to sink if the vreg def sinks.
  489. assert(MI.isDebugValue() && "Expected DBG_VALUE for processing");
  490. DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
  491. MI.getDebugLoc()->getInlinedAt());
  492. bool SeenBefore = SeenDbgVars.contains(Var);
  493. for (MachineOperand &MO : MI.debug_operands()) {
  494. if (MO.isReg() && MO.getReg().isVirtual())
  495. SeenDbgUsers[MO.getReg()].push_back(SeenDbgUser(&MI, SeenBefore));
  496. }
  497. // Record the variable for any DBG_VALUE, to avoid re-ordering any of them.
  498. SeenDbgVars.insert(Var);
  499. }
  500. bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr &MI,
  501. MachineBasicBlock *From,
  502. MachineBasicBlock *To) {
  503. // FIXME: Need much better heuristics.
  504. // If the pass has already considered breaking this edge (during this pass
  505. // through the function), then let's go ahead and break it. This means
  506. // sinking multiple "cheap" instructions into the same block.
  507. if (!CEBCandidates.insert(std::make_pair(From, To)).second)
  508. return true;
  509. if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI))
  510. return true;
  511. if (From->isSuccessor(To) && MBPI->getEdgeProbability(From, To) <=
  512. BranchProbability(SplitEdgeProbabilityThreshold, 100))
  513. return true;
  514. // MI is cheap, we probably don't want to break the critical edge for it.
  515. // However, if this would allow some definitions of its source operands
  516. // to be sunk then it's probably worth it.
  517. for (const MachineOperand &MO : MI.operands()) {
  518. if (!MO.isReg() || !MO.isUse())
  519. continue;
  520. Register Reg = MO.getReg();
  521. if (Reg == 0)
  522. continue;
  523. // We don't move live definitions of physical registers,
  524. // so sinking their uses won't enable any opportunities.
  525. if (Register::isPhysicalRegister(Reg))
  526. continue;
  527. // If this instruction is the only user of a virtual register,
  528. // check if breaking the edge will enable sinking
  529. // both this instruction and the defining instruction.
  530. if (MRI->hasOneNonDBGUse(Reg)) {
  531. // If the definition resides in same MBB,
  532. // claim it's likely we can sink these together.
  533. // If definition resides elsewhere, we aren't
  534. // blocking it from being sunk so don't break the edge.
  535. MachineInstr *DefMI = MRI->getVRegDef(Reg);
  536. if (DefMI->getParent() == MI.getParent())
  537. return true;
  538. }
  539. }
  540. return false;
  541. }
  542. bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
  543. MachineBasicBlock *FromBB,
  544. MachineBasicBlock *ToBB,
  545. bool BreakPHIEdge) {
  546. if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
  547. return false;
  548. // Avoid breaking back edge. From == To means backedge for single BB loop.
  549. if (!SplitEdges || FromBB == ToBB)
  550. return false;
  551. // Check for backedges of more "complex" loops.
  552. if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
  553. LI->isLoopHeader(ToBB))
  554. return false;
  555. // It's not always legal to break critical edges and sink the computation
  556. // to the edge.
  557. //
  558. // %bb.1:
  559. // v1024
  560. // Beq %bb.3
  561. // <fallthrough>
  562. // %bb.2:
  563. // ... no uses of v1024
  564. // <fallthrough>
  565. // %bb.3:
  566. // ...
  567. // = v1024
  568. //
  569. // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted:
  570. //
  571. // %bb.1:
  572. // ...
  573. // Bne %bb.2
  574. // %bb.4:
  575. // v1024 =
  576. // B %bb.3
  577. // %bb.2:
  578. // ... no uses of v1024
  579. // <fallthrough>
  580. // %bb.3:
  581. // ...
  582. // = v1024
  583. //
  584. // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3
  585. // flow. We need to ensure the new basic block where the computation is
  586. // sunk to dominates all the uses.
  587. // It's only legal to break critical edge and sink the computation to the
  588. // new block if all the predecessors of "To", except for "From", are
  589. // not dominated by "From". Given SSA property, this means these
  590. // predecessors are dominated by "To".
  591. //
  592. // There is no need to do this check if all the uses are PHI nodes. PHI
  593. // sources are only defined on the specific predecessor edges.
  594. if (!BreakPHIEdge) {
  595. for (MachineBasicBlock *Pred : ToBB->predecessors())
  596. if (Pred != FromBB && !DT->dominates(ToBB, Pred))
  597. return false;
  598. }
  599. ToSplit.insert(std::make_pair(FromBB, ToBB));
  600. return true;
  601. }
  602. std::vector<unsigned> &
  603. MachineSinking::getBBRegisterPressure(MachineBasicBlock &MBB) {
  604. // Currently to save compiling time, MBB's register pressure will not change
  605. // in one ProcessBlock iteration because of CachedRegisterPressure. but MBB's
  606. // register pressure is changed after sinking any instructions into it.
  607. // FIXME: need a accurate and cheap register pressure estiminate model here.
  608. auto RP = CachedRegisterPressure.find(&MBB);
  609. if (RP != CachedRegisterPressure.end())
  610. return RP->second;
  611. RegionPressure Pressure;
  612. RegPressureTracker RPTracker(Pressure);
  613. // Initialize the register pressure tracker.
  614. RPTracker.init(MBB.getParent(), &RegClassInfo, nullptr, &MBB, MBB.end(),
  615. /*TrackLaneMasks*/ false, /*TrackUntiedDefs=*/true);
  616. for (MachineBasicBlock::iterator MII = MBB.instr_end(),
  617. MIE = MBB.instr_begin();
  618. MII != MIE; --MII) {
  619. MachineInstr &MI = *std::prev(MII);
  620. if (MI.isDebugInstr() || MI.isPseudoProbe())
  621. continue;
  622. RegisterOperands RegOpers;
  623. RegOpers.collect(MI, *TRI, *MRI, false, false);
  624. RPTracker.recedeSkipDebugValues();
  625. assert(&*RPTracker.getPos() == &MI && "RPTracker sync error!");
  626. RPTracker.recede(RegOpers);
  627. }
  628. RPTracker.closeRegion();
  629. auto It = CachedRegisterPressure.insert(
  630. std::make_pair(&MBB, RPTracker.getPressure().MaxSetPressure));
  631. return It.first->second;
  632. }
  633. /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
  634. bool MachineSinking::isProfitableToSinkTo(Register Reg, MachineInstr &MI,
  635. MachineBasicBlock *MBB,
  636. MachineBasicBlock *SuccToSinkTo,
  637. AllSuccsCache &AllSuccessors) {
  638. assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
  639. if (MBB == SuccToSinkTo)
  640. return false;
  641. // It is profitable if SuccToSinkTo does not post dominate current block.
  642. if (!PDT->dominates(SuccToSinkTo, MBB))
  643. return true;
  644. // It is profitable to sink an instruction from a deeper loop to a shallower
  645. // loop, even if the latter post-dominates the former (PR21115).
  646. if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo))
  647. return true;
  648. // Check if only use in post dominated block is PHI instruction.
  649. bool NonPHIUse = false;
  650. for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
  651. MachineBasicBlock *UseBlock = UseInst.getParent();
  652. if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
  653. NonPHIUse = true;
  654. }
  655. if (!NonPHIUse)
  656. return true;
  657. // If SuccToSinkTo post dominates then also it may be profitable if MI
  658. // can further profitably sinked into another block in next round.
  659. bool BreakPHIEdge = false;
  660. // FIXME - If finding successor is compile time expensive then cache results.
  661. if (MachineBasicBlock *MBB2 =
  662. FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
  663. return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
  664. MachineLoop *ML = LI->getLoopFor(MBB);
  665. // If the instruction is not inside a loop, it is not profitable to sink MI to
  666. // a post dominate block SuccToSinkTo.
  667. if (!ML)
  668. return false;
  669. auto isRegisterPressureSetExceedLimit = [&](const TargetRegisterClass *RC) {
  670. unsigned Weight = TRI->getRegClassWeight(RC).RegWeight;
  671. const int *PS = TRI->getRegClassPressureSets(RC);
  672. // Get register pressure for block SuccToSinkTo.
  673. std::vector<unsigned> BBRegisterPressure =
  674. getBBRegisterPressure(*SuccToSinkTo);
  675. for (; *PS != -1; PS++)
  676. // check if any register pressure set exceeds limit in block SuccToSinkTo
  677. // after sinking.
  678. if (Weight + BBRegisterPressure[*PS] >=
  679. TRI->getRegPressureSetLimit(*MBB->getParent(), *PS))
  680. return true;
  681. return false;
  682. };
  683. // If this instruction is inside a loop and sinking this instruction can make
  684. // more registers live range shorten, it is still prifitable.
  685. for (const MachineOperand &MO : MI.operands()) {
  686. // Ignore non-register operands.
  687. if (!MO.isReg())
  688. continue;
  689. Register Reg = MO.getReg();
  690. if (Reg == 0)
  691. continue;
  692. if (Register::isPhysicalRegister(Reg)) {
  693. if (MO.isUse() &&
  694. (MRI->isConstantPhysReg(Reg) || TII->isIgnorableUse(MO)))
  695. continue;
  696. // Don't handle non-constant and non-ignorable physical register.
  697. return false;
  698. }
  699. // Users for the defs are all dominated by SuccToSinkTo.
  700. if (MO.isDef()) {
  701. // This def register's live range is shortened after sinking.
  702. bool LocalUse = false;
  703. if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, BreakPHIEdge,
  704. LocalUse))
  705. return false;
  706. } else {
  707. MachineInstr *DefMI = MRI->getVRegDef(Reg);
  708. // DefMI is defined outside of loop. There should be no live range
  709. // impact for this operand. Defination outside of loop means:
  710. // 1: defination is outside of loop.
  711. // 2: defination is in this loop, but it is a PHI in the loop header.
  712. if (LI->getLoopFor(DefMI->getParent()) != ML ||
  713. (DefMI->isPHI() && LI->isLoopHeader(DefMI->getParent())))
  714. continue;
  715. // The DefMI is defined inside the loop.
  716. // If sinking this operand makes some register pressure set exceed limit,
  717. // it is not profitable.
  718. if (isRegisterPressureSetExceedLimit(MRI->getRegClass(Reg))) {
  719. LLVM_DEBUG(dbgs() << "register pressure exceed limit, not profitable.");
  720. return false;
  721. }
  722. }
  723. }
  724. // If MI is in loop and all its operands are alive across the whole loop or if
  725. // no operand sinking make register pressure set exceed limit, it is
  726. // profitable to sink MI.
  727. return true;
  728. }
  729. /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
  730. /// computing it if it was not already cached.
  731. SmallVector<MachineBasicBlock *, 4> &
  732. MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
  733. AllSuccsCache &AllSuccessors) const {
  734. // Do we have the sorted successors in cache ?
  735. auto Succs = AllSuccessors.find(MBB);
  736. if (Succs != AllSuccessors.end())
  737. return Succs->second;
  738. SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->successors());
  739. // Handle cases where sinking can happen but where the sink point isn't a
  740. // successor. For example:
  741. //
  742. // x = computation
  743. // if () {} else {}
  744. // use x
  745. //
  746. for (MachineDomTreeNode *DTChild : DT->getNode(MBB)->children()) {
  747. // DomTree children of MBB that have MBB as immediate dominator are added.
  748. if (DTChild->getIDom()->getBlock() == MI.getParent() &&
  749. // Skip MBBs already added to the AllSuccs vector above.
  750. !MBB->isSuccessor(DTChild->getBlock()))
  751. AllSuccs.push_back(DTChild->getBlock());
  752. }
  753. // Sort Successors according to their loop depth or block frequency info.
  754. llvm::stable_sort(
  755. AllSuccs, [this](const MachineBasicBlock *L, const MachineBasicBlock *R) {
  756. uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
  757. uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
  758. bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0;
  759. return HasBlockFreq ? LHSFreq < RHSFreq
  760. : LI->getLoopDepth(L) < LI->getLoopDepth(R);
  761. });
  762. auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
  763. return it.first->second;
  764. }
  765. /// FindSuccToSinkTo - Find a successor to sink this instruction to.
  766. MachineBasicBlock *
  767. MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
  768. bool &BreakPHIEdge,
  769. AllSuccsCache &AllSuccessors) {
  770. assert (MBB && "Invalid MachineBasicBlock!");
  771. // Loop over all the operands of the specified instruction. If there is
  772. // anything we can't handle, bail out.
  773. // SuccToSinkTo - This is the successor to sink this instruction to, once we
  774. // decide.
  775. MachineBasicBlock *SuccToSinkTo = nullptr;
  776. for (const MachineOperand &MO : MI.operands()) {
  777. if (!MO.isReg()) continue; // Ignore non-register operands.
  778. Register Reg = MO.getReg();
  779. if (Reg == 0) continue;
  780. if (Register::isPhysicalRegister(Reg)) {
  781. if (MO.isUse()) {
  782. // If the physreg has no defs anywhere, it's just an ambient register
  783. // and we can freely move its uses. Alternatively, if it's allocatable,
  784. // it could get allocated to something with a def during allocation.
  785. if (!MRI->isConstantPhysReg(Reg) && !TII->isIgnorableUse(MO))
  786. return nullptr;
  787. } else if (!MO.isDead()) {
  788. // A def that isn't dead. We can't move it.
  789. return nullptr;
  790. }
  791. } else {
  792. // Virtual register uses are always safe to sink.
  793. if (MO.isUse()) continue;
  794. // If it's not safe to move defs of the register class, then abort.
  795. if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
  796. return nullptr;
  797. // Virtual register defs can only be sunk if all their uses are in blocks
  798. // dominated by one of the successors.
  799. if (SuccToSinkTo) {
  800. // If a previous operand picked a block to sink to, then this operand
  801. // must be sinkable to the same block.
  802. bool LocalUse = false;
  803. if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
  804. BreakPHIEdge, LocalUse))
  805. return nullptr;
  806. continue;
  807. }
  808. // Otherwise, we should look at all the successors and decide which one
  809. // we should sink to. If we have reliable block frequency information
  810. // (frequency != 0) available, give successors with smaller frequencies
  811. // higher priority, otherwise prioritize smaller loop depths.
  812. for (MachineBasicBlock *SuccBlock :
  813. GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
  814. bool LocalUse = false;
  815. if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
  816. BreakPHIEdge, LocalUse)) {
  817. SuccToSinkTo = SuccBlock;
  818. break;
  819. }
  820. if (LocalUse)
  821. // Def is used locally, it's never safe to move this def.
  822. return nullptr;
  823. }
  824. // If we couldn't find a block to sink to, ignore this instruction.
  825. if (!SuccToSinkTo)
  826. return nullptr;
  827. if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
  828. return nullptr;
  829. }
  830. }
  831. // It is not possible to sink an instruction into its own block. This can
  832. // happen with loops.
  833. if (MBB == SuccToSinkTo)
  834. return nullptr;
  835. // It's not safe to sink instructions to EH landing pad. Control flow into
  836. // landing pad is implicitly defined.
  837. if (SuccToSinkTo && SuccToSinkTo->isEHPad())
  838. return nullptr;
  839. // It ought to be okay to sink instructions into an INLINEASM_BR target, but
  840. // only if we make sure that MI occurs _before_ an INLINEASM_BR instruction in
  841. // the source block (which this code does not yet do). So for now, forbid
  842. // doing so.
  843. if (SuccToSinkTo && SuccToSinkTo->isInlineAsmBrIndirectTarget())
  844. return nullptr;
  845. return SuccToSinkTo;
  846. }
  847. /// Return true if MI is likely to be usable as a memory operation by the
  848. /// implicit null check optimization.
  849. ///
  850. /// This is a "best effort" heuristic, and should not be relied upon for
  851. /// correctness. This returning true does not guarantee that the implicit null
  852. /// check optimization is legal over MI, and this returning false does not
  853. /// guarantee MI cannot possibly be used to do a null check.
  854. static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI,
  855. const TargetInstrInfo *TII,
  856. const TargetRegisterInfo *TRI) {
  857. using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
  858. auto *MBB = MI.getParent();
  859. if (MBB->pred_size() != 1)
  860. return false;
  861. auto *PredMBB = *MBB->pred_begin();
  862. auto *PredBB = PredMBB->getBasicBlock();
  863. // Frontends that don't use implicit null checks have no reason to emit
  864. // branches with make.implicit metadata, and this function should always
  865. // return false for them.
  866. if (!PredBB ||
  867. !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
  868. return false;
  869. const MachineOperand *BaseOp;
  870. int64_t Offset;
  871. bool OffsetIsScalable;
  872. if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
  873. return false;
  874. if (!BaseOp->isReg())
  875. return false;
  876. if (!(MI.mayLoad() && !MI.isPredicable()))
  877. return false;
  878. MachineBranchPredicate MBP;
  879. if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
  880. return false;
  881. return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
  882. (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
  883. MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
  884. MBP.LHS.getReg() == BaseOp->getReg();
  885. }
  886. /// If the sunk instruction is a copy, try to forward the copy instead of
  887. /// leaving an 'undef' DBG_VALUE in the original location. Don't do this if
  888. /// there's any subregister weirdness involved. Returns true if copy
  889. /// propagation occurred.
  890. static bool attemptDebugCopyProp(MachineInstr &SinkInst, MachineInstr &DbgMI,
  891. Register Reg) {
  892. const MachineRegisterInfo &MRI = SinkInst.getMF()->getRegInfo();
  893. const TargetInstrInfo &TII = *SinkInst.getMF()->getSubtarget().getInstrInfo();
  894. // Copy DBG_VALUE operand and set the original to undef. We then check to
  895. // see whether this is something that can be copy-forwarded. If it isn't,
  896. // continue around the loop.
  897. const MachineOperand *SrcMO = nullptr, *DstMO = nullptr;
  898. auto CopyOperands = TII.isCopyInstr(SinkInst);
  899. if (!CopyOperands)
  900. return false;
  901. SrcMO = CopyOperands->Source;
  902. DstMO = CopyOperands->Destination;
  903. // Check validity of forwarding this copy.
  904. bool PostRA = MRI.getNumVirtRegs() == 0;
  905. // Trying to forward between physical and virtual registers is too hard.
  906. if (Reg.isVirtual() != SrcMO->getReg().isVirtual())
  907. return false;
  908. // Only try virtual register copy-forwarding before regalloc, and physical
  909. // register copy-forwarding after regalloc.
  910. bool arePhysRegs = !Reg.isVirtual();
  911. if (arePhysRegs != PostRA)
  912. return false;
  913. // Pre-regalloc, only forward if all subregisters agree (or there are no
  914. // subregs at all). More analysis might recover some forwardable copies.
  915. if (!PostRA)
  916. for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg))
  917. if (DbgMO.getSubReg() != SrcMO->getSubReg() ||
  918. DbgMO.getSubReg() != DstMO->getSubReg())
  919. return false;
  920. // Post-regalloc, we may be sinking a DBG_VALUE of a sub or super-register
  921. // of this copy. Only forward the copy if the DBG_VALUE operand exactly
  922. // matches the copy destination.
  923. if (PostRA && Reg != DstMO->getReg())
  924. return false;
  925. for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg)) {
  926. DbgMO.setReg(SrcMO->getReg());
  927. DbgMO.setSubReg(SrcMO->getSubReg());
  928. }
  929. return true;
  930. }
  931. using MIRegs = std::pair<MachineInstr *, SmallVector<unsigned, 2>>;
  932. /// Sink an instruction and its associated debug instructions.
  933. static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo,
  934. MachineBasicBlock::iterator InsertPos,
  935. SmallVectorImpl<MIRegs> &DbgValuesToSink) {
  936. // If we cannot find a location to use (merge with), then we erase the debug
  937. // location to prevent debug-info driven tools from potentially reporting
  938. // wrong location information.
  939. if (!SuccToSinkTo.empty() && InsertPos != SuccToSinkTo.end())
  940. MI.setDebugLoc(DILocation::getMergedLocation(MI.getDebugLoc(),
  941. InsertPos->getDebugLoc()));
  942. else
  943. MI.setDebugLoc(DebugLoc());
  944. // Move the instruction.
  945. MachineBasicBlock *ParentBlock = MI.getParent();
  946. SuccToSinkTo.splice(InsertPos, ParentBlock, MI,
  947. ++MachineBasicBlock::iterator(MI));
  948. // Sink a copy of debug users to the insert position. Mark the original
  949. // DBG_VALUE location as 'undef', indicating that any earlier variable
  950. // location should be terminated as we've optimised away the value at this
  951. // point.
  952. for (auto DbgValueToSink : DbgValuesToSink) {
  953. MachineInstr *DbgMI = DbgValueToSink.first;
  954. MachineInstr *NewDbgMI = DbgMI->getMF()->CloneMachineInstr(DbgMI);
  955. SuccToSinkTo.insert(InsertPos, NewDbgMI);
  956. bool PropagatedAllSunkOps = true;
  957. for (unsigned Reg : DbgValueToSink.second) {
  958. if (DbgMI->hasDebugOperandForReg(Reg)) {
  959. if (!attemptDebugCopyProp(MI, *DbgMI, Reg)) {
  960. PropagatedAllSunkOps = false;
  961. break;
  962. }
  963. }
  964. }
  965. if (!PropagatedAllSunkOps)
  966. DbgMI->setDebugValueUndef();
  967. }
  968. }
  969. /// hasStoreBetween - check if there is store betweeen straight line blocks From
  970. /// and To.
  971. bool MachineSinking::hasStoreBetween(MachineBasicBlock *From,
  972. MachineBasicBlock *To, MachineInstr &MI) {
  973. // Make sure From and To are in straight line which means From dominates To
  974. // and To post dominates From.
  975. if (!DT->dominates(From, To) || !PDT->dominates(To, From))
  976. return true;
  977. auto BlockPair = std::make_pair(From, To);
  978. // Does these two blocks pair be queried before and have a definite cached
  979. // result?
  980. if (HasStoreCache.find(BlockPair) != HasStoreCache.end())
  981. return HasStoreCache[BlockPair];
  982. if (StoreInstrCache.find(BlockPair) != StoreInstrCache.end())
  983. return llvm::any_of(StoreInstrCache[BlockPair], [&](MachineInstr *I) {
  984. return I->mayAlias(AA, MI, false);
  985. });
  986. bool SawStore = false;
  987. bool HasAliasedStore = false;
  988. DenseSet<MachineBasicBlock *> HandledBlocks;
  989. DenseSet<MachineBasicBlock *> HandledDomBlocks;
  990. // Go through all reachable blocks from From.
  991. for (MachineBasicBlock *BB : depth_first(From)) {
  992. // We insert the instruction at the start of block To, so no need to worry
  993. // about stores inside To.
  994. // Store in block From should be already considered when just enter function
  995. // SinkInstruction.
  996. if (BB == To || BB == From)
  997. continue;
  998. // We already handle this BB in previous iteration.
  999. if (HandledBlocks.count(BB))
  1000. continue;
  1001. HandledBlocks.insert(BB);
  1002. // To post dominates BB, it must be a path from block From.
  1003. if (PDT->dominates(To, BB)) {
  1004. if (!HandledDomBlocks.count(BB))
  1005. HandledDomBlocks.insert(BB);
  1006. // If this BB is too big or the block number in straight line between From
  1007. // and To is too big, stop searching to save compiling time.
  1008. if (BB->size() > SinkLoadInstsPerBlockThreshold ||
  1009. HandledDomBlocks.size() > SinkLoadBlocksThreshold) {
  1010. for (auto *DomBB : HandledDomBlocks) {
  1011. if (DomBB != BB && DT->dominates(DomBB, BB))
  1012. HasStoreCache[std::make_pair(DomBB, To)] = true;
  1013. else if(DomBB != BB && DT->dominates(BB, DomBB))
  1014. HasStoreCache[std::make_pair(From, DomBB)] = true;
  1015. }
  1016. HasStoreCache[BlockPair] = true;
  1017. return true;
  1018. }
  1019. for (MachineInstr &I : *BB) {
  1020. // Treat as alias conservatively for a call or an ordered memory
  1021. // operation.
  1022. if (I.isCall() || I.hasOrderedMemoryRef()) {
  1023. for (auto *DomBB : HandledDomBlocks) {
  1024. if (DomBB != BB && DT->dominates(DomBB, BB))
  1025. HasStoreCache[std::make_pair(DomBB, To)] = true;
  1026. else if(DomBB != BB && DT->dominates(BB, DomBB))
  1027. HasStoreCache[std::make_pair(From, DomBB)] = true;
  1028. }
  1029. HasStoreCache[BlockPair] = true;
  1030. return true;
  1031. }
  1032. if (I.mayStore()) {
  1033. SawStore = true;
  1034. // We still have chance to sink MI if all stores between are not
  1035. // aliased to MI.
  1036. // Cache all store instructions, so that we don't need to go through
  1037. // all From reachable blocks for next load instruction.
  1038. if (I.mayAlias(AA, MI, false))
  1039. HasAliasedStore = true;
  1040. StoreInstrCache[BlockPair].push_back(&I);
  1041. }
  1042. }
  1043. }
  1044. }
  1045. // If there is no store at all, cache the result.
  1046. if (!SawStore)
  1047. HasStoreCache[BlockPair] = false;
  1048. return HasAliasedStore;
  1049. }
  1050. /// Sink instructions into loops if profitable. This especially tries to prevent
  1051. /// register spills caused by register pressure if there is little to no
  1052. /// overhead moving instructions into loops.
  1053. bool MachineSinking::SinkIntoLoop(MachineLoop *L, MachineInstr &I) {
  1054. LLVM_DEBUG(dbgs() << "LoopSink: Finding sink block for: " << I);
  1055. MachineBasicBlock *Preheader = L->getLoopPreheader();
  1056. assert(Preheader && "Loop sink needs a preheader block");
  1057. MachineBasicBlock *SinkBlock = nullptr;
  1058. bool CanSink = true;
  1059. const MachineOperand &MO = I.getOperand(0);
  1060. for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
  1061. LLVM_DEBUG(dbgs() << "LoopSink: Analysing use: " << MI);
  1062. if (!L->contains(&MI)) {
  1063. LLVM_DEBUG(dbgs() << "LoopSink: Use not in loop, can't sink.\n");
  1064. CanSink = false;
  1065. break;
  1066. }
  1067. // FIXME: Come up with a proper cost model that estimates whether sinking
  1068. // the instruction (and thus possibly executing it on every loop
  1069. // iteration) is more expensive than a register.
  1070. // For now assumes that copies are cheap and thus almost always worth it.
  1071. if (!MI.isCopy()) {
  1072. LLVM_DEBUG(dbgs() << "LoopSink: Use is not a copy\n");
  1073. CanSink = false;
  1074. break;
  1075. }
  1076. if (!SinkBlock) {
  1077. SinkBlock = MI.getParent();
  1078. LLVM_DEBUG(dbgs() << "LoopSink: Setting sink block to: "
  1079. << printMBBReference(*SinkBlock) << "\n");
  1080. continue;
  1081. }
  1082. SinkBlock = DT->findNearestCommonDominator(SinkBlock, MI.getParent());
  1083. if (!SinkBlock) {
  1084. LLVM_DEBUG(dbgs() << "LoopSink: Can't find nearest dominator\n");
  1085. CanSink = false;
  1086. break;
  1087. }
  1088. LLVM_DEBUG(dbgs() << "LoopSink: Setting nearest common dom block: " <<
  1089. printMBBReference(*SinkBlock) << "\n");
  1090. }
  1091. if (!CanSink) {
  1092. LLVM_DEBUG(dbgs() << "LoopSink: Can't sink instruction.\n");
  1093. return false;
  1094. }
  1095. if (!SinkBlock) {
  1096. LLVM_DEBUG(dbgs() << "LoopSink: Not sinking, can't find sink block.\n");
  1097. return false;
  1098. }
  1099. if (SinkBlock == Preheader) {
  1100. LLVM_DEBUG(dbgs() << "LoopSink: Not sinking, sink block is the preheader\n");
  1101. return false;
  1102. }
  1103. if (SinkBlock->size() > SinkLoadInstsPerBlockThreshold) {
  1104. LLVM_DEBUG(dbgs() << "LoopSink: Not Sinking, block too large to analyse.\n");
  1105. return false;
  1106. }
  1107. LLVM_DEBUG(dbgs() << "LoopSink: Sinking instruction!\n");
  1108. SinkBlock->splice(SinkBlock->getFirstNonPHI(), Preheader, I);
  1109. // The instruction is moved from its basic block, so do not retain the
  1110. // debug information.
  1111. assert(!I.isDebugInstr() && "Should not sink debug inst");
  1112. I.setDebugLoc(DebugLoc());
  1113. return true;
  1114. }
  1115. /// SinkInstruction - Determine whether it is safe to sink the specified machine
  1116. /// instruction out of its current block into a successor.
  1117. bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
  1118. AllSuccsCache &AllSuccessors) {
  1119. // Don't sink instructions that the target prefers not to sink.
  1120. if (!TII->shouldSink(MI))
  1121. return false;
  1122. // Check if it's safe to move the instruction.
  1123. if (!MI.isSafeToMove(AA, SawStore))
  1124. return false;
  1125. // Convergent operations may not be made control-dependent on additional
  1126. // values.
  1127. if (MI.isConvergent())
  1128. return false;
  1129. // Don't break implicit null checks. This is a performance heuristic, and not
  1130. // required for correctness.
  1131. if (SinkingPreventsImplicitNullCheck(MI, TII, TRI))
  1132. return false;
  1133. // FIXME: This should include support for sinking instructions within the
  1134. // block they are currently in to shorten the live ranges. We often get
  1135. // instructions sunk into the top of a large block, but it would be better to
  1136. // also sink them down before their first use in the block. This xform has to
  1137. // be careful not to *increase* register pressure though, e.g. sinking
  1138. // "x = y + z" down if it kills y and z would increase the live ranges of y
  1139. // and z and only shrink the live range of x.
  1140. bool BreakPHIEdge = false;
  1141. MachineBasicBlock *ParentBlock = MI.getParent();
  1142. MachineBasicBlock *SuccToSinkTo =
  1143. FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
  1144. // If there are no outputs, it must have side-effects.
  1145. if (!SuccToSinkTo)
  1146. return false;
  1147. // If the instruction to move defines a dead physical register which is live
  1148. // when leaving the basic block, don't move it because it could turn into a
  1149. // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
  1150. for (const MachineOperand &MO : MI.operands()) {
  1151. if (!MO.isReg() || MO.isUse())
  1152. continue;
  1153. Register Reg = MO.getReg();
  1154. if (Reg == 0 || !Register::isPhysicalRegister(Reg))
  1155. continue;
  1156. if (SuccToSinkTo->isLiveIn(Reg))
  1157. return false;
  1158. }
  1159. LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
  1160. // If the block has multiple predecessors, this is a critical edge.
  1161. // Decide if we can sink along it or need to break the edge.
  1162. if (SuccToSinkTo->pred_size() > 1) {
  1163. // We cannot sink a load across a critical edge - there may be stores in
  1164. // other code paths.
  1165. bool TryBreak = false;
  1166. bool Store =
  1167. MI.mayLoad() ? hasStoreBetween(ParentBlock, SuccToSinkTo, MI) : true;
  1168. if (!MI.isSafeToMove(AA, Store)) {
  1169. LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
  1170. TryBreak = true;
  1171. }
  1172. // We don't want to sink across a critical edge if we don't dominate the
  1173. // successor. We could be introducing calculations to new code paths.
  1174. if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
  1175. LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
  1176. TryBreak = true;
  1177. }
  1178. // Don't sink instructions into a loop.
  1179. if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
  1180. LLVM_DEBUG(dbgs() << " *** NOTE: Loop header found\n");
  1181. TryBreak = true;
  1182. }
  1183. // Otherwise we are OK with sinking along a critical edge.
  1184. if (!TryBreak)
  1185. LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
  1186. else {
  1187. // Mark this edge as to be split.
  1188. // If the edge can actually be split, the next iteration of the main loop
  1189. // will sink MI in the newly created block.
  1190. bool Status =
  1191. PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
  1192. if (!Status)
  1193. LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
  1194. "break critical edge\n");
  1195. // The instruction will not be sunk this time.
  1196. return false;
  1197. }
  1198. }
  1199. if (BreakPHIEdge) {
  1200. // BreakPHIEdge is true if all the uses are in the successor MBB being
  1201. // sunken into and they are all PHI nodes. In this case, machine-sink must
  1202. // break the critical edge first.
  1203. bool Status = PostponeSplitCriticalEdge(MI, ParentBlock,
  1204. SuccToSinkTo, BreakPHIEdge);
  1205. if (!Status)
  1206. LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
  1207. "break critical edge\n");
  1208. // The instruction will not be sunk this time.
  1209. return false;
  1210. }
  1211. // Determine where to insert into. Skip phi nodes.
  1212. MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
  1213. while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
  1214. ++InsertPos;
  1215. // Collect debug users of any vreg that this inst defines.
  1216. SmallVector<MIRegs, 4> DbgUsersToSink;
  1217. for (auto &MO : MI.operands()) {
  1218. if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual())
  1219. continue;
  1220. if (!SeenDbgUsers.count(MO.getReg()))
  1221. continue;
  1222. // Sink any users that don't pass any other DBG_VALUEs for this variable.
  1223. auto &Users = SeenDbgUsers[MO.getReg()];
  1224. for (auto &User : Users) {
  1225. MachineInstr *DbgMI = User.getPointer();
  1226. if (User.getInt()) {
  1227. // This DBG_VALUE would re-order assignments. If we can't copy-propagate
  1228. // it, it can't be recovered. Set it undef.
  1229. if (!attemptDebugCopyProp(MI, *DbgMI, MO.getReg()))
  1230. DbgMI->setDebugValueUndef();
  1231. } else {
  1232. DbgUsersToSink.push_back(
  1233. {DbgMI, SmallVector<unsigned, 2>(1, MO.getReg())});
  1234. }
  1235. }
  1236. }
  1237. // After sinking, some debug users may not be dominated any more. If possible,
  1238. // copy-propagate their operands. As it's expensive, don't do this if there's
  1239. // no debuginfo in the program.
  1240. if (MI.getMF()->getFunction().getSubprogram() && MI.isCopy())
  1241. SalvageUnsunkDebugUsersOfCopy(MI, SuccToSinkTo);
  1242. performSink(MI, *SuccToSinkTo, InsertPos, DbgUsersToSink);
  1243. // Conservatively, clear any kill flags, since it's possible that they are no
  1244. // longer correct.
  1245. // Note that we have to clear the kill flags for any register this instruction
  1246. // uses as we may sink over another instruction which currently kills the
  1247. // used registers.
  1248. for (MachineOperand &MO : MI.operands()) {
  1249. if (MO.isReg() && MO.isUse())
  1250. RegsToClearKillFlags.insert(MO.getReg()); // Remember to clear kill flags.
  1251. }
  1252. return true;
  1253. }
  1254. void MachineSinking::SalvageUnsunkDebugUsersOfCopy(
  1255. MachineInstr &MI, MachineBasicBlock *TargetBlock) {
  1256. assert(MI.isCopy());
  1257. assert(MI.getOperand(1).isReg());
  1258. // Enumerate all users of vreg operands that are def'd. Skip those that will
  1259. // be sunk. For the rest, if they are not dominated by the block we will sink
  1260. // MI into, propagate the copy source to them.
  1261. SmallVector<MachineInstr *, 4> DbgDefUsers;
  1262. SmallVector<Register, 4> DbgUseRegs;
  1263. const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
  1264. for (auto &MO : MI.operands()) {
  1265. if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual())
  1266. continue;
  1267. DbgUseRegs.push_back(MO.getReg());
  1268. for (auto &User : MRI.use_instructions(MO.getReg())) {
  1269. if (!User.isDebugValue() || DT->dominates(TargetBlock, User.getParent()))
  1270. continue;
  1271. // If is in same block, will either sink or be use-before-def.
  1272. if (User.getParent() == MI.getParent())
  1273. continue;
  1274. assert(User.hasDebugOperandForReg(MO.getReg()) &&
  1275. "DBG_VALUE user of vreg, but has no operand for it?");
  1276. DbgDefUsers.push_back(&User);
  1277. }
  1278. }
  1279. // Point the users of this copy that are no longer dominated, at the source
  1280. // of the copy.
  1281. for (auto *User : DbgDefUsers) {
  1282. for (auto &Reg : DbgUseRegs) {
  1283. for (auto &DbgOp : User->getDebugOperandsForReg(Reg)) {
  1284. DbgOp.setReg(MI.getOperand(1).getReg());
  1285. DbgOp.setSubReg(MI.getOperand(1).getSubReg());
  1286. }
  1287. }
  1288. }
  1289. }
  1290. //===----------------------------------------------------------------------===//
  1291. // This pass is not intended to be a replacement or a complete alternative
  1292. // for the pre-ra machine sink pass. It is only designed to sink COPY
  1293. // instructions which should be handled after RA.
  1294. //
  1295. // This pass sinks COPY instructions into a successor block, if the COPY is not
  1296. // used in the current block and the COPY is live-in to a single successor
  1297. // (i.e., doesn't require the COPY to be duplicated). This avoids executing the
  1298. // copy on paths where their results aren't needed. This also exposes
  1299. // additional opportunites for dead copy elimination and shrink wrapping.
  1300. //
  1301. // These copies were either not handled by or are inserted after the MachineSink
  1302. // pass. As an example of the former case, the MachineSink pass cannot sink
  1303. // COPY instructions with allocatable source registers; for AArch64 these type
  1304. // of copy instructions are frequently used to move function parameters (PhyReg)
  1305. // into virtual registers in the entry block.
  1306. //
  1307. // For the machine IR below, this pass will sink %w19 in the entry into its
  1308. // successor (%bb.1) because %w19 is only live-in in %bb.1.
  1309. // %bb.0:
  1310. // %wzr = SUBSWri %w1, 1
  1311. // %w19 = COPY %w0
  1312. // Bcc 11, %bb.2
  1313. // %bb.1:
  1314. // Live Ins: %w19
  1315. // BL @fun
  1316. // %w0 = ADDWrr %w0, %w19
  1317. // RET %w0
  1318. // %bb.2:
  1319. // %w0 = COPY %wzr
  1320. // RET %w0
  1321. // As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be
  1322. // able to see %bb.0 as a candidate.
  1323. //===----------------------------------------------------------------------===//
  1324. namespace {
  1325. class PostRAMachineSinking : public MachineFunctionPass {
  1326. public:
  1327. bool runOnMachineFunction(MachineFunction &MF) override;
  1328. static char ID;
  1329. PostRAMachineSinking() : MachineFunctionPass(ID) {}
  1330. StringRef getPassName() const override { return "PostRA Machine Sink"; }
  1331. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1332. AU.setPreservesCFG();
  1333. MachineFunctionPass::getAnalysisUsage(AU);
  1334. }
  1335. MachineFunctionProperties getRequiredProperties() const override {
  1336. return MachineFunctionProperties().set(
  1337. MachineFunctionProperties::Property::NoVRegs);
  1338. }
  1339. private:
  1340. /// Track which register units have been modified and used.
  1341. LiveRegUnits ModifiedRegUnits, UsedRegUnits;
  1342. /// Track DBG_VALUEs of (unmodified) register units. Each DBG_VALUE has an
  1343. /// entry in this map for each unit it touches. The DBG_VALUE's entry
  1344. /// consists of a pointer to the instruction itself, and a vector of registers
  1345. /// referred to by the instruction that overlap the key register unit.
  1346. DenseMap<unsigned, SmallVector<MIRegs, 2>> SeenDbgInstrs;
  1347. /// Sink Copy instructions unused in the same block close to their uses in
  1348. /// successors.
  1349. bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF,
  1350. const TargetRegisterInfo *TRI, const TargetInstrInfo *TII);
  1351. };
  1352. } // namespace
  1353. char PostRAMachineSinking::ID = 0;
  1354. char &llvm::PostRAMachineSinkingID = PostRAMachineSinking::ID;
  1355. INITIALIZE_PASS(PostRAMachineSinking, "postra-machine-sink",
  1356. "PostRA Machine Sink", false, false)
  1357. static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, unsigned Reg,
  1358. const TargetRegisterInfo *TRI) {
  1359. LiveRegUnits LiveInRegUnits(*TRI);
  1360. LiveInRegUnits.addLiveIns(MBB);
  1361. return !LiveInRegUnits.available(Reg);
  1362. }
  1363. static MachineBasicBlock *
  1364. getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
  1365. const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
  1366. unsigned Reg, const TargetRegisterInfo *TRI) {
  1367. // Try to find a single sinkable successor in which Reg is live-in.
  1368. MachineBasicBlock *BB = nullptr;
  1369. for (auto *SI : SinkableBBs) {
  1370. if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) {
  1371. // If BB is set here, Reg is live-in to at least two sinkable successors,
  1372. // so quit.
  1373. if (BB)
  1374. return nullptr;
  1375. BB = SI;
  1376. }
  1377. }
  1378. // Reg is not live-in to any sinkable successors.
  1379. if (!BB)
  1380. return nullptr;
  1381. // Check if any register aliased with Reg is live-in in other successors.
  1382. for (auto *SI : CurBB.successors()) {
  1383. if (!SinkableBBs.count(SI) && aliasWithRegsInLiveIn(*SI, Reg, TRI))
  1384. return nullptr;
  1385. }
  1386. return BB;
  1387. }
  1388. static MachineBasicBlock *
  1389. getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
  1390. const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
  1391. ArrayRef<unsigned> DefedRegsInCopy,
  1392. const TargetRegisterInfo *TRI) {
  1393. MachineBasicBlock *SingleBB = nullptr;
  1394. for (auto DefReg : DefedRegsInCopy) {
  1395. MachineBasicBlock *BB =
  1396. getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI);
  1397. if (!BB || (SingleBB && SingleBB != BB))
  1398. return nullptr;
  1399. SingleBB = BB;
  1400. }
  1401. return SingleBB;
  1402. }
  1403. static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB,
  1404. SmallVectorImpl<unsigned> &UsedOpsInCopy,
  1405. LiveRegUnits &UsedRegUnits,
  1406. const TargetRegisterInfo *TRI) {
  1407. for (auto U : UsedOpsInCopy) {
  1408. MachineOperand &MO = MI->getOperand(U);
  1409. Register SrcReg = MO.getReg();
  1410. if (!UsedRegUnits.available(SrcReg)) {
  1411. MachineBasicBlock::iterator NI = std::next(MI->getIterator());
  1412. for (MachineInstr &UI : make_range(NI, CurBB.end())) {
  1413. if (UI.killsRegister(SrcReg, TRI)) {
  1414. UI.clearRegisterKills(SrcReg, TRI);
  1415. MO.setIsKill(true);
  1416. break;
  1417. }
  1418. }
  1419. }
  1420. }
  1421. }
  1422. static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB,
  1423. SmallVectorImpl<unsigned> &UsedOpsInCopy,
  1424. SmallVectorImpl<unsigned> &DefedRegsInCopy) {
  1425. MachineFunction &MF = *SuccBB->getParent();
  1426. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  1427. for (unsigned DefReg : DefedRegsInCopy)
  1428. for (MCSubRegIterator S(DefReg, TRI, true); S.isValid(); ++S)
  1429. SuccBB->removeLiveIn(*S);
  1430. for (auto U : UsedOpsInCopy) {
  1431. Register SrcReg = MI->getOperand(U).getReg();
  1432. LaneBitmask Mask;
  1433. for (MCRegUnitMaskIterator S(SrcReg, TRI); S.isValid(); ++S) {
  1434. Mask |= (*S).second;
  1435. }
  1436. SuccBB->addLiveIn(SrcReg, Mask.any() ? Mask : LaneBitmask::getAll());
  1437. }
  1438. SuccBB->sortUniqueLiveIns();
  1439. }
  1440. static bool hasRegisterDependency(MachineInstr *MI,
  1441. SmallVectorImpl<unsigned> &UsedOpsInCopy,
  1442. SmallVectorImpl<unsigned> &DefedRegsInCopy,
  1443. LiveRegUnits &ModifiedRegUnits,
  1444. LiveRegUnits &UsedRegUnits) {
  1445. bool HasRegDependency = false;
  1446. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  1447. MachineOperand &MO = MI->getOperand(i);
  1448. if (!MO.isReg())
  1449. continue;
  1450. Register Reg = MO.getReg();
  1451. if (!Reg)
  1452. continue;
  1453. if (MO.isDef()) {
  1454. if (!ModifiedRegUnits.available(Reg) || !UsedRegUnits.available(Reg)) {
  1455. HasRegDependency = true;
  1456. break;
  1457. }
  1458. DefedRegsInCopy.push_back(Reg);
  1459. // FIXME: instead of isUse(), readsReg() would be a better fix here,
  1460. // For example, we can ignore modifications in reg with undef. However,
  1461. // it's not perfectly clear if skipping the internal read is safe in all
  1462. // other targets.
  1463. } else if (MO.isUse()) {
  1464. if (!ModifiedRegUnits.available(Reg)) {
  1465. HasRegDependency = true;
  1466. break;
  1467. }
  1468. UsedOpsInCopy.push_back(i);
  1469. }
  1470. }
  1471. return HasRegDependency;
  1472. }
  1473. static SmallSet<MCRegister, 4> getRegUnits(MCRegister Reg,
  1474. const TargetRegisterInfo *TRI) {
  1475. SmallSet<MCRegister, 4> RegUnits;
  1476. for (auto RI = MCRegUnitIterator(Reg, TRI); RI.isValid(); ++RI)
  1477. RegUnits.insert(*RI);
  1478. return RegUnits;
  1479. }
  1480. bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock &CurBB,
  1481. MachineFunction &MF,
  1482. const TargetRegisterInfo *TRI,
  1483. const TargetInstrInfo *TII) {
  1484. SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs;
  1485. // FIXME: For now, we sink only to a successor which has a single predecessor
  1486. // so that we can directly sink COPY instructions to the successor without
  1487. // adding any new block or branch instruction.
  1488. for (MachineBasicBlock *SI : CurBB.successors())
  1489. if (!SI->livein_empty() && SI->pred_size() == 1)
  1490. SinkableBBs.insert(SI);
  1491. if (SinkableBBs.empty())
  1492. return false;
  1493. bool Changed = false;
  1494. // Track which registers have been modified and used between the end of the
  1495. // block and the current instruction.
  1496. ModifiedRegUnits.clear();
  1497. UsedRegUnits.clear();
  1498. SeenDbgInstrs.clear();
  1499. for (MachineInstr &MI : llvm::make_early_inc_range(llvm::reverse(CurBB))) {
  1500. // Track the operand index for use in Copy.
  1501. SmallVector<unsigned, 2> UsedOpsInCopy;
  1502. // Track the register number defed in Copy.
  1503. SmallVector<unsigned, 2> DefedRegsInCopy;
  1504. // We must sink this DBG_VALUE if its operand is sunk. To avoid searching
  1505. // for DBG_VALUEs later, record them when they're encountered.
  1506. if (MI.isDebugValue()) {
  1507. SmallDenseMap<MCRegister, SmallVector<unsigned, 2>, 4> MIUnits;
  1508. bool IsValid = true;
  1509. for (MachineOperand &MO : MI.debug_operands()) {
  1510. if (MO.isReg() && Register::isPhysicalRegister(MO.getReg())) {
  1511. // Bail if we can already tell the sink would be rejected, rather
  1512. // than needlessly accumulating lots of DBG_VALUEs.
  1513. if (hasRegisterDependency(&MI, UsedOpsInCopy, DefedRegsInCopy,
  1514. ModifiedRegUnits, UsedRegUnits)) {
  1515. IsValid = false;
  1516. break;
  1517. }
  1518. // Record debug use of each reg unit.
  1519. SmallSet<MCRegister, 4> RegUnits = getRegUnits(MO.getReg(), TRI);
  1520. for (MCRegister Reg : RegUnits)
  1521. MIUnits[Reg].push_back(MO.getReg());
  1522. }
  1523. }
  1524. if (IsValid) {
  1525. for (auto RegOps : MIUnits)
  1526. SeenDbgInstrs[RegOps.first].push_back({&MI, RegOps.second});
  1527. }
  1528. continue;
  1529. }
  1530. if (MI.isDebugOrPseudoInstr())
  1531. continue;
  1532. // Do not move any instruction across function call.
  1533. if (MI.isCall())
  1534. return false;
  1535. if (!MI.isCopy() || !MI.getOperand(0).isRenamable()) {
  1536. LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
  1537. TRI);
  1538. continue;
  1539. }
  1540. // Don't sink the COPY if it would violate a register dependency.
  1541. if (hasRegisterDependency(&MI, UsedOpsInCopy, DefedRegsInCopy,
  1542. ModifiedRegUnits, UsedRegUnits)) {
  1543. LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
  1544. TRI);
  1545. continue;
  1546. }
  1547. assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) &&
  1548. "Unexpect SrcReg or DefReg");
  1549. MachineBasicBlock *SuccBB =
  1550. getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI);
  1551. // Don't sink if we cannot find a single sinkable successor in which Reg
  1552. // is live-in.
  1553. if (!SuccBB) {
  1554. LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
  1555. TRI);
  1556. continue;
  1557. }
  1558. assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) &&
  1559. "Unexpected predecessor");
  1560. // Collect DBG_VALUEs that must sink with this copy. We've previously
  1561. // recorded which reg units that DBG_VALUEs read, if this instruction
  1562. // writes any of those units then the corresponding DBG_VALUEs must sink.
  1563. MapVector<MachineInstr *, MIRegs::second_type> DbgValsToSinkMap;
  1564. for (auto &MO : MI.operands()) {
  1565. if (!MO.isReg() || !MO.isDef())
  1566. continue;
  1567. SmallSet<MCRegister, 4> Units = getRegUnits(MO.getReg(), TRI);
  1568. for (MCRegister Reg : Units) {
  1569. for (auto MIRegs : SeenDbgInstrs.lookup(Reg)) {
  1570. auto &Regs = DbgValsToSinkMap[MIRegs.first];
  1571. for (unsigned Reg : MIRegs.second)
  1572. Regs.push_back(Reg);
  1573. }
  1574. }
  1575. }
  1576. SmallVector<MIRegs, 4> DbgValsToSink(DbgValsToSinkMap.begin(),
  1577. DbgValsToSinkMap.end());
  1578. // Clear the kill flag if SrcReg is killed between MI and the end of the
  1579. // block.
  1580. clearKillFlags(&MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI);
  1581. MachineBasicBlock::iterator InsertPos = SuccBB->getFirstNonPHI();
  1582. performSink(MI, *SuccBB, InsertPos, DbgValsToSink);
  1583. updateLiveIn(&MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy);
  1584. Changed = true;
  1585. ++NumPostRACopySink;
  1586. }
  1587. return Changed;
  1588. }
  1589. bool PostRAMachineSinking::runOnMachineFunction(MachineFunction &MF) {
  1590. if (skipFunction(MF.getFunction()))
  1591. return false;
  1592. bool Changed = false;
  1593. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  1594. const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
  1595. ModifiedRegUnits.init(*TRI);
  1596. UsedRegUnits.init(*TRI);
  1597. for (auto &BB : MF)
  1598. Changed |= tryToSinkCopy(BB, MF, TRI, TII);
  1599. return Changed;
  1600. }