xref: /llvm-project/llvm/lib/CodeGen/MachineSink.cpp (revision 553058f825157b33a2d7f793c811f301260b765b)
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 
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/DepthFirstIterator.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/PointerIntPair.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/CFG.h"
28 #include "llvm/Analysis/ProfileSummaryInfo.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
31 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
32 #include "llvm/CodeGen/MachineCycleAnalysis.h"
33 #include "llvm/CodeGen/MachineDominators.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineFunctionPass.h"
36 #include "llvm/CodeGen/MachineInstr.h"
37 #include "llvm/CodeGen/MachineLoopInfo.h"
38 #include "llvm/CodeGen/MachineOperand.h"
39 #include "llvm/CodeGen/MachinePostDominators.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/MachineSizeOpts.h"
42 #include "llvm/CodeGen/RegisterClassInfo.h"
43 #include "llvm/CodeGen/RegisterPressure.h"
44 #include "llvm/CodeGen/TargetInstrInfo.h"
45 #include "llvm/CodeGen/TargetPassConfig.h"
46 #include "llvm/CodeGen/TargetRegisterInfo.h"
47 #include "llvm/CodeGen/TargetSubtargetInfo.h"
48 #include "llvm/IR/BasicBlock.h"
49 #include "llvm/IR/DebugInfoMetadata.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/InitializePasses.h"
52 #include "llvm/Pass.h"
53 #include "llvm/Support/BranchProbability.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include <cassert>
58 #include <cstdint>
59 #include <utility>
60 #include <vector>
61 
62 using namespace llvm;
63 
64 #define DEBUG_TYPE "machine-sink"
65 
66 static cl::opt<bool>
67     SplitEdges("machine-sink-split",
68                cl::desc("Split critical edges during machine sinking"),
69                cl::init(true), cl::Hidden);
70 
71 static cl::opt<bool> UseBlockFreqInfo(
72     "machine-sink-bfi",
73     cl::desc("Use block frequency info to find successors to sink"),
74     cl::init(true), cl::Hidden);
75 
76 static cl::opt<unsigned> SplitEdgeProbabilityThreshold(
77     "machine-sink-split-probability-threshold",
78     cl::desc(
79         "Percentage threshold for splitting single-instruction critical edge. "
80         "If the branch threshold is higher than this threshold, we allow "
81         "speculative execution of up to 1 instruction to avoid branching to "
82         "splitted critical edge"),
83     cl::init(40), cl::Hidden);
84 
85 static cl::opt<unsigned> SinkLoadInstsPerBlockThreshold(
86     "machine-sink-load-instrs-threshold",
87     cl::desc("Do not try to find alias store for a load if there is a in-path "
88              "block whose instruction number is higher than this threshold."),
89     cl::init(2000), cl::Hidden);
90 
91 static cl::opt<unsigned> SinkLoadBlocksThreshold(
92     "machine-sink-load-blocks-threshold",
93     cl::desc("Do not try to find alias store for a load if the block number in "
94              "the straight line is higher than this threshold."),
95     cl::init(20), cl::Hidden);
96 
97 static cl::opt<bool>
98     SinkInstsIntoCycle("sink-insts-to-avoid-spills",
99                        cl::desc("Sink instructions into cycles to avoid "
100                                 "register spills"),
101                        cl::init(false), cl::Hidden);
102 
103 static cl::opt<unsigned> SinkIntoCycleLimit(
104     "machine-sink-cycle-limit",
105     cl::desc(
106         "The maximum number of instructions considered for cycle sinking."),
107     cl::init(50), cl::Hidden);
108 
109 STATISTIC(NumSunk, "Number of machine instructions sunk");
110 STATISTIC(NumCycleSunk, "Number of machine instructions sunk into a cycle");
111 STATISTIC(NumSplit, "Number of critical edges split");
112 STATISTIC(NumCoalesces, "Number of copies coalesced");
113 STATISTIC(NumPostRACopySink, "Number of copies sunk after RA");
114 
115 namespace {
116 
117 class MachineSinking : public MachineFunctionPass {
118   const TargetSubtargetInfo *STI = nullptr;
119   const TargetInstrInfo *TII = nullptr;
120   const TargetRegisterInfo *TRI = nullptr;
121   MachineRegisterInfo *MRI = nullptr;      // Machine register information
122   MachineDominatorTree *DT = nullptr;      // Machine dominator tree
123   MachinePostDominatorTree *PDT = nullptr; // Machine post dominator tree
124   MachineCycleInfo *CI = nullptr;
125   ProfileSummaryInfo *PSI = nullptr;
126   MachineBlockFrequencyInfo *MBFI = nullptr;
127   const MachineBranchProbabilityInfo *MBPI = nullptr;
128   AliasAnalysis *AA = nullptr;
129   RegisterClassInfo RegClassInfo;
130 
131   // Remember which edges have been considered for breaking.
132   SmallSet<std::pair<MachineBasicBlock *, MachineBasicBlock *>, 8>
133       CEBCandidates;
134   // Memorize the register that also wanted to sink into the same block along
135   // a different critical edge.
136   // {register to sink, sink-to block} -> the first sink-from block.
137   // We're recording the first sink-from block because that (critical) edge
138   // was deferred until we see another register that's going to sink into the
139   // same block.
140   DenseMap<std::pair<Register, MachineBasicBlock *>, MachineBasicBlock *>
141       CEMergeCandidates;
142   // Remember which edges we are about to split.
143   // This is different from CEBCandidates since those edges
144   // will be split.
145   SetVector<std::pair<MachineBasicBlock *, MachineBasicBlock *>> ToSplit;
146 
147   DenseSet<Register> RegsToClearKillFlags;
148 
149   using AllSuccsCache =
150       SmallDenseMap<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>;
151 
152   /// DBG_VALUE pointer and flag. The flag is true if this DBG_VALUE is
153   /// post-dominated by another DBG_VALUE of the same variable location.
154   /// This is necessary to detect sequences such as:
155   ///     %0 = someinst
156   ///     DBG_VALUE %0, !123, !DIExpression()
157   ///     %1 = anotherinst
158   ///     DBG_VALUE %1, !123, !DIExpression()
159   /// Where if %0 were to sink, the DBG_VAUE should not sink with it, as that
160   /// would re-order assignments.
161   using SeenDbgUser = PointerIntPair<MachineInstr *, 1>;
162 
163   /// Record of DBG_VALUE uses of vregs in a block, so that we can identify
164   /// debug instructions to sink.
165   SmallDenseMap<unsigned, TinyPtrVector<SeenDbgUser>> SeenDbgUsers;
166 
167   /// Record of debug variables that have had their locations set in the
168   /// current block.
169   DenseSet<DebugVariable> SeenDbgVars;
170 
171   DenseMap<std::pair<MachineBasicBlock *, MachineBasicBlock *>, bool>
172       HasStoreCache;
173 
174   DenseMap<std::pair<MachineBasicBlock *, MachineBasicBlock *>,
175            SmallVector<MachineInstr *>>
176       StoreInstrCache;
177 
178   /// Cached BB's register pressure.
179   DenseMap<const MachineBasicBlock *, std::vector<unsigned>>
180       CachedRegisterPressure;
181 
182   bool EnableSinkAndFold;
183 
184 public:
185   static char ID; // Pass identification
186 
187   MachineSinking() : MachineFunctionPass(ID) {
188     initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
189   }
190 
191   bool runOnMachineFunction(MachineFunction &MF) override;
192 
193   void getAnalysisUsage(AnalysisUsage &AU) const override {
194     MachineFunctionPass::getAnalysisUsage(AU);
195     AU.addRequired<AAResultsWrapperPass>();
196     AU.addRequired<MachineDominatorTreeWrapperPass>();
197     AU.addRequired<MachinePostDominatorTreeWrapperPass>();
198     AU.addRequired<MachineCycleInfoWrapperPass>();
199     AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
200     AU.addPreserved<MachineCycleInfoWrapperPass>();
201     AU.addPreserved<MachineLoopInfoWrapperPass>();
202     AU.addRequired<ProfileSummaryInfoWrapperPass>();
203     if (UseBlockFreqInfo)
204       AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
205     AU.addRequired<TargetPassConfig>();
206   }
207 
208   void releaseMemory() override {
209     CEBCandidates.clear();
210     CEMergeCandidates.clear();
211   }
212 
213 private:
214   bool ProcessBlock(MachineBasicBlock &MBB);
215   void ProcessDbgInst(MachineInstr &MI);
216   bool isLegalToBreakCriticalEdge(MachineInstr &MI, MachineBasicBlock *From,
217                                   MachineBasicBlock *To, bool BreakPHIEdge);
218   bool isWorthBreakingCriticalEdge(MachineInstr &MI, MachineBasicBlock *From,
219                                    MachineBasicBlock *To,
220                                    MachineBasicBlock *&DeferredFromBlock);
221 
222   bool hasStoreBetween(MachineBasicBlock *From, MachineBasicBlock *To,
223                        MachineInstr &MI);
224 
225   /// Postpone the splitting of the given critical
226   /// edge (\p From, \p To).
227   ///
228   /// We do not split the edges on the fly. Indeed, this invalidates
229   /// the dominance information and thus triggers a lot of updates
230   /// of that information underneath.
231   /// Instead, we postpone all the splits after each iteration of
232   /// the main loop. That way, the information is at least valid
233   /// for the lifetime of an iteration.
234   ///
235   /// \return True if the edge is marked as toSplit, false otherwise.
236   /// False can be returned if, for instance, this is not profitable.
237   bool PostponeSplitCriticalEdge(MachineInstr &MI, MachineBasicBlock *From,
238                                  MachineBasicBlock *To, bool BreakPHIEdge);
239   bool SinkInstruction(MachineInstr &MI, bool &SawStore,
240                        AllSuccsCache &AllSuccessors);
241 
242   /// If we sink a COPY inst, some debug users of it's destination may no
243   /// longer be dominated by the COPY, and will eventually be dropped.
244   /// This is easily rectified by forwarding the non-dominated debug uses
245   /// to the copy source.
246   void SalvageUnsunkDebugUsersOfCopy(MachineInstr &,
247                                      MachineBasicBlock *TargetBlock);
248   bool AllUsesDominatedByBlock(Register Reg, MachineBasicBlock *MBB,
249                                MachineBasicBlock *DefMBB, bool &BreakPHIEdge,
250                                bool &LocalUse) const;
251   MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
252                                       bool &BreakPHIEdge,
253                                       AllSuccsCache &AllSuccessors);
254 
255   void FindCycleSinkCandidates(MachineCycle *Cycle, MachineBasicBlock *BB,
256                                SmallVectorImpl<MachineInstr *> &Candidates);
257   bool SinkIntoCycle(MachineCycle *Cycle, MachineInstr &I);
258 
259   bool isProfitableToSinkTo(Register Reg, MachineInstr &MI,
260                             MachineBasicBlock *MBB,
261                             MachineBasicBlock *SuccToSinkTo,
262                             AllSuccsCache &AllSuccessors);
263 
264   bool PerformTrivialForwardCoalescing(MachineInstr &MI,
265                                        MachineBasicBlock *MBB);
266 
267   bool PerformSinkAndFold(MachineInstr &MI, MachineBasicBlock *MBB);
268 
269   SmallVector<MachineBasicBlock *, 4> &
270   GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
271                          AllSuccsCache &AllSuccessors) const;
272 
273   std::vector<unsigned> &getBBRegisterPressure(const MachineBasicBlock &MBB);
274 
275   bool registerPressureSetExceedsLimit(unsigned NRegs,
276                                        const TargetRegisterClass *RC,
277                                        const MachineBasicBlock &MBB);
278 };
279 
280 } // end anonymous namespace
281 
282 char MachineSinking::ID = 0;
283 
284 char &llvm::MachineSinkingID = MachineSinking::ID;
285 
286 INITIALIZE_PASS_BEGIN(MachineSinking, DEBUG_TYPE, "Machine code sinking", false,
287                       false)
288 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
289 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfoWrapperPass)
290 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
291 INITIALIZE_PASS_DEPENDENCY(MachineCycleInfoWrapperPass)
292 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
293 INITIALIZE_PASS_END(MachineSinking, DEBUG_TYPE, "Machine code sinking", false,
294                     false)
295 
296 /// Return true if a target defined block prologue instruction interferes
297 /// with a sink candidate.
298 static bool blockPrologueInterferes(const MachineBasicBlock *BB,
299                                     MachineBasicBlock::const_iterator End,
300                                     const MachineInstr &MI,
301                                     const TargetRegisterInfo *TRI,
302                                     const TargetInstrInfo *TII,
303                                     const MachineRegisterInfo *MRI) {
304   for (MachineBasicBlock::const_iterator PI = BB->getFirstNonPHI(); PI != End;
305        ++PI) {
306     // Only check target defined prologue instructions
307     if (!TII->isBasicBlockPrologue(*PI))
308       continue;
309     for (auto &MO : MI.operands()) {
310       if (!MO.isReg())
311         continue;
312       Register Reg = MO.getReg();
313       if (!Reg)
314         continue;
315       if (MO.isUse()) {
316         if (Reg.isPhysical() &&
317             (TII->isIgnorableUse(MO) || (MRI && MRI->isConstantPhysReg(Reg))))
318           continue;
319         if (PI->modifiesRegister(Reg, TRI))
320           return true;
321       } else {
322         if (PI->readsRegister(Reg, TRI))
323           return true;
324         // Check for interference with non-dead defs
325         auto *DefOp = PI->findRegisterDefOperand(Reg, TRI, false, true);
326         if (DefOp && !DefOp->isDead())
327           return true;
328       }
329     }
330   }
331 
332   return false;
333 }
334 
335 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI,
336                                                      MachineBasicBlock *MBB) {
337   if (!MI.isCopy())
338     return false;
339 
340   Register SrcReg = MI.getOperand(1).getReg();
341   Register DstReg = MI.getOperand(0).getReg();
342   if (!SrcReg.isVirtual() || !DstReg.isVirtual() ||
343       !MRI->hasOneNonDBGUse(SrcReg))
344     return false;
345 
346   const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
347   const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
348   if (SRC != DRC)
349     return false;
350 
351   MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
352   if (DefMI->isCopyLike())
353     return false;
354   LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
355   LLVM_DEBUG(dbgs() << "*** to: " << MI);
356   MRI->replaceRegWith(DstReg, SrcReg);
357   MI.eraseFromParent();
358 
359   // Conservatively, clear any kill flags, since it's possible that they are no
360   // longer correct.
361   MRI->clearKillFlags(SrcReg);
362 
363   ++NumCoalesces;
364   return true;
365 }
366 
367 bool MachineSinking::PerformSinkAndFold(MachineInstr &MI,
368                                         MachineBasicBlock *MBB) {
369   if (MI.isCopy() || MI.mayLoadOrStore() ||
370       MI.getOpcode() == TargetOpcode::REG_SEQUENCE)
371     return false;
372 
373   // Don't sink instructions that the target prefers not to sink.
374   if (!TII->shouldSink(MI))
375     return false;
376 
377   // Check if it's safe to move the instruction.
378   bool SawStore = true;
379   if (!MI.isSafeToMove(SawStore))
380     return false;
381 
382   // Convergent operations may not be made control-dependent on additional
383   // values.
384   if (MI.isConvergent())
385     return false;
386 
387   // Don't sink defs/uses of hard registers or if the instruction defines more
388   // than one register.
389   // Don't sink more than two register uses - it'll cover most of the cases and
390   // greatly simplifies the register pressure checks.
391   Register DefReg;
392   Register UsedRegA, UsedRegB;
393   for (const MachineOperand &MO : MI.operands()) {
394     if (MO.isImm() || MO.isRegMask() || MO.isRegLiveOut() || MO.isMetadata() ||
395         MO.isMCSymbol() || MO.isDbgInstrRef() || MO.isCFIIndex() ||
396         MO.isIntrinsicID() || MO.isPredicate() || MO.isShuffleMask())
397       continue;
398     if (!MO.isReg())
399       return false;
400 
401     Register Reg = MO.getReg();
402     if (Reg == 0)
403       continue;
404 
405     if (Reg.isVirtual()) {
406       if (MO.isDef()) {
407         if (DefReg)
408           return false;
409         DefReg = Reg;
410         continue;
411       }
412 
413       if (UsedRegA == 0)
414         UsedRegA = Reg;
415       else if (UsedRegB == 0)
416         UsedRegB = Reg;
417       else
418         return false;
419       continue;
420     }
421 
422     if (Reg.isPhysical() && MO.isUse() &&
423         (MRI->isConstantPhysReg(Reg) || TII->isIgnorableUse(MO)))
424       continue;
425 
426     return false;
427   }
428 
429   // Scan uses of the destination register. Every use, except the last, must be
430   // a copy, with a chain of copies terminating with either a copy into a hard
431   // register, or a load/store instruction where the use is part of the
432   // address (*not* the stored value).
433   using SinkInfo = std::pair<MachineInstr *, ExtAddrMode>;
434   SmallVector<SinkInfo> SinkInto;
435   SmallVector<Register> Worklist;
436 
437   const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
438   const TargetRegisterClass *RCA =
439       UsedRegA == 0 ? nullptr : MRI->getRegClass(UsedRegA);
440   const TargetRegisterClass *RCB =
441       UsedRegB == 0 ? nullptr : MRI->getRegClass(UsedRegB);
442 
443   Worklist.push_back(DefReg);
444   while (!Worklist.empty()) {
445     Register Reg = Worklist.pop_back_val();
446 
447     for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
448       ExtAddrMode MaybeAM;
449       MachineInstr &UseInst = *MO.getParent();
450       if (UseInst.isCopy()) {
451         Register DstReg;
452         if (const MachineOperand &O = UseInst.getOperand(0); O.isReg())
453           DstReg = O.getReg();
454         if (DstReg == 0)
455           return false;
456         if (DstReg.isVirtual()) {
457           Worklist.push_back(DstReg);
458           continue;
459         }
460         // If we are going to replace a copy, the original instruction must be
461         // as cheap as a copy.
462         if (!TII->isAsCheapAsAMove(MI))
463           return false;
464         // The hard register must be in the register class of the original
465         // instruction's destination register.
466         if (!RC->contains(DstReg))
467           return false;
468       } else if (UseInst.mayLoadOrStore()) {
469         ExtAddrMode AM;
470         if (!TII->canFoldIntoAddrMode(UseInst, Reg, MI, AM))
471           return false;
472         MaybeAM = AM;
473       } else {
474         return false;
475       }
476 
477       if (UseInst.getParent() != MI.getParent()) {
478         // If the register class of the register we are replacing is a superset
479         // of any of the register classes of the operands of the materialized
480         // instruction don't consider that live range extended.
481         const TargetRegisterClass *RCS = MRI->getRegClass(Reg);
482         if (RCA && RCA->hasSuperClassEq(RCS))
483           RCA = nullptr;
484         else if (RCB && RCB->hasSuperClassEq(RCS))
485           RCB = nullptr;
486         if (RCA || RCB) {
487           if (RCA == nullptr) {
488             RCA = RCB;
489             RCB = nullptr;
490           }
491 
492           unsigned NRegs = !!RCA + !!RCB;
493           if (RCA == RCB)
494             RCB = nullptr;
495 
496           // Check we don't exceed register pressure at the destination.
497           const MachineBasicBlock &MBB = *UseInst.getParent();
498           if (RCB == nullptr) {
499             if (registerPressureSetExceedsLimit(NRegs, RCA, MBB))
500               return false;
501           } else if (registerPressureSetExceedsLimit(1, RCA, MBB) ||
502                      registerPressureSetExceedsLimit(1, RCB, MBB)) {
503             return false;
504           }
505         }
506       }
507 
508       SinkInto.emplace_back(&UseInst, MaybeAM);
509     }
510   }
511 
512   if (SinkInto.empty())
513     return false;
514 
515   // Now we know we can fold the instruction in all its users.
516   for (auto &[SinkDst, MaybeAM] : SinkInto) {
517     MachineInstr *New = nullptr;
518     LLVM_DEBUG(dbgs() << "Sinking copy of"; MI.dump(); dbgs() << "into";
519                SinkDst->dump());
520     if (SinkDst->isCopy()) {
521       // TODO: After performing the sink-and-fold, the original instruction is
522       // deleted. Its value is still available (in a hard register), so if there
523       // are debug instructions which refer to the (now deleted) virtual
524       // register they could be updated to refer to the hard register, in
525       // principle. However, it's not clear how to do that, moreover in some
526       // cases the debug instructions may need to be replicated proportionally
527       // to the number of the COPY instructions replaced and in some extreme
528       // cases we can end up with quadratic increase in the number of debug
529       // instructions.
530 
531       // Sink a copy of the instruction, replacing a COPY instruction.
532       MachineBasicBlock::iterator InsertPt = SinkDst->getIterator();
533       Register DstReg = SinkDst->getOperand(0).getReg();
534       TII->reMaterialize(*SinkDst->getParent(), InsertPt, DstReg, 0, MI, *TRI);
535       New = &*std::prev(InsertPt);
536       if (!New->getDebugLoc())
537         New->setDebugLoc(SinkDst->getDebugLoc());
538 
539       // The operand registers of the "sunk" instruction have their live range
540       // extended and their kill flags may no longer be correct. Conservatively
541       // clear the kill flags.
542       if (UsedRegA)
543         MRI->clearKillFlags(UsedRegA);
544       if (UsedRegB)
545         MRI->clearKillFlags(UsedRegB);
546     } else {
547       // Fold instruction into the addressing mode of a memory instruction.
548       New = TII->emitLdStWithAddr(*SinkDst, MaybeAM);
549 
550       // The registers of the addressing mode may have their live range extended
551       // and their kill flags may no longer be correct. Conservatively clear the
552       // kill flags.
553       if (Register R = MaybeAM.BaseReg; R.isValid() && R.isVirtual())
554         MRI->clearKillFlags(R);
555       if (Register R = MaybeAM.ScaledReg; R.isValid() && R.isVirtual())
556         MRI->clearKillFlags(R);
557     }
558     LLVM_DEBUG(dbgs() << "yielding"; New->dump());
559     // Clear the StoreInstrCache, since we may invalidate it by erasing.
560     if (SinkDst->mayStore() && !SinkDst->hasOrderedMemoryRef())
561       StoreInstrCache.clear();
562     SinkDst->eraseFromParent();
563   }
564 
565   // Collect operands that need to be cleaned up because the registers no longer
566   // exist (in COPYs and debug instructions). We cannot delete instructions or
567   // clear operands while traversing register uses.
568   SmallVector<MachineOperand *> Cleanup;
569   Worklist.push_back(DefReg);
570   while (!Worklist.empty()) {
571     Register Reg = Worklist.pop_back_val();
572     for (MachineOperand &MO : MRI->use_operands(Reg)) {
573       MachineInstr *U = MO.getParent();
574       assert((U->isCopy() || U->isDebugInstr()) &&
575              "Only debug uses and copies must remain");
576       if (U->isCopy())
577         Worklist.push_back(U->getOperand(0).getReg());
578       Cleanup.push_back(&MO);
579     }
580   }
581 
582   // Delete the dead COPYs and clear operands in debug instructions
583   for (MachineOperand *MO : Cleanup) {
584     MachineInstr *I = MO->getParent();
585     if (I->isCopy()) {
586       I->eraseFromParent();
587     } else {
588       MO->setReg(0);
589       MO->setSubReg(0);
590     }
591   }
592 
593   MI.eraseFromParent();
594   return true;
595 }
596 
597 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
598 /// occur in blocks dominated by the specified block. If any use is in the
599 /// definition block, then return false since it is never legal to move def
600 /// after uses.
601 bool MachineSinking::AllUsesDominatedByBlock(Register Reg,
602                                              MachineBasicBlock *MBB,
603                                              MachineBasicBlock *DefMBB,
604                                              bool &BreakPHIEdge,
605                                              bool &LocalUse) const {
606   assert(Reg.isVirtual() && "Only makes sense for vregs");
607 
608   // Ignore debug uses because debug info doesn't affect the code.
609   if (MRI->use_nodbg_empty(Reg))
610     return true;
611 
612   // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
613   // into and they are all PHI nodes. In this case, machine-sink must break
614   // the critical edge first. e.g.
615   //
616   // %bb.1:
617   //   Predecessors according to CFG: %bb.0
618   //     ...
619   //     %def = DEC64_32r %x, implicit-def dead %eflags
620   //     ...
621   //     JE_4 <%bb.37>, implicit %eflags
622   //   Successors according to CFG: %bb.37 %bb.2
623   //
624   // %bb.2:
625   //     %p = PHI %y, %bb.0, %def, %bb.1
626   if (all_of(MRI->use_nodbg_operands(Reg), [&](MachineOperand &MO) {
627         MachineInstr *UseInst = MO.getParent();
628         unsigned OpNo = MO.getOperandNo();
629         MachineBasicBlock *UseBlock = UseInst->getParent();
630         return UseBlock == MBB && UseInst->isPHI() &&
631                UseInst->getOperand(OpNo + 1).getMBB() == DefMBB;
632       })) {
633     BreakPHIEdge = true;
634     return true;
635   }
636 
637   for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
638     // Determine the block of the use.
639     MachineInstr *UseInst = MO.getParent();
640     unsigned OpNo = &MO - &UseInst->getOperand(0);
641     MachineBasicBlock *UseBlock = UseInst->getParent();
642     if (UseInst->isPHI()) {
643       // PHI nodes use the operand in the predecessor block, not the block with
644       // the PHI.
645       UseBlock = UseInst->getOperand(OpNo + 1).getMBB();
646     } else if (UseBlock == DefMBB) {
647       LocalUse = true;
648       return false;
649     }
650 
651     // Check that it dominates.
652     if (!DT->dominates(MBB, UseBlock))
653       return false;
654   }
655 
656   return true;
657 }
658 
659 /// Return true if this machine instruction loads from global offset table or
660 /// constant pool.
661 static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
662   assert(MI.mayLoad() && "Expected MI that loads!");
663 
664   // If we lost memory operands, conservatively assume that the instruction
665   // reads from everything..
666   if (MI.memoperands_empty())
667     return true;
668 
669   for (MachineMemOperand *MemOp : MI.memoperands())
670     if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
671       if (PSV->isGOT() || PSV->isConstantPool())
672         return true;
673 
674   return false;
675 }
676 
677 void MachineSinking::FindCycleSinkCandidates(
678     MachineCycle *Cycle, MachineBasicBlock *BB,
679     SmallVectorImpl<MachineInstr *> &Candidates) {
680   for (auto &MI : *BB) {
681     LLVM_DEBUG(dbgs() << "CycleSink: Analysing candidate: " << MI);
682     if (!TII->shouldSink(MI)) {
683       LLVM_DEBUG(dbgs() << "CycleSink: Instruction not a candidate for this "
684                            "target\n");
685       continue;
686     }
687     if (!isCycleInvariant(Cycle, MI)) {
688       LLVM_DEBUG(dbgs() << "CycleSink: Instruction is not cycle invariant\n");
689       continue;
690     }
691     bool DontMoveAcrossStore = true;
692     if (!MI.isSafeToMove(DontMoveAcrossStore)) {
693       LLVM_DEBUG(dbgs() << "CycleSink: Instruction not safe to move.\n");
694       continue;
695     }
696     if (MI.mayLoad() && !mayLoadFromGOTOrConstantPool(MI)) {
697       LLVM_DEBUG(dbgs() << "CycleSink: Dont sink GOT or constant pool loads\n");
698       continue;
699     }
700     if (MI.isConvergent())
701       continue;
702 
703     const MachineOperand &MO = MI.getOperand(0);
704     if (!MO.isReg() || !MO.getReg() || !MO.isDef())
705       continue;
706     if (!MRI->hasOneDef(MO.getReg()))
707       continue;
708 
709     LLVM_DEBUG(dbgs() << "CycleSink: Instruction added as candidate.\n");
710     Candidates.push_back(&MI);
711   }
712 }
713 
714 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
715   if (skipFunction(MF.getFunction()))
716     return false;
717 
718   LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n");
719 
720   STI = &MF.getSubtarget();
721   TII = STI->getInstrInfo();
722   TRI = STI->getRegisterInfo();
723   MRI = &MF.getRegInfo();
724   DT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
725   PDT = &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
726   CI = &getAnalysis<MachineCycleInfoWrapperPass>().getCycleInfo();
727   PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
728   MBFI = UseBlockFreqInfo
729              ? &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI()
730              : nullptr;
731   MBPI = &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
732   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
733   RegClassInfo.runOnMachineFunction(MF);
734   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
735   EnableSinkAndFold = PassConfig->getEnableSinkAndFold();
736 
737   bool EverMadeChange = false;
738 
739   while (true) {
740     bool MadeChange = false;
741 
742     // Process all basic blocks.
743     CEBCandidates.clear();
744     CEMergeCandidates.clear();
745     ToSplit.clear();
746     for (auto &MBB : MF)
747       MadeChange |= ProcessBlock(MBB);
748 
749     // If we have anything we marked as toSplit, split it now.
750     for (const auto &Pair : ToSplit) {
751       auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this);
752       if (NewSucc != nullptr) {
753         LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "
754                           << printMBBReference(*Pair.first) << " -- "
755                           << printMBBReference(*NewSucc) << " -- "
756                           << printMBBReference(*Pair.second) << '\n');
757         if (MBFI)
758           MBFI->onEdgeSplit(*Pair.first, *NewSucc, *MBPI);
759 
760         MadeChange = true;
761         ++NumSplit;
762         CI->splitCriticalEdge(Pair.first, Pair.second, NewSucc);
763       } else
764         LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n");
765     }
766     // If this iteration over the code changed anything, keep iterating.
767     if (!MadeChange)
768       break;
769     EverMadeChange = true;
770   }
771 
772   if (SinkInstsIntoCycle) {
773     SmallVector<MachineCycle *, 8> Cycles(CI->toplevel_cycles());
774     for (auto *Cycle : Cycles) {
775       MachineBasicBlock *Preheader = Cycle->getCyclePreheader();
776       if (!Preheader) {
777         LLVM_DEBUG(dbgs() << "CycleSink: Can't find preheader\n");
778         continue;
779       }
780       SmallVector<MachineInstr *, 8> Candidates;
781       FindCycleSinkCandidates(Cycle, Preheader, Candidates);
782 
783       // Walk the candidates in reverse order so that we start with the use
784       // of a def-use chain, if there is any.
785       // TODO: Sort the candidates using a cost-model.
786       unsigned i = 0;
787       for (MachineInstr *I : llvm::reverse(Candidates)) {
788         if (i++ == SinkIntoCycleLimit) {
789           LLVM_DEBUG(dbgs() << "CycleSink:   Limit reached of instructions to "
790                                "be analysed.");
791           break;
792         }
793 
794         if (!SinkIntoCycle(Cycle, *I))
795           break;
796         EverMadeChange = true;
797         ++NumCycleSunk;
798       }
799     }
800   }
801 
802   HasStoreCache.clear();
803   StoreInstrCache.clear();
804 
805   // Now clear any kill flags for recorded registers.
806   for (auto I : RegsToClearKillFlags)
807     MRI->clearKillFlags(I);
808   RegsToClearKillFlags.clear();
809 
810   return EverMadeChange;
811 }
812 
813 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
814   if ((!EnableSinkAndFold && MBB.succ_size() <= 1) || MBB.empty())
815     return false;
816 
817   // Don't bother sinking code out of unreachable blocks. In addition to being
818   // unprofitable, it can also lead to infinite looping, because in an
819   // unreachable cycle there may be nowhere to stop.
820   if (!DT->isReachableFromEntry(&MBB))
821     return false;
822 
823   bool MadeChange = false;
824 
825   // Cache all successors, sorted by frequency info and cycle depth.
826   AllSuccsCache AllSuccessors;
827 
828   // Walk the basic block bottom-up.  Remember if we saw a store.
829   MachineBasicBlock::iterator I = MBB.end();
830   --I;
831   bool ProcessedBegin, SawStore = false;
832   do {
833     MachineInstr &MI = *I; // The instruction to sink.
834 
835     // Predecrement I (if it's not begin) so that it isn't invalidated by
836     // sinking.
837     ProcessedBegin = I == MBB.begin();
838     if (!ProcessedBegin)
839       --I;
840 
841     if (MI.isDebugOrPseudoInstr() || MI.isFakeUse()) {
842       if (MI.isDebugValue())
843         ProcessDbgInst(MI);
844       continue;
845     }
846 
847     if (EnableSinkAndFold && PerformSinkAndFold(MI, &MBB)) {
848       MadeChange = true;
849       continue;
850     }
851 
852     // Can't sink anything out of a block that has less than two successors.
853     if (MBB.succ_size() <= 1)
854       continue;
855 
856     if (PerformTrivialForwardCoalescing(MI, &MBB)) {
857       MadeChange = true;
858       continue;
859     }
860 
861     if (SinkInstruction(MI, SawStore, AllSuccessors)) {
862       ++NumSunk;
863       MadeChange = true;
864     }
865 
866     // If we just processed the first instruction in the block, we're done.
867   } while (!ProcessedBegin);
868 
869   SeenDbgUsers.clear();
870   SeenDbgVars.clear();
871   // recalculate the bb register pressure after sinking one BB.
872   CachedRegisterPressure.clear();
873   return MadeChange;
874 }
875 
876 void MachineSinking::ProcessDbgInst(MachineInstr &MI) {
877   // When we see DBG_VALUEs for registers, record any vreg it reads, so that
878   // we know what to sink if the vreg def sinks.
879   assert(MI.isDebugValue() && "Expected DBG_VALUE for processing");
880 
881   DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
882                     MI.getDebugLoc()->getInlinedAt());
883   bool SeenBefore = SeenDbgVars.contains(Var);
884 
885   for (MachineOperand &MO : MI.debug_operands()) {
886     if (MO.isReg() && MO.getReg().isVirtual())
887       SeenDbgUsers[MO.getReg()].push_back(SeenDbgUser(&MI, SeenBefore));
888   }
889 
890   // Record the variable for any DBG_VALUE, to avoid re-ordering any of them.
891   SeenDbgVars.insert(Var);
892 }
893 
894 bool MachineSinking::isWorthBreakingCriticalEdge(
895     MachineInstr &MI, MachineBasicBlock *From, MachineBasicBlock *To,
896     MachineBasicBlock *&DeferredFromBlock) {
897   // FIXME: Need much better heuristics.
898 
899   // If the pass has already considered breaking this edge (during this pass
900   // through the function), then let's go ahead and break it. This means
901   // sinking multiple "cheap" instructions into the same block.
902   if (!CEBCandidates.insert(std::make_pair(From, To)).second)
903     return true;
904 
905   if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI))
906     return true;
907 
908   // Check and record the register and the destination block we want to sink
909   // into. Note that we want to do the following before the next check on branch
910   // probability. Because we want to record the initial candidate even if it's
911   // on hot edge, so that other candidates that might not on hot edges can be
912   // sinked as well.
913   for (const auto &MO : MI.all_defs()) {
914     Register Reg = MO.getReg();
915     if (!Reg)
916       continue;
917     Register SrcReg = Reg.isVirtual() ? TRI->lookThruCopyLike(Reg, MRI) : Reg;
918     auto Key = std::make_pair(SrcReg, To);
919     auto Res = CEMergeCandidates.try_emplace(Key, From);
920     // We wanted to sink the same register into the same block, consider it to
921     // be profitable.
922     if (!Res.second) {
923       // Return the source block that was previously held off.
924       DeferredFromBlock = Res.first->second;
925       return true;
926     }
927   }
928 
929   if (From->isSuccessor(To) &&
930       MBPI->getEdgeProbability(From, To) <=
931           BranchProbability(SplitEdgeProbabilityThreshold, 100))
932     return true;
933 
934   // MI is cheap, we probably don't want to break the critical edge for it.
935   // However, if this would allow some definitions of its source operands
936   // to be sunk then it's probably worth it.
937   for (const MachineOperand &MO : MI.all_uses()) {
938     Register Reg = MO.getReg();
939     if (Reg == 0)
940       continue;
941 
942     // We don't move live definitions of physical registers,
943     // so sinking their uses won't enable any opportunities.
944     if (Reg.isPhysical())
945       continue;
946 
947     // If this instruction is the only user of a virtual register,
948     // check if breaking the edge will enable sinking
949     // both this instruction and the defining instruction.
950     if (MRI->hasOneNonDBGUse(Reg)) {
951       // If the definition resides in same MBB,
952       // claim it's likely we can sink these together.
953       // If definition resides elsewhere, we aren't
954       // blocking it from being sunk so don't break the edge.
955       MachineInstr *DefMI = MRI->getVRegDef(Reg);
956       if (DefMI->getParent() == MI.getParent())
957         return true;
958     }
959   }
960 
961   // Let the target decide if it's worth breaking this
962   // critical edge for a "cheap" instruction.
963   return TII->shouldBreakCriticalEdgeToSink(MI);
964 }
965 
966 bool MachineSinking::isLegalToBreakCriticalEdge(MachineInstr &MI,
967                                                 MachineBasicBlock *FromBB,
968                                                 MachineBasicBlock *ToBB,
969                                                 bool BreakPHIEdge) {
970   // Avoid breaking back edge. From == To means backedge for single BB cycle.
971   if (!SplitEdges || FromBB == ToBB || !FromBB->isSuccessor(ToBB))
972     return false;
973 
974   MachineCycle *FromCycle = CI->getCycle(FromBB);
975   MachineCycle *ToCycle = CI->getCycle(ToBB);
976 
977   // Check for backedges of more "complex" cycles.
978   if (FromCycle == ToCycle && FromCycle &&
979       (!FromCycle->isReducible() || FromCycle->getHeader() == ToBB))
980     return false;
981 
982   // It's not always legal to break critical edges and sink the computation
983   // to the edge.
984   //
985   // %bb.1:
986   // v1024
987   // Beq %bb.3
988   // <fallthrough>
989   // %bb.2:
990   // ... no uses of v1024
991   // <fallthrough>
992   // %bb.3:
993   // ...
994   //       = v1024
995   //
996   // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted:
997   //
998   // %bb.1:
999   // ...
1000   // Bne %bb.2
1001   // %bb.4:
1002   // v1024 =
1003   // B %bb.3
1004   // %bb.2:
1005   // ... no uses of v1024
1006   // <fallthrough>
1007   // %bb.3:
1008   // ...
1009   //       = v1024
1010   //
1011   // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3
1012   // flow. We need to ensure the new basic block where the computation is
1013   // sunk to dominates all the uses.
1014   // It's only legal to break critical edge and sink the computation to the
1015   // new block if all the predecessors of "To", except for "From", are
1016   // not dominated by "From". Given SSA property, this means these
1017   // predecessors are dominated by "To".
1018   //
1019   // There is no need to do this check if all the uses are PHI nodes. PHI
1020   // sources are only defined on the specific predecessor edges.
1021   if (!BreakPHIEdge) {
1022     for (MachineBasicBlock *Pred : ToBB->predecessors())
1023       if (Pred != FromBB && !DT->dominates(ToBB, Pred))
1024         return false;
1025   }
1026 
1027   return true;
1028 }
1029 
1030 bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
1031                                                MachineBasicBlock *FromBB,
1032                                                MachineBasicBlock *ToBB,
1033                                                bool BreakPHIEdge) {
1034   bool Status = false;
1035   MachineBasicBlock *DeferredFromBB = nullptr;
1036   if (isWorthBreakingCriticalEdge(MI, FromBB, ToBB, DeferredFromBB)) {
1037     // If there is a DeferredFromBB, we consider FromBB only if _both_
1038     // of them are legal to split.
1039     if ((!DeferredFromBB ||
1040          ToSplit.count(std::make_pair(DeferredFromBB, ToBB)) ||
1041          isLegalToBreakCriticalEdge(MI, DeferredFromBB, ToBB, BreakPHIEdge)) &&
1042         isLegalToBreakCriticalEdge(MI, FromBB, ToBB, BreakPHIEdge)) {
1043       ToSplit.insert(std::make_pair(FromBB, ToBB));
1044       if (DeferredFromBB)
1045         ToSplit.insert(std::make_pair(DeferredFromBB, ToBB));
1046       Status = true;
1047     }
1048   }
1049 
1050   return Status;
1051 }
1052 
1053 std::vector<unsigned> &
1054 MachineSinking::getBBRegisterPressure(const MachineBasicBlock &MBB) {
1055   // Currently to save compiling time, MBB's register pressure will not change
1056   // in one ProcessBlock iteration because of CachedRegisterPressure. but MBB's
1057   // register pressure is changed after sinking any instructions into it.
1058   // FIXME: need a accurate and cheap register pressure estiminate model here.
1059   auto RP = CachedRegisterPressure.find(&MBB);
1060   if (RP != CachedRegisterPressure.end())
1061     return RP->second;
1062 
1063   RegionPressure Pressure;
1064   RegPressureTracker RPTracker(Pressure);
1065 
1066   // Initialize the register pressure tracker.
1067   RPTracker.init(MBB.getParent(), &RegClassInfo, nullptr, &MBB, MBB.end(),
1068                  /*TrackLaneMasks*/ false, /*TrackUntiedDefs=*/true);
1069 
1070   for (MachineBasicBlock::const_iterator MII = MBB.instr_end(),
1071                                          MIE = MBB.instr_begin();
1072        MII != MIE; --MII) {
1073     const MachineInstr &MI = *std::prev(MII);
1074     if (MI.isDebugInstr() || MI.isPseudoProbe())
1075       continue;
1076     RegisterOperands RegOpers;
1077     RegOpers.collect(MI, *TRI, *MRI, false, false);
1078     RPTracker.recedeSkipDebugValues();
1079     assert(&*RPTracker.getPos() == &MI && "RPTracker sync error!");
1080     RPTracker.recede(RegOpers);
1081   }
1082 
1083   RPTracker.closeRegion();
1084   auto It = CachedRegisterPressure.insert(
1085       std::make_pair(&MBB, RPTracker.getPressure().MaxSetPressure));
1086   return It.first->second;
1087 }
1088 
1089 bool MachineSinking::registerPressureSetExceedsLimit(
1090     unsigned NRegs, const TargetRegisterClass *RC,
1091     const MachineBasicBlock &MBB) {
1092   unsigned Weight = NRegs * TRI->getRegClassWeight(RC).RegWeight;
1093   const int *PS = TRI->getRegClassPressureSets(RC);
1094   std::vector<unsigned> BBRegisterPressure = getBBRegisterPressure(MBB);
1095   for (; *PS != -1; PS++)
1096     if (Weight + BBRegisterPressure[*PS] >=
1097         TRI->getRegPressureSetLimit(*MBB.getParent(), *PS))
1098       return true;
1099   return false;
1100 }
1101 
1102 /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
1103 bool MachineSinking::isProfitableToSinkTo(Register Reg, MachineInstr &MI,
1104                                           MachineBasicBlock *MBB,
1105                                           MachineBasicBlock *SuccToSinkTo,
1106                                           AllSuccsCache &AllSuccessors) {
1107   assert(SuccToSinkTo && "Invalid SinkTo Candidate BB");
1108 
1109   if (MBB == SuccToSinkTo)
1110     return false;
1111 
1112   // It is profitable if SuccToSinkTo does not post dominate current block.
1113   if (!PDT->dominates(SuccToSinkTo, MBB))
1114     return true;
1115 
1116   // It is profitable to sink an instruction from a deeper cycle to a shallower
1117   // cycle, even if the latter post-dominates the former (PR21115).
1118   if (CI->getCycleDepth(MBB) > CI->getCycleDepth(SuccToSinkTo))
1119     return true;
1120 
1121   // Check if only use in post dominated block is PHI instruction.
1122   bool NonPHIUse = false;
1123   for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
1124     MachineBasicBlock *UseBlock = UseInst.getParent();
1125     if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
1126       NonPHIUse = true;
1127   }
1128   if (!NonPHIUse)
1129     return true;
1130 
1131   // If SuccToSinkTo post dominates then also it may be profitable if MI
1132   // can further profitably sinked into another block in next round.
1133   bool BreakPHIEdge = false;
1134   // FIXME - If finding successor is compile time expensive then cache results.
1135   if (MachineBasicBlock *MBB2 =
1136           FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
1137     return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
1138 
1139   MachineCycle *MCycle = CI->getCycle(MBB);
1140 
1141   // If the instruction is not inside a cycle, it is not profitable to sink MI
1142   // to a post dominate block SuccToSinkTo.
1143   if (!MCycle)
1144     return false;
1145 
1146   // If this instruction is inside a Cycle and sinking this instruction can make
1147   // more registers live range shorten, it is still prifitable.
1148   for (const MachineOperand &MO : MI.operands()) {
1149     // Ignore non-register operands.
1150     if (!MO.isReg())
1151       continue;
1152     Register Reg = MO.getReg();
1153     if (Reg == 0)
1154       continue;
1155 
1156     if (Reg.isPhysical()) {
1157       // Don't handle non-constant and non-ignorable physical register uses.
1158       if (MO.isUse() && !MRI->isConstantPhysReg(Reg) &&
1159           !TII->isIgnorableUse(MO))
1160         return false;
1161       continue;
1162     }
1163 
1164     // Users for the defs are all dominated by SuccToSinkTo.
1165     if (MO.isDef()) {
1166       // This def register's live range is shortened after sinking.
1167       bool LocalUse = false;
1168       if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, BreakPHIEdge,
1169                                    LocalUse))
1170         return false;
1171     } else {
1172       MachineInstr *DefMI = MRI->getVRegDef(Reg);
1173       if (!DefMI)
1174         continue;
1175       MachineCycle *Cycle = CI->getCycle(DefMI->getParent());
1176       // DefMI is defined outside of cycle. There should be no live range
1177       // impact for this operand. Defination outside of cycle means:
1178       // 1: defination is outside of cycle.
1179       // 2: defination is in this cycle, but it is a PHI in the cycle header.
1180       if (Cycle != MCycle || (DefMI->isPHI() && Cycle && Cycle->isReducible() &&
1181                               Cycle->getHeader() == DefMI->getParent()))
1182         continue;
1183       // The DefMI is defined inside the cycle.
1184       // If sinking this operand makes some register pressure set exceed limit,
1185       // it is not profitable.
1186       if (registerPressureSetExceedsLimit(1, MRI->getRegClass(Reg),
1187                                           *SuccToSinkTo)) {
1188         LLVM_DEBUG(dbgs() << "register pressure exceed limit, not profitable.");
1189         return false;
1190       }
1191     }
1192   }
1193 
1194   // If MI is in cycle and all its operands are alive across the whole cycle or
1195   // if no operand sinking make register pressure set exceed limit, it is
1196   // profitable to sink MI.
1197   return true;
1198 }
1199 
1200 /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
1201 /// computing it if it was not already cached.
1202 SmallVector<MachineBasicBlock *, 4> &
1203 MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
1204                                        AllSuccsCache &AllSuccessors) const {
1205   // Do we have the sorted successors in cache ?
1206   auto Succs = AllSuccessors.find(MBB);
1207   if (Succs != AllSuccessors.end())
1208     return Succs->second;
1209 
1210   SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->successors());
1211 
1212   // Handle cases where sinking can happen but where the sink point isn't a
1213   // successor. For example:
1214   //
1215   //   x = computation
1216   //   if () {} else {}
1217   //   use x
1218   //
1219   for (MachineDomTreeNode *DTChild : DT->getNode(MBB)->children()) {
1220     // DomTree children of MBB that have MBB as immediate dominator are added.
1221     if (DTChild->getIDom()->getBlock() == MI.getParent() &&
1222         // Skip MBBs already added to the AllSuccs vector above.
1223         !MBB->isSuccessor(DTChild->getBlock()))
1224       AllSuccs.push_back(DTChild->getBlock());
1225   }
1226 
1227   // Sort Successors according to their cycle depth or block frequency info.
1228   llvm::stable_sort(
1229       AllSuccs, [&](const MachineBasicBlock *L, const MachineBasicBlock *R) {
1230         uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
1231         uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
1232         if (llvm::shouldOptimizeForSize(MBB, PSI, MBFI) ||
1233             (!LHSFreq && !RHSFreq))
1234           return CI->getCycleDepth(L) < CI->getCycleDepth(R);
1235         return LHSFreq < RHSFreq;
1236       });
1237 
1238   auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
1239 
1240   return it.first->second;
1241 }
1242 
1243 /// FindSuccToSinkTo - Find a successor to sink this instruction to.
1244 MachineBasicBlock *
1245 MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
1246                                  bool &BreakPHIEdge,
1247                                  AllSuccsCache &AllSuccessors) {
1248   assert(MBB && "Invalid MachineBasicBlock!");
1249 
1250   // loop over all the operands of the specified instruction.  If there is
1251   // anything we can't handle, bail out.
1252 
1253   // SuccToSinkTo - This is the successor to sink this instruction to, once we
1254   // decide.
1255   MachineBasicBlock *SuccToSinkTo = nullptr;
1256   for (const MachineOperand &MO : MI.operands()) {
1257     if (!MO.isReg())
1258       continue; // Ignore non-register operands.
1259 
1260     Register Reg = MO.getReg();
1261     if (Reg == 0)
1262       continue;
1263 
1264     if (Reg.isPhysical()) {
1265       if (MO.isUse()) {
1266         // If the physreg has no defs anywhere, it's just an ambient register
1267         // and we can freely move its uses. Alternatively, if it's allocatable,
1268         // it could get allocated to something with a def during allocation.
1269         if (!MRI->isConstantPhysReg(Reg) && !TII->isIgnorableUse(MO))
1270           return nullptr;
1271       } else if (!MO.isDead()) {
1272         // A def that isn't dead. We can't move it.
1273         return nullptr;
1274       }
1275     } else {
1276       // Virtual register uses are always safe to sink.
1277       if (MO.isUse())
1278         continue;
1279 
1280       // If it's not safe to move defs of the register class, then abort.
1281       if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
1282         return nullptr;
1283 
1284       // Virtual register defs can only be sunk if all their uses are in blocks
1285       // dominated by one of the successors.
1286       if (SuccToSinkTo) {
1287         // If a previous operand picked a block to sink to, then this operand
1288         // must be sinkable to the same block.
1289         bool LocalUse = false;
1290         if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, BreakPHIEdge,
1291                                      LocalUse))
1292           return nullptr;
1293 
1294         continue;
1295       }
1296 
1297       // Otherwise, we should look at all the successors and decide which one
1298       // we should sink to. If we have reliable block frequency information
1299       // (frequency != 0) available, give successors with smaller frequencies
1300       // higher priority, otherwise prioritize smaller cycle depths.
1301       for (MachineBasicBlock *SuccBlock :
1302            GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
1303         bool LocalUse = false;
1304         if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB, BreakPHIEdge,
1305                                     LocalUse)) {
1306           SuccToSinkTo = SuccBlock;
1307           break;
1308         }
1309         if (LocalUse)
1310           // Def is used locally, it's never safe to move this def.
1311           return nullptr;
1312       }
1313 
1314       // If we couldn't find a block to sink to, ignore this instruction.
1315       if (!SuccToSinkTo)
1316         return nullptr;
1317       if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
1318         return nullptr;
1319     }
1320   }
1321 
1322   // It is not possible to sink an instruction into its own block.  This can
1323   // happen with cycles.
1324   if (MBB == SuccToSinkTo)
1325     return nullptr;
1326 
1327   // It's not safe to sink instructions to EH landing pad. Control flow into
1328   // landing pad is implicitly defined.
1329   if (SuccToSinkTo && SuccToSinkTo->isEHPad())
1330     return nullptr;
1331 
1332   // It ought to be okay to sink instructions into an INLINEASM_BR target, but
1333   // only if we make sure that MI occurs _before_ an INLINEASM_BR instruction in
1334   // the source block (which this code does not yet do). So for now, forbid
1335   // doing so.
1336   if (SuccToSinkTo && SuccToSinkTo->isInlineAsmBrIndirectTarget())
1337     return nullptr;
1338 
1339   if (SuccToSinkTo && !TII->isSafeToSink(MI, SuccToSinkTo, CI))
1340     return nullptr;
1341 
1342   return SuccToSinkTo;
1343 }
1344 
1345 /// Return true if MI is likely to be usable as a memory operation by the
1346 /// implicit null check optimization.
1347 ///
1348 /// This is a "best effort" heuristic, and should not be relied upon for
1349 /// correctness.  This returning true does not guarantee that the implicit null
1350 /// check optimization is legal over MI, and this returning false does not
1351 /// guarantee MI cannot possibly be used to do a null check.
1352 static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI,
1353                                              const TargetInstrInfo *TII,
1354                                              const TargetRegisterInfo *TRI) {
1355   using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
1356 
1357   auto *MBB = MI.getParent();
1358   if (MBB->pred_size() != 1)
1359     return false;
1360 
1361   auto *PredMBB = *MBB->pred_begin();
1362   auto *PredBB = PredMBB->getBasicBlock();
1363 
1364   // Frontends that don't use implicit null checks have no reason to emit
1365   // branches with make.implicit metadata, and this function should always
1366   // return false for them.
1367   if (!PredBB ||
1368       !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
1369     return false;
1370 
1371   const MachineOperand *BaseOp;
1372   int64_t Offset;
1373   bool OffsetIsScalable;
1374   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
1375     return false;
1376 
1377   if (!BaseOp->isReg())
1378     return false;
1379 
1380   if (!(MI.mayLoad() && !MI.isPredicable()))
1381     return false;
1382 
1383   MachineBranchPredicate MBP;
1384   if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
1385     return false;
1386 
1387   return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
1388          (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
1389           MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
1390          MBP.LHS.getReg() == BaseOp->getReg();
1391 }
1392 
1393 /// If the sunk instruction is a copy, try to forward the copy instead of
1394 /// leaving an 'undef' DBG_VALUE in the original location. Don't do this if
1395 /// there's any subregister weirdness involved. Returns true if copy
1396 /// propagation occurred.
1397 static bool attemptDebugCopyProp(MachineInstr &SinkInst, MachineInstr &DbgMI,
1398                                  Register Reg) {
1399   const MachineRegisterInfo &MRI = SinkInst.getMF()->getRegInfo();
1400   const TargetInstrInfo &TII = *SinkInst.getMF()->getSubtarget().getInstrInfo();
1401 
1402   // Copy DBG_VALUE operand and set the original to undef. We then check to
1403   // see whether this is something that can be copy-forwarded. If it isn't,
1404   // continue around the loop.
1405 
1406   const MachineOperand *SrcMO = nullptr, *DstMO = nullptr;
1407   auto CopyOperands = TII.isCopyInstr(SinkInst);
1408   if (!CopyOperands)
1409     return false;
1410   SrcMO = CopyOperands->Source;
1411   DstMO = CopyOperands->Destination;
1412 
1413   // Check validity of forwarding this copy.
1414   bool PostRA = MRI.getNumVirtRegs() == 0;
1415 
1416   // Trying to forward between physical and virtual registers is too hard.
1417   if (Reg.isVirtual() != SrcMO->getReg().isVirtual())
1418     return false;
1419 
1420   // Only try virtual register copy-forwarding before regalloc, and physical
1421   // register copy-forwarding after regalloc.
1422   bool arePhysRegs = !Reg.isVirtual();
1423   if (arePhysRegs != PostRA)
1424     return false;
1425 
1426   // Pre-regalloc, only forward if all subregisters agree (or there are no
1427   // subregs at all). More analysis might recover some forwardable copies.
1428   if (!PostRA)
1429     for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg))
1430       if (DbgMO.getSubReg() != SrcMO->getSubReg() ||
1431           DbgMO.getSubReg() != DstMO->getSubReg())
1432         return false;
1433 
1434   // Post-regalloc, we may be sinking a DBG_VALUE of a sub or super-register
1435   // of this copy. Only forward the copy if the DBG_VALUE operand exactly
1436   // matches the copy destination.
1437   if (PostRA && Reg != DstMO->getReg())
1438     return false;
1439 
1440   for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg)) {
1441     DbgMO.setReg(SrcMO->getReg());
1442     DbgMO.setSubReg(SrcMO->getSubReg());
1443   }
1444   return true;
1445 }
1446 
1447 using MIRegs = std::pair<MachineInstr *, SmallVector<unsigned, 2>>;
1448 /// Sink an instruction and its associated debug instructions.
1449 static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo,
1450                         MachineBasicBlock::iterator InsertPos,
1451                         ArrayRef<MIRegs> DbgValuesToSink) {
1452   // If we cannot find a location to use (merge with), then we erase the debug
1453   // location to prevent debug-info driven tools from potentially reporting
1454   // wrong location information.
1455   if (!SuccToSinkTo.empty() && InsertPos != SuccToSinkTo.end())
1456     MI.setDebugLoc(DILocation::getMergedLocation(MI.getDebugLoc(),
1457                                                  InsertPos->getDebugLoc()));
1458   else
1459     MI.setDebugLoc(DebugLoc());
1460 
1461   // Move the instruction.
1462   MachineBasicBlock *ParentBlock = MI.getParent();
1463   SuccToSinkTo.splice(InsertPos, ParentBlock, MI,
1464                       ++MachineBasicBlock::iterator(MI));
1465 
1466   // Sink a copy of debug users to the insert position. Mark the original
1467   // DBG_VALUE location as 'undef', indicating that any earlier variable
1468   // location should be terminated as we've optimised away the value at this
1469   // point.
1470   for (const auto &DbgValueToSink : DbgValuesToSink) {
1471     MachineInstr *DbgMI = DbgValueToSink.first;
1472     MachineInstr *NewDbgMI = DbgMI->getMF()->CloneMachineInstr(DbgMI);
1473     SuccToSinkTo.insert(InsertPos, NewDbgMI);
1474 
1475     bool PropagatedAllSunkOps = true;
1476     for (unsigned Reg : DbgValueToSink.second) {
1477       if (DbgMI->hasDebugOperandForReg(Reg)) {
1478         if (!attemptDebugCopyProp(MI, *DbgMI, Reg)) {
1479           PropagatedAllSunkOps = false;
1480           break;
1481         }
1482       }
1483     }
1484     if (!PropagatedAllSunkOps)
1485       DbgMI->setDebugValueUndef();
1486   }
1487 }
1488 
1489 /// hasStoreBetween - check if there is store betweeen straight line blocks From
1490 /// and To.
1491 bool MachineSinking::hasStoreBetween(MachineBasicBlock *From,
1492                                      MachineBasicBlock *To, MachineInstr &MI) {
1493   // Make sure From and To are in straight line which means From dominates To
1494   // and To post dominates From.
1495   if (!DT->dominates(From, To) || !PDT->dominates(To, From))
1496     return true;
1497 
1498   auto BlockPair = std::make_pair(From, To);
1499 
1500   // Does these two blocks pair be queried before and have a definite cached
1501   // result?
1502   if (auto It = HasStoreCache.find(BlockPair); It != HasStoreCache.end())
1503     return It->second;
1504 
1505   if (auto It = StoreInstrCache.find(BlockPair); It != StoreInstrCache.end())
1506     return llvm::any_of(It->second, [&](MachineInstr *I) {
1507       return I->mayAlias(AA, MI, false);
1508     });
1509 
1510   bool SawStore = false;
1511   bool HasAliasedStore = false;
1512   DenseSet<MachineBasicBlock *> HandledBlocks;
1513   DenseSet<MachineBasicBlock *> HandledDomBlocks;
1514   // Go through all reachable blocks from From.
1515   for (MachineBasicBlock *BB : depth_first(From)) {
1516     // We insert the instruction at the start of block To, so no need to worry
1517     // about stores inside To.
1518     // Store in block From should be already considered when just enter function
1519     // SinkInstruction.
1520     if (BB == To || BB == From)
1521       continue;
1522 
1523     // We already handle this BB in previous iteration.
1524     if (HandledBlocks.count(BB))
1525       continue;
1526 
1527     HandledBlocks.insert(BB);
1528     // To post dominates BB, it must be a path from block From.
1529     if (PDT->dominates(To, BB)) {
1530       if (!HandledDomBlocks.count(BB))
1531         HandledDomBlocks.insert(BB);
1532 
1533       // If this BB is too big or the block number in straight line between From
1534       // and To is too big, stop searching to save compiling time.
1535       if (BB->sizeWithoutDebugLargerThan(SinkLoadInstsPerBlockThreshold) ||
1536           HandledDomBlocks.size() > SinkLoadBlocksThreshold) {
1537         for (auto *DomBB : HandledDomBlocks) {
1538           if (DomBB != BB && DT->dominates(DomBB, BB))
1539             HasStoreCache[std::make_pair(DomBB, To)] = true;
1540           else if (DomBB != BB && DT->dominates(BB, DomBB))
1541             HasStoreCache[std::make_pair(From, DomBB)] = true;
1542         }
1543         HasStoreCache[BlockPair] = true;
1544         return true;
1545       }
1546 
1547       for (MachineInstr &I : *BB) {
1548         // Treat as alias conservatively for a call or an ordered memory
1549         // operation.
1550         if (I.isCall() || I.hasOrderedMemoryRef()) {
1551           for (auto *DomBB : HandledDomBlocks) {
1552             if (DomBB != BB && DT->dominates(DomBB, BB))
1553               HasStoreCache[std::make_pair(DomBB, To)] = true;
1554             else if (DomBB != BB && DT->dominates(BB, DomBB))
1555               HasStoreCache[std::make_pair(From, DomBB)] = true;
1556           }
1557           HasStoreCache[BlockPair] = true;
1558           return true;
1559         }
1560 
1561         if (I.mayStore()) {
1562           SawStore = true;
1563           // We still have chance to sink MI if all stores between are not
1564           // aliased to MI.
1565           // Cache all store instructions, so that we don't need to go through
1566           // all From reachable blocks for next load instruction.
1567           if (I.mayAlias(AA, MI, false))
1568             HasAliasedStore = true;
1569           StoreInstrCache[BlockPair].push_back(&I);
1570         }
1571       }
1572     }
1573   }
1574   // If there is no store at all, cache the result.
1575   if (!SawStore)
1576     HasStoreCache[BlockPair] = false;
1577   return HasAliasedStore;
1578 }
1579 
1580 /// Sink instructions into cycles if profitable. This especially tries to
1581 /// prevent register spills caused by register pressure if there is little to no
1582 /// overhead moving instructions into cycles.
1583 bool MachineSinking::SinkIntoCycle(MachineCycle *Cycle, MachineInstr &I) {
1584   LLVM_DEBUG(dbgs() << "CycleSink: Finding sink block for: " << I);
1585   MachineBasicBlock *Preheader = Cycle->getCyclePreheader();
1586   assert(Preheader && "Cycle sink needs a preheader block");
1587   MachineBasicBlock *SinkBlock = nullptr;
1588   bool CanSink = true;
1589   const MachineOperand &MO = I.getOperand(0);
1590 
1591   for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
1592     LLVM_DEBUG(dbgs() << "CycleSink:   Analysing use: " << MI);
1593     if (!Cycle->contains(MI.getParent())) {
1594       LLVM_DEBUG(dbgs() << "CycleSink:   Use not in cycle, can't sink.\n");
1595       CanSink = false;
1596       break;
1597     }
1598 
1599     // FIXME: Come up with a proper cost model that estimates whether sinking
1600     // the instruction (and thus possibly executing it on every cycle
1601     // iteration) is more expensive than a register.
1602     // For now assumes that copies are cheap and thus almost always worth it.
1603     if (!MI.isCopy()) {
1604       LLVM_DEBUG(dbgs() << "CycleSink:   Use is not a copy\n");
1605       CanSink = false;
1606       break;
1607     }
1608     if (!SinkBlock) {
1609       SinkBlock = MI.getParent();
1610       LLVM_DEBUG(dbgs() << "CycleSink:   Setting sink block to: "
1611                         << printMBBReference(*SinkBlock) << "\n");
1612       continue;
1613     }
1614     SinkBlock = DT->findNearestCommonDominator(SinkBlock, MI.getParent());
1615     if (!SinkBlock) {
1616       LLVM_DEBUG(dbgs() << "CycleSink:   Can't find nearest dominator\n");
1617       CanSink = false;
1618       break;
1619     }
1620     LLVM_DEBUG(dbgs() << "CycleSink:   Setting nearest common dom block: "
1621                       << printMBBReference(*SinkBlock) << "\n");
1622   }
1623 
1624   if (!CanSink) {
1625     LLVM_DEBUG(dbgs() << "CycleSink: Can't sink instruction.\n");
1626     return false;
1627   }
1628   if (!SinkBlock) {
1629     LLVM_DEBUG(dbgs() << "CycleSink: Not sinking, can't find sink block.\n");
1630     return false;
1631   }
1632   if (SinkBlock == Preheader) {
1633     LLVM_DEBUG(
1634         dbgs() << "CycleSink: Not sinking, sink block is the preheader\n");
1635     return false;
1636   }
1637   if (SinkBlock->sizeWithoutDebugLargerThan(SinkLoadInstsPerBlockThreshold)) {
1638     LLVM_DEBUG(
1639         dbgs() << "CycleSink: Not Sinking, block too large to analyse.\n");
1640     return false;
1641   }
1642 
1643   LLVM_DEBUG(dbgs() << "CycleSink: Sinking instruction!\n");
1644   SinkBlock->splice(SinkBlock->SkipPHIsAndLabels(SinkBlock->begin()), Preheader,
1645                     I);
1646 
1647   // Conservatively clear any kill flags on uses of sunk instruction
1648   for (MachineOperand &MO : I.operands()) {
1649     if (MO.isReg() && MO.readsReg())
1650       RegsToClearKillFlags.insert(MO.getReg());
1651   }
1652 
1653   // The instruction is moved from its basic block, so do not retain the
1654   // debug information.
1655   assert(!I.isDebugInstr() && "Should not sink debug inst");
1656   I.setDebugLoc(DebugLoc());
1657   return true;
1658 }
1659 
1660 /// SinkInstruction - Determine whether it is safe to sink the specified machine
1661 /// instruction out of its current block into a successor.
1662 bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
1663                                      AllSuccsCache &AllSuccessors) {
1664   // Don't sink instructions that the target prefers not to sink.
1665   if (!TII->shouldSink(MI))
1666     return false;
1667 
1668   // Check if it's safe to move the instruction.
1669   if (!MI.isSafeToMove(SawStore))
1670     return false;
1671 
1672   // Convergent operations may not be made control-dependent on additional
1673   // values.
1674   if (MI.isConvergent())
1675     return false;
1676 
1677   // Don't break implicit null checks.  This is a performance heuristic, and not
1678   // required for correctness.
1679   if (SinkingPreventsImplicitNullCheck(MI, TII, TRI))
1680     return false;
1681 
1682   // FIXME: This should include support for sinking instructions within the
1683   // block they are currently in to shorten the live ranges.  We often get
1684   // instructions sunk into the top of a large block, but it would be better to
1685   // also sink them down before their first use in the block.  This xform has to
1686   // be careful not to *increase* register pressure though, e.g. sinking
1687   // "x = y + z" down if it kills y and z would increase the live ranges of y
1688   // and z and only shrink the live range of x.
1689 
1690   bool BreakPHIEdge = false;
1691   MachineBasicBlock *ParentBlock = MI.getParent();
1692   MachineBasicBlock *SuccToSinkTo =
1693       FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
1694 
1695   // If there are no outputs, it must have side-effects.
1696   if (!SuccToSinkTo)
1697     return false;
1698 
1699   // If the instruction to move defines a dead physical register which is live
1700   // when leaving the basic block, don't move it because it could turn into a
1701   // "zombie" define of that preg. E.g., EFLAGS.
1702   for (const MachineOperand &MO : MI.all_defs()) {
1703     Register Reg = MO.getReg();
1704     if (Reg == 0 || !Reg.isPhysical())
1705       continue;
1706     if (SuccToSinkTo->isLiveIn(Reg))
1707       return false;
1708   }
1709 
1710   LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
1711 
1712   // If the block has multiple predecessors, this is a critical edge.
1713   // Decide if we can sink along it or need to break the edge.
1714   if (SuccToSinkTo->pred_size() > 1) {
1715     // We cannot sink a load across a critical edge - there may be stores in
1716     // other code paths.
1717     bool TryBreak = false;
1718     bool Store =
1719         MI.mayLoad() ? hasStoreBetween(ParentBlock, SuccToSinkTo, MI) : true;
1720     if (!MI.isSafeToMove(Store)) {
1721       LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
1722       TryBreak = true;
1723     }
1724 
1725     // We don't want to sink across a critical edge if we don't dominate the
1726     // successor. We could be introducing calculations to new code paths.
1727     if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
1728       LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
1729       TryBreak = true;
1730     }
1731 
1732     // Don't sink instructions into a cycle.
1733     if (!TryBreak && CI->getCycle(SuccToSinkTo) &&
1734         (!CI->getCycle(SuccToSinkTo)->isReducible() ||
1735          CI->getCycle(SuccToSinkTo)->getHeader() == SuccToSinkTo)) {
1736       LLVM_DEBUG(dbgs() << " *** NOTE: cycle header found\n");
1737       TryBreak = true;
1738     }
1739 
1740     // Otherwise we are OK with sinking along a critical edge.
1741     if (!TryBreak)
1742       LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
1743     else {
1744       // Mark this edge as to be split.
1745       // If the edge can actually be split, the next iteration of the main loop
1746       // will sink MI in the newly created block.
1747       bool Status = PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo,
1748                                               BreakPHIEdge);
1749       if (!Status)
1750         LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
1751                              "break critical edge\n");
1752       // The instruction will not be sunk this time.
1753       return false;
1754     }
1755   }
1756 
1757   if (BreakPHIEdge) {
1758     // BreakPHIEdge is true if all the uses are in the successor MBB being
1759     // sunken into and they are all PHI nodes. In this case, machine-sink must
1760     // break the critical edge first.
1761     bool Status =
1762         PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
1763     if (!Status)
1764       LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
1765                            "break critical edge\n");
1766     // The instruction will not be sunk this time.
1767     return false;
1768   }
1769 
1770   // Determine where to insert into. Skip phi nodes.
1771   MachineBasicBlock::iterator InsertPos =
1772       SuccToSinkTo->SkipPHIsAndLabels(SuccToSinkTo->begin());
1773   if (blockPrologueInterferes(SuccToSinkTo, InsertPos, MI, TRI, TII, MRI)) {
1774     LLVM_DEBUG(dbgs() << " *** Not sinking: prologue interference\n");
1775     return false;
1776   }
1777 
1778   // Collect debug users of any vreg that this inst defines.
1779   SmallVector<MIRegs, 4> DbgUsersToSink;
1780   for (auto &MO : MI.all_defs()) {
1781     if (!MO.getReg().isVirtual())
1782       continue;
1783     if (!SeenDbgUsers.count(MO.getReg()))
1784       continue;
1785 
1786     // Sink any users that don't pass any other DBG_VALUEs for this variable.
1787     auto &Users = SeenDbgUsers[MO.getReg()];
1788     for (auto &User : Users) {
1789       MachineInstr *DbgMI = User.getPointer();
1790       if (User.getInt()) {
1791         // This DBG_VALUE would re-order assignments. If we can't copy-propagate
1792         // it, it can't be recovered. Set it undef.
1793         if (!attemptDebugCopyProp(MI, *DbgMI, MO.getReg()))
1794           DbgMI->setDebugValueUndef();
1795       } else {
1796         DbgUsersToSink.push_back(
1797             {DbgMI, SmallVector<unsigned, 2>(1, MO.getReg())});
1798       }
1799     }
1800   }
1801 
1802   // After sinking, some debug users may not be dominated any more. If possible,
1803   // copy-propagate their operands. As it's expensive, don't do this if there's
1804   // no debuginfo in the program.
1805   if (MI.getMF()->getFunction().getSubprogram() && MI.isCopy())
1806     SalvageUnsunkDebugUsersOfCopy(MI, SuccToSinkTo);
1807 
1808   performSink(MI, *SuccToSinkTo, InsertPos, DbgUsersToSink);
1809 
1810   // Conservatively, clear any kill flags, since it's possible that they are no
1811   // longer correct.
1812   // Note that we have to clear the kill flags for any register this instruction
1813   // uses as we may sink over another instruction which currently kills the
1814   // used registers.
1815   for (MachineOperand &MO : MI.all_uses())
1816     RegsToClearKillFlags.insert(MO.getReg()); // Remember to clear kill flags.
1817 
1818   return true;
1819 }
1820 
1821 void MachineSinking::SalvageUnsunkDebugUsersOfCopy(
1822     MachineInstr &MI, MachineBasicBlock *TargetBlock) {
1823   assert(MI.isCopy());
1824   assert(MI.getOperand(1).isReg());
1825 
1826   // Enumerate all users of vreg operands that are def'd. Skip those that will
1827   // be sunk. For the rest, if they are not dominated by the block we will sink
1828   // MI into, propagate the copy source to them.
1829   SmallVector<MachineInstr *, 4> DbgDefUsers;
1830   SmallVector<Register, 4> DbgUseRegs;
1831   const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1832   for (auto &MO : MI.all_defs()) {
1833     if (!MO.getReg().isVirtual())
1834       continue;
1835     DbgUseRegs.push_back(MO.getReg());
1836     for (auto &User : MRI.use_instructions(MO.getReg())) {
1837       if (!User.isDebugValue() || DT->dominates(TargetBlock, User.getParent()))
1838         continue;
1839 
1840       // If is in same block, will either sink or be use-before-def.
1841       if (User.getParent() == MI.getParent())
1842         continue;
1843 
1844       assert(User.hasDebugOperandForReg(MO.getReg()) &&
1845              "DBG_VALUE user of vreg, but has no operand for it?");
1846       DbgDefUsers.push_back(&User);
1847     }
1848   }
1849 
1850   // Point the users of this copy that are no longer dominated, at the source
1851   // of the copy.
1852   for (auto *User : DbgDefUsers) {
1853     for (auto &Reg : DbgUseRegs) {
1854       for (auto &DbgOp : User->getDebugOperandsForReg(Reg)) {
1855         DbgOp.setReg(MI.getOperand(1).getReg());
1856         DbgOp.setSubReg(MI.getOperand(1).getSubReg());
1857       }
1858     }
1859   }
1860 }
1861 
1862 //===----------------------------------------------------------------------===//
1863 // This pass is not intended to be a replacement or a complete alternative
1864 // for the pre-ra machine sink pass. It is only designed to sink COPY
1865 // instructions which should be handled after RA.
1866 //
1867 // This pass sinks COPY instructions into a successor block, if the COPY is not
1868 // used in the current block and the COPY is live-in to a single successor
1869 // (i.e., doesn't require the COPY to be duplicated).  This avoids executing the
1870 // copy on paths where their results aren't needed.  This also exposes
1871 // additional opportunites for dead copy elimination and shrink wrapping.
1872 //
1873 // These copies were either not handled by or are inserted after the MachineSink
1874 // pass. As an example of the former case, the MachineSink pass cannot sink
1875 // COPY instructions with allocatable source registers; for AArch64 these type
1876 // of copy instructions are frequently used to move function parameters (PhyReg)
1877 // into virtual registers in the entry block.
1878 //
1879 // For the machine IR below, this pass will sink %w19 in the entry into its
1880 // successor (%bb.1) because %w19 is only live-in in %bb.1.
1881 // %bb.0:
1882 //   %wzr = SUBSWri %w1, 1
1883 //   %w19 = COPY %w0
1884 //   Bcc 11, %bb.2
1885 // %bb.1:
1886 //   Live Ins: %w19
1887 //   BL @fun
1888 //   %w0 = ADDWrr %w0, %w19
1889 //   RET %w0
1890 // %bb.2:
1891 //   %w0 = COPY %wzr
1892 //   RET %w0
1893 // As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be
1894 // able to see %bb.0 as a candidate.
1895 //===----------------------------------------------------------------------===//
1896 namespace {
1897 
1898 class PostRAMachineSinking : public MachineFunctionPass {
1899 public:
1900   bool runOnMachineFunction(MachineFunction &MF) override;
1901 
1902   static char ID;
1903   PostRAMachineSinking() : MachineFunctionPass(ID) {}
1904   StringRef getPassName() const override { return "PostRA Machine Sink"; }
1905 
1906   void getAnalysisUsage(AnalysisUsage &AU) const override {
1907     AU.setPreservesCFG();
1908     MachineFunctionPass::getAnalysisUsage(AU);
1909   }
1910 
1911   MachineFunctionProperties getRequiredProperties() const override {
1912     return MachineFunctionProperties().set(
1913         MachineFunctionProperties::Property::NoVRegs);
1914   }
1915 
1916 private:
1917   /// Track which register units have been modified and used.
1918   LiveRegUnits ModifiedRegUnits, UsedRegUnits;
1919 
1920   /// Track DBG_VALUEs of (unmodified) register units. Each DBG_VALUE has an
1921   /// entry in this map for each unit it touches. The DBG_VALUE's entry
1922   /// consists of a pointer to the instruction itself, and a vector of registers
1923   /// referred to by the instruction that overlap the key register unit.
1924   DenseMap<unsigned, SmallVector<MIRegs, 2>> SeenDbgInstrs;
1925 
1926   /// Sink Copy instructions unused in the same block close to their uses in
1927   /// successors.
1928   bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF,
1929                      const TargetRegisterInfo *TRI, const TargetInstrInfo *TII);
1930 };
1931 } // namespace
1932 
1933 char PostRAMachineSinking::ID = 0;
1934 char &llvm::PostRAMachineSinkingID = PostRAMachineSinking::ID;
1935 
1936 INITIALIZE_PASS(PostRAMachineSinking, "postra-machine-sink",
1937                 "PostRA Machine Sink", false, false)
1938 
1939 static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, unsigned Reg,
1940                                   const TargetRegisterInfo *TRI) {
1941   LiveRegUnits LiveInRegUnits(*TRI);
1942   LiveInRegUnits.addLiveIns(MBB);
1943   return !LiveInRegUnits.available(Reg);
1944 }
1945 
1946 static MachineBasicBlock *
1947 getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
1948                       const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
1949                       unsigned Reg, const TargetRegisterInfo *TRI) {
1950   // Try to find a single sinkable successor in which Reg is live-in.
1951   MachineBasicBlock *BB = nullptr;
1952   for (auto *SI : SinkableBBs) {
1953     if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) {
1954       // If BB is set here, Reg is live-in to at least two sinkable successors,
1955       // so quit.
1956       if (BB)
1957         return nullptr;
1958       BB = SI;
1959     }
1960   }
1961   // Reg is not live-in to any sinkable successors.
1962   if (!BB)
1963     return nullptr;
1964 
1965   // Check if any register aliased with Reg is live-in in other successors.
1966   for (auto *SI : CurBB.successors()) {
1967     if (!SinkableBBs.count(SI) && aliasWithRegsInLiveIn(*SI, Reg, TRI))
1968       return nullptr;
1969   }
1970   return BB;
1971 }
1972 
1973 static MachineBasicBlock *
1974 getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
1975                       const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
1976                       ArrayRef<unsigned> DefedRegsInCopy,
1977                       const TargetRegisterInfo *TRI) {
1978   MachineBasicBlock *SingleBB = nullptr;
1979   for (auto DefReg : DefedRegsInCopy) {
1980     MachineBasicBlock *BB =
1981         getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI);
1982     if (!BB || (SingleBB && SingleBB != BB))
1983       return nullptr;
1984     SingleBB = BB;
1985   }
1986   return SingleBB;
1987 }
1988 
1989 static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB,
1990                            SmallVectorImpl<unsigned> &UsedOpsInCopy,
1991                            LiveRegUnits &UsedRegUnits,
1992                            const TargetRegisterInfo *TRI) {
1993   for (auto U : UsedOpsInCopy) {
1994     MachineOperand &MO = MI->getOperand(U);
1995     Register SrcReg = MO.getReg();
1996     if (!UsedRegUnits.available(SrcReg)) {
1997       MachineBasicBlock::iterator NI = std::next(MI->getIterator());
1998       for (MachineInstr &UI : make_range(NI, CurBB.end())) {
1999         if (UI.killsRegister(SrcReg, TRI)) {
2000           UI.clearRegisterKills(SrcReg, TRI);
2001           MO.setIsKill(true);
2002           break;
2003         }
2004       }
2005     }
2006   }
2007 }
2008 
2009 static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB,
2010                          SmallVectorImpl<unsigned> &UsedOpsInCopy,
2011                          SmallVectorImpl<unsigned> &DefedRegsInCopy) {
2012   MachineFunction &MF = *SuccBB->getParent();
2013   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2014   for (unsigned DefReg : DefedRegsInCopy)
2015     for (MCPhysReg S : TRI->subregs_inclusive(DefReg))
2016       SuccBB->removeLiveIn(S);
2017   for (auto U : UsedOpsInCopy)
2018     SuccBB->addLiveIn(MI->getOperand(U).getReg());
2019   SuccBB->sortUniqueLiveIns();
2020 }
2021 
2022 static bool hasRegisterDependency(MachineInstr *MI,
2023                                   SmallVectorImpl<unsigned> &UsedOpsInCopy,
2024                                   SmallVectorImpl<unsigned> &DefedRegsInCopy,
2025                                   LiveRegUnits &ModifiedRegUnits,
2026                                   LiveRegUnits &UsedRegUnits) {
2027   bool HasRegDependency = false;
2028   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2029     MachineOperand &MO = MI->getOperand(i);
2030     if (!MO.isReg())
2031       continue;
2032     Register Reg = MO.getReg();
2033     if (!Reg)
2034       continue;
2035     if (MO.isDef()) {
2036       if (!ModifiedRegUnits.available(Reg) || !UsedRegUnits.available(Reg)) {
2037         HasRegDependency = true;
2038         break;
2039       }
2040       DefedRegsInCopy.push_back(Reg);
2041 
2042       // FIXME: instead of isUse(), readsReg() would be a better fix here,
2043       // For example, we can ignore modifications in reg with undef. However,
2044       // it's not perfectly clear if skipping the internal read is safe in all
2045       // other targets.
2046     } else if (MO.isUse()) {
2047       if (!ModifiedRegUnits.available(Reg)) {
2048         HasRegDependency = true;
2049         break;
2050       }
2051       UsedOpsInCopy.push_back(i);
2052     }
2053   }
2054   return HasRegDependency;
2055 }
2056 
2057 bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock &CurBB,
2058                                          MachineFunction &MF,
2059                                          const TargetRegisterInfo *TRI,
2060                                          const TargetInstrInfo *TII) {
2061   SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs;
2062   // FIXME: For now, we sink only to a successor which has a single predecessor
2063   // so that we can directly sink COPY instructions to the successor without
2064   // adding any new block or branch instruction.
2065   for (MachineBasicBlock *SI : CurBB.successors())
2066     if (!SI->livein_empty() && SI->pred_size() == 1)
2067       SinkableBBs.insert(SI);
2068 
2069   if (SinkableBBs.empty())
2070     return false;
2071 
2072   bool Changed = false;
2073 
2074   // Track which registers have been modified and used between the end of the
2075   // block and the current instruction.
2076   ModifiedRegUnits.clear();
2077   UsedRegUnits.clear();
2078   SeenDbgInstrs.clear();
2079 
2080   for (MachineInstr &MI : llvm::make_early_inc_range(llvm::reverse(CurBB))) {
2081     // Track the operand index for use in Copy.
2082     SmallVector<unsigned, 2> UsedOpsInCopy;
2083     // Track the register number defed in Copy.
2084     SmallVector<unsigned, 2> DefedRegsInCopy;
2085 
2086     // We must sink this DBG_VALUE if its operand is sunk. To avoid searching
2087     // for DBG_VALUEs later, record them when they're encountered.
2088     if (MI.isDebugValue() && !MI.isDebugRef()) {
2089       SmallDenseMap<MCRegister, SmallVector<unsigned, 2>, 4> MIUnits;
2090       bool IsValid = true;
2091       for (MachineOperand &MO : MI.debug_operands()) {
2092         if (MO.isReg() && MO.getReg().isPhysical()) {
2093           // Bail if we can already tell the sink would be rejected, rather
2094           // than needlessly accumulating lots of DBG_VALUEs.
2095           if (hasRegisterDependency(&MI, UsedOpsInCopy, DefedRegsInCopy,
2096                                     ModifiedRegUnits, UsedRegUnits)) {
2097             IsValid = false;
2098             break;
2099           }
2100 
2101           // Record debug use of each reg unit.
2102           for (MCRegUnit Unit : TRI->regunits(MO.getReg()))
2103             MIUnits[Unit].push_back(MO.getReg());
2104         }
2105       }
2106       if (IsValid) {
2107         for (auto &RegOps : MIUnits)
2108           SeenDbgInstrs[RegOps.first].emplace_back(&MI,
2109                                                    std::move(RegOps.second));
2110       }
2111       continue;
2112     }
2113 
2114     if (MI.isDebugOrPseudoInstr())
2115       continue;
2116 
2117     // Do not move any instruction across function call.
2118     if (MI.isCall())
2119       return false;
2120 
2121     if (!MI.isCopy() || !MI.getOperand(0).isRenamable()) {
2122       LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2123                                         TRI);
2124       continue;
2125     }
2126 
2127     // Don't sink the COPY if it would violate a register dependency.
2128     if (hasRegisterDependency(&MI, UsedOpsInCopy, DefedRegsInCopy,
2129                               ModifiedRegUnits, UsedRegUnits)) {
2130       LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2131                                         TRI);
2132       continue;
2133     }
2134     assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) &&
2135            "Unexpect SrcReg or DefReg");
2136     MachineBasicBlock *SuccBB =
2137         getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI);
2138     // Don't sink if we cannot find a single sinkable successor in which Reg
2139     // is live-in.
2140     if (!SuccBB) {
2141       LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2142                                         TRI);
2143       continue;
2144     }
2145     assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) &&
2146            "Unexpected predecessor");
2147 
2148     // Collect DBG_VALUEs that must sink with this copy. We've previously
2149     // recorded which reg units that DBG_VALUEs read, if this instruction
2150     // writes any of those units then the corresponding DBG_VALUEs must sink.
2151     MapVector<MachineInstr *, MIRegs::second_type> DbgValsToSinkMap;
2152     for (auto &MO : MI.all_defs()) {
2153       for (MCRegUnit Unit : TRI->regunits(MO.getReg())) {
2154         for (const auto &MIRegs : SeenDbgInstrs.lookup(Unit)) {
2155           auto &Regs = DbgValsToSinkMap[MIRegs.first];
2156           for (unsigned Reg : MIRegs.second)
2157             Regs.push_back(Reg);
2158         }
2159       }
2160     }
2161     auto DbgValsToSink = DbgValsToSinkMap.takeVector();
2162 
2163     LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccBB);
2164 
2165     MachineBasicBlock::iterator InsertPos =
2166         SuccBB->SkipPHIsAndLabels(SuccBB->begin());
2167     if (blockPrologueInterferes(SuccBB, InsertPos, MI, TRI, TII, nullptr)) {
2168       LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2169                                         TRI);
2170       LLVM_DEBUG(dbgs() << " *** Not sinking: prologue interference\n");
2171       continue;
2172     }
2173 
2174     // Clear the kill flag if SrcReg is killed between MI and the end of the
2175     // block.
2176     clearKillFlags(&MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI);
2177     performSink(MI, *SuccBB, InsertPos, DbgValsToSink);
2178     updateLiveIn(&MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy);
2179 
2180     Changed = true;
2181     ++NumPostRACopySink;
2182   }
2183   return Changed;
2184 }
2185 
2186 bool PostRAMachineSinking::runOnMachineFunction(MachineFunction &MF) {
2187   if (skipFunction(MF.getFunction()))
2188     return false;
2189 
2190   bool Changed = false;
2191   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2192   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
2193 
2194   ModifiedRegUnits.init(*TRI);
2195   UsedRegUnits.init(*TRI);
2196   for (auto &BB : MF)
2197     Changed |= tryToSinkCopy(BB, MF, TRI, TII);
2198 
2199   return Changed;
2200 }
2201