xref: /llvm-project/llvm/lib/CodeGen/MachineSink.cpp (revision e72209db3586ee03f433fe30c3bfac6c9c4d9d6f)
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   return false;
962 }
963 
964 bool MachineSinking::isLegalToBreakCriticalEdge(MachineInstr &MI,
965                                                 MachineBasicBlock *FromBB,
966                                                 MachineBasicBlock *ToBB,
967                                                 bool BreakPHIEdge) {
968   // Avoid breaking back edge. From == To means backedge for single BB cycle.
969   if (!SplitEdges || FromBB == ToBB || !FromBB->isSuccessor(ToBB))
970     return false;
971 
972   MachineCycle *FromCycle = CI->getCycle(FromBB);
973   MachineCycle *ToCycle = CI->getCycle(ToBB);
974 
975   // Check for backedges of more "complex" cycles.
976   if (FromCycle == ToCycle && FromCycle &&
977       (!FromCycle->isReducible() || FromCycle->getHeader() == ToBB))
978     return false;
979 
980   // It's not always legal to break critical edges and sink the computation
981   // to the edge.
982   //
983   // %bb.1:
984   // v1024
985   // Beq %bb.3
986   // <fallthrough>
987   // %bb.2:
988   // ... no uses of v1024
989   // <fallthrough>
990   // %bb.3:
991   // ...
992   //       = v1024
993   //
994   // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted:
995   //
996   // %bb.1:
997   // ...
998   // Bne %bb.2
999   // %bb.4:
1000   // v1024 =
1001   // B %bb.3
1002   // %bb.2:
1003   // ... no uses of v1024
1004   // <fallthrough>
1005   // %bb.3:
1006   // ...
1007   //       = v1024
1008   //
1009   // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3
1010   // flow. We need to ensure the new basic block where the computation is
1011   // sunk to dominates all the uses.
1012   // It's only legal to break critical edge and sink the computation to the
1013   // new block if all the predecessors of "To", except for "From", are
1014   // not dominated by "From". Given SSA property, this means these
1015   // predecessors are dominated by "To".
1016   //
1017   // There is no need to do this check if all the uses are PHI nodes. PHI
1018   // sources are only defined on the specific predecessor edges.
1019   if (!BreakPHIEdge) {
1020     for (MachineBasicBlock *Pred : ToBB->predecessors())
1021       if (Pred != FromBB && !DT->dominates(ToBB, Pred))
1022         return false;
1023   }
1024 
1025   return true;
1026 }
1027 
1028 bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
1029                                                MachineBasicBlock *FromBB,
1030                                                MachineBasicBlock *ToBB,
1031                                                bool BreakPHIEdge) {
1032   bool Status = false;
1033   MachineBasicBlock *DeferredFromBB = nullptr;
1034   if (isWorthBreakingCriticalEdge(MI, FromBB, ToBB, DeferredFromBB)) {
1035     // If there is a DeferredFromBB, we consider FromBB only if _both_
1036     // of them are legal to split.
1037     if ((!DeferredFromBB ||
1038          ToSplit.count(std::make_pair(DeferredFromBB, ToBB)) ||
1039          isLegalToBreakCriticalEdge(MI, DeferredFromBB, ToBB, BreakPHIEdge)) &&
1040         isLegalToBreakCriticalEdge(MI, FromBB, ToBB, BreakPHIEdge)) {
1041       ToSplit.insert(std::make_pair(FromBB, ToBB));
1042       if (DeferredFromBB)
1043         ToSplit.insert(std::make_pair(DeferredFromBB, ToBB));
1044       Status = true;
1045     }
1046   }
1047 
1048   return Status;
1049 }
1050 
1051 std::vector<unsigned> &
1052 MachineSinking::getBBRegisterPressure(const MachineBasicBlock &MBB) {
1053   // Currently to save compiling time, MBB's register pressure will not change
1054   // in one ProcessBlock iteration because of CachedRegisterPressure. but MBB's
1055   // register pressure is changed after sinking any instructions into it.
1056   // FIXME: need a accurate and cheap register pressure estiminate model here.
1057   auto RP = CachedRegisterPressure.find(&MBB);
1058   if (RP != CachedRegisterPressure.end())
1059     return RP->second;
1060 
1061   RegionPressure Pressure;
1062   RegPressureTracker RPTracker(Pressure);
1063 
1064   // Initialize the register pressure tracker.
1065   RPTracker.init(MBB.getParent(), &RegClassInfo, nullptr, &MBB, MBB.end(),
1066                  /*TrackLaneMasks*/ false, /*TrackUntiedDefs=*/true);
1067 
1068   for (MachineBasicBlock::const_iterator MII = MBB.instr_end(),
1069                                          MIE = MBB.instr_begin();
1070        MII != MIE; --MII) {
1071     const MachineInstr &MI = *std::prev(MII);
1072     if (MI.isDebugInstr() || MI.isPseudoProbe())
1073       continue;
1074     RegisterOperands RegOpers;
1075     RegOpers.collect(MI, *TRI, *MRI, false, false);
1076     RPTracker.recedeSkipDebugValues();
1077     assert(&*RPTracker.getPos() == &MI && "RPTracker sync error!");
1078     RPTracker.recede(RegOpers);
1079   }
1080 
1081   RPTracker.closeRegion();
1082   auto It = CachedRegisterPressure.insert(
1083       std::make_pair(&MBB, RPTracker.getPressure().MaxSetPressure));
1084   return It.first->second;
1085 }
1086 
1087 bool MachineSinking::registerPressureSetExceedsLimit(
1088     unsigned NRegs, const TargetRegisterClass *RC,
1089     const MachineBasicBlock &MBB) {
1090   unsigned Weight = NRegs * TRI->getRegClassWeight(RC).RegWeight;
1091   const int *PS = TRI->getRegClassPressureSets(RC);
1092   std::vector<unsigned> BBRegisterPressure = getBBRegisterPressure(MBB);
1093   for (; *PS != -1; PS++)
1094     if (Weight + BBRegisterPressure[*PS] >=
1095         TRI->getRegPressureSetLimit(*MBB.getParent(), *PS))
1096       return true;
1097   return false;
1098 }
1099 
1100 /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
1101 bool MachineSinking::isProfitableToSinkTo(Register Reg, MachineInstr &MI,
1102                                           MachineBasicBlock *MBB,
1103                                           MachineBasicBlock *SuccToSinkTo,
1104                                           AllSuccsCache &AllSuccessors) {
1105   assert(SuccToSinkTo && "Invalid SinkTo Candidate BB");
1106 
1107   if (MBB == SuccToSinkTo)
1108     return false;
1109 
1110   // It is profitable if SuccToSinkTo does not post dominate current block.
1111   if (!PDT->dominates(SuccToSinkTo, MBB))
1112     return true;
1113 
1114   // It is profitable to sink an instruction from a deeper cycle to a shallower
1115   // cycle, even if the latter post-dominates the former (PR21115).
1116   if (CI->getCycleDepth(MBB) > CI->getCycleDepth(SuccToSinkTo))
1117     return true;
1118 
1119   // Check if only use in post dominated block is PHI instruction.
1120   bool NonPHIUse = false;
1121   for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
1122     MachineBasicBlock *UseBlock = UseInst.getParent();
1123     if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
1124       NonPHIUse = true;
1125   }
1126   if (!NonPHIUse)
1127     return true;
1128 
1129   // If SuccToSinkTo post dominates then also it may be profitable if MI
1130   // can further profitably sinked into another block in next round.
1131   bool BreakPHIEdge = false;
1132   // FIXME - If finding successor is compile time expensive then cache results.
1133   if (MachineBasicBlock *MBB2 =
1134           FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
1135     return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
1136 
1137   MachineCycle *MCycle = CI->getCycle(MBB);
1138 
1139   // If the instruction is not inside a cycle, it is not profitable to sink MI
1140   // to a post dominate block SuccToSinkTo.
1141   if (!MCycle)
1142     return false;
1143 
1144   // If this instruction is inside a Cycle and sinking this instruction can make
1145   // more registers live range shorten, it is still prifitable.
1146   for (const MachineOperand &MO : MI.operands()) {
1147     // Ignore non-register operands.
1148     if (!MO.isReg())
1149       continue;
1150     Register Reg = MO.getReg();
1151     if (Reg == 0)
1152       continue;
1153 
1154     if (Reg.isPhysical()) {
1155       // Don't handle non-constant and non-ignorable physical register uses.
1156       if (MO.isUse() && !MRI->isConstantPhysReg(Reg) &&
1157           !TII->isIgnorableUse(MO))
1158         return false;
1159       continue;
1160     }
1161 
1162     // Users for the defs are all dominated by SuccToSinkTo.
1163     if (MO.isDef()) {
1164       // This def register's live range is shortened after sinking.
1165       bool LocalUse = false;
1166       if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, BreakPHIEdge,
1167                                    LocalUse))
1168         return false;
1169     } else {
1170       MachineInstr *DefMI = MRI->getVRegDef(Reg);
1171       if (!DefMI)
1172         continue;
1173       MachineCycle *Cycle = CI->getCycle(DefMI->getParent());
1174       // DefMI is defined outside of cycle. There should be no live range
1175       // impact for this operand. Defination outside of cycle means:
1176       // 1: defination is outside of cycle.
1177       // 2: defination is in this cycle, but it is a PHI in the cycle header.
1178       if (Cycle != MCycle || (DefMI->isPHI() && Cycle && Cycle->isReducible() &&
1179                               Cycle->getHeader() == DefMI->getParent()))
1180         continue;
1181       // The DefMI is defined inside the cycle.
1182       // If sinking this operand makes some register pressure set exceed limit,
1183       // it is not profitable.
1184       if (registerPressureSetExceedsLimit(1, MRI->getRegClass(Reg),
1185                                           *SuccToSinkTo)) {
1186         LLVM_DEBUG(dbgs() << "register pressure exceed limit, not profitable.");
1187         return false;
1188       }
1189     }
1190   }
1191 
1192   // If MI is in cycle and all its operands are alive across the whole cycle or
1193   // if no operand sinking make register pressure set exceed limit, it is
1194   // profitable to sink MI.
1195   return true;
1196 }
1197 
1198 /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
1199 /// computing it if it was not already cached.
1200 SmallVector<MachineBasicBlock *, 4> &
1201 MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
1202                                        AllSuccsCache &AllSuccessors) const {
1203   // Do we have the sorted successors in cache ?
1204   auto Succs = AllSuccessors.find(MBB);
1205   if (Succs != AllSuccessors.end())
1206     return Succs->second;
1207 
1208   SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->successors());
1209 
1210   // Handle cases where sinking can happen but where the sink point isn't a
1211   // successor. For example:
1212   //
1213   //   x = computation
1214   //   if () {} else {}
1215   //   use x
1216   //
1217   for (MachineDomTreeNode *DTChild : DT->getNode(MBB)->children()) {
1218     // DomTree children of MBB that have MBB as immediate dominator are added.
1219     if (DTChild->getIDom()->getBlock() == MI.getParent() &&
1220         // Skip MBBs already added to the AllSuccs vector above.
1221         !MBB->isSuccessor(DTChild->getBlock()))
1222       AllSuccs.push_back(DTChild->getBlock());
1223   }
1224 
1225   // Sort Successors according to their cycle depth or block frequency info.
1226   llvm::stable_sort(
1227       AllSuccs, [&](const MachineBasicBlock *L, const MachineBasicBlock *R) {
1228         uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
1229         uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
1230         if (llvm::shouldOptimizeForSize(MBB, PSI, MBFI) ||
1231             (!LHSFreq && !RHSFreq))
1232           return CI->getCycleDepth(L) < CI->getCycleDepth(R);
1233         return LHSFreq < RHSFreq;
1234       });
1235 
1236   auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
1237 
1238   return it.first->second;
1239 }
1240 
1241 /// FindSuccToSinkTo - Find a successor to sink this instruction to.
1242 MachineBasicBlock *
1243 MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
1244                                  bool &BreakPHIEdge,
1245                                  AllSuccsCache &AllSuccessors) {
1246   assert(MBB && "Invalid MachineBasicBlock!");
1247 
1248   // loop over all the operands of the specified instruction.  If there is
1249   // anything we can't handle, bail out.
1250 
1251   // SuccToSinkTo - This is the successor to sink this instruction to, once we
1252   // decide.
1253   MachineBasicBlock *SuccToSinkTo = nullptr;
1254   for (const MachineOperand &MO : MI.operands()) {
1255     if (!MO.isReg())
1256       continue; // Ignore non-register operands.
1257 
1258     Register Reg = MO.getReg();
1259     if (Reg == 0)
1260       continue;
1261 
1262     if (Reg.isPhysical()) {
1263       if (MO.isUse()) {
1264         // If the physreg has no defs anywhere, it's just an ambient register
1265         // and we can freely move its uses. Alternatively, if it's allocatable,
1266         // it could get allocated to something with a def during allocation.
1267         if (!MRI->isConstantPhysReg(Reg) && !TII->isIgnorableUse(MO))
1268           return nullptr;
1269       } else if (!MO.isDead()) {
1270         // A def that isn't dead. We can't move it.
1271         return nullptr;
1272       }
1273     } else {
1274       // Virtual register uses are always safe to sink.
1275       if (MO.isUse())
1276         continue;
1277 
1278       // If it's not safe to move defs of the register class, then abort.
1279       if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
1280         return nullptr;
1281 
1282       // Virtual register defs can only be sunk if all their uses are in blocks
1283       // dominated by one of the successors.
1284       if (SuccToSinkTo) {
1285         // If a previous operand picked a block to sink to, then this operand
1286         // must be sinkable to the same block.
1287         bool LocalUse = false;
1288         if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, BreakPHIEdge,
1289                                      LocalUse))
1290           return nullptr;
1291 
1292         continue;
1293       }
1294 
1295       // Otherwise, we should look at all the successors and decide which one
1296       // we should sink to. If we have reliable block frequency information
1297       // (frequency != 0) available, give successors with smaller frequencies
1298       // higher priority, otherwise prioritize smaller cycle depths.
1299       for (MachineBasicBlock *SuccBlock :
1300            GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
1301         bool LocalUse = false;
1302         if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB, BreakPHIEdge,
1303                                     LocalUse)) {
1304           SuccToSinkTo = SuccBlock;
1305           break;
1306         }
1307         if (LocalUse)
1308           // Def is used locally, it's never safe to move this def.
1309           return nullptr;
1310       }
1311 
1312       // If we couldn't find a block to sink to, ignore this instruction.
1313       if (!SuccToSinkTo)
1314         return nullptr;
1315       if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
1316         return nullptr;
1317     }
1318   }
1319 
1320   // It is not possible to sink an instruction into its own block.  This can
1321   // happen with cycles.
1322   if (MBB == SuccToSinkTo)
1323     return nullptr;
1324 
1325   // It's not safe to sink instructions to EH landing pad. Control flow into
1326   // landing pad is implicitly defined.
1327   if (SuccToSinkTo && SuccToSinkTo->isEHPad())
1328     return nullptr;
1329 
1330   // It ought to be okay to sink instructions into an INLINEASM_BR target, but
1331   // only if we make sure that MI occurs _before_ an INLINEASM_BR instruction in
1332   // the source block (which this code does not yet do). So for now, forbid
1333   // doing so.
1334   if (SuccToSinkTo && SuccToSinkTo->isInlineAsmBrIndirectTarget())
1335     return nullptr;
1336 
1337   if (SuccToSinkTo && !TII->isSafeToSink(MI, SuccToSinkTo, CI))
1338     return nullptr;
1339 
1340   return SuccToSinkTo;
1341 }
1342 
1343 /// Return true if MI is likely to be usable as a memory operation by the
1344 /// implicit null check optimization.
1345 ///
1346 /// This is a "best effort" heuristic, and should not be relied upon for
1347 /// correctness.  This returning true does not guarantee that the implicit null
1348 /// check optimization is legal over MI, and this returning false does not
1349 /// guarantee MI cannot possibly be used to do a null check.
1350 static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI,
1351                                              const TargetInstrInfo *TII,
1352                                              const TargetRegisterInfo *TRI) {
1353   using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
1354 
1355   auto *MBB = MI.getParent();
1356   if (MBB->pred_size() != 1)
1357     return false;
1358 
1359   auto *PredMBB = *MBB->pred_begin();
1360   auto *PredBB = PredMBB->getBasicBlock();
1361 
1362   // Frontends that don't use implicit null checks have no reason to emit
1363   // branches with make.implicit metadata, and this function should always
1364   // return false for them.
1365   if (!PredBB ||
1366       !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
1367     return false;
1368 
1369   const MachineOperand *BaseOp;
1370   int64_t Offset;
1371   bool OffsetIsScalable;
1372   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
1373     return false;
1374 
1375   if (!BaseOp->isReg())
1376     return false;
1377 
1378   if (!(MI.mayLoad() && !MI.isPredicable()))
1379     return false;
1380 
1381   MachineBranchPredicate MBP;
1382   if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
1383     return false;
1384 
1385   return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
1386          (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
1387           MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
1388          MBP.LHS.getReg() == BaseOp->getReg();
1389 }
1390 
1391 /// If the sunk instruction is a copy, try to forward the copy instead of
1392 /// leaving an 'undef' DBG_VALUE in the original location. Don't do this if
1393 /// there's any subregister weirdness involved. Returns true if copy
1394 /// propagation occurred.
1395 static bool attemptDebugCopyProp(MachineInstr &SinkInst, MachineInstr &DbgMI,
1396                                  Register Reg) {
1397   const MachineRegisterInfo &MRI = SinkInst.getMF()->getRegInfo();
1398   const TargetInstrInfo &TII = *SinkInst.getMF()->getSubtarget().getInstrInfo();
1399 
1400   // Copy DBG_VALUE operand and set the original to undef. We then check to
1401   // see whether this is something that can be copy-forwarded. If it isn't,
1402   // continue around the loop.
1403 
1404   const MachineOperand *SrcMO = nullptr, *DstMO = nullptr;
1405   auto CopyOperands = TII.isCopyInstr(SinkInst);
1406   if (!CopyOperands)
1407     return false;
1408   SrcMO = CopyOperands->Source;
1409   DstMO = CopyOperands->Destination;
1410 
1411   // Check validity of forwarding this copy.
1412   bool PostRA = MRI.getNumVirtRegs() == 0;
1413 
1414   // Trying to forward between physical and virtual registers is too hard.
1415   if (Reg.isVirtual() != SrcMO->getReg().isVirtual())
1416     return false;
1417 
1418   // Only try virtual register copy-forwarding before regalloc, and physical
1419   // register copy-forwarding after regalloc.
1420   bool arePhysRegs = !Reg.isVirtual();
1421   if (arePhysRegs != PostRA)
1422     return false;
1423 
1424   // Pre-regalloc, only forward if all subregisters agree (or there are no
1425   // subregs at all). More analysis might recover some forwardable copies.
1426   if (!PostRA)
1427     for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg))
1428       if (DbgMO.getSubReg() != SrcMO->getSubReg() ||
1429           DbgMO.getSubReg() != DstMO->getSubReg())
1430         return false;
1431 
1432   // Post-regalloc, we may be sinking a DBG_VALUE of a sub or super-register
1433   // of this copy. Only forward the copy if the DBG_VALUE operand exactly
1434   // matches the copy destination.
1435   if (PostRA && Reg != DstMO->getReg())
1436     return false;
1437 
1438   for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg)) {
1439     DbgMO.setReg(SrcMO->getReg());
1440     DbgMO.setSubReg(SrcMO->getSubReg());
1441   }
1442   return true;
1443 }
1444 
1445 using MIRegs = std::pair<MachineInstr *, SmallVector<unsigned, 2>>;
1446 /// Sink an instruction and its associated debug instructions.
1447 static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo,
1448                         MachineBasicBlock::iterator InsertPos,
1449                         ArrayRef<MIRegs> DbgValuesToSink) {
1450   // If we cannot find a location to use (merge with), then we erase the debug
1451   // location to prevent debug-info driven tools from potentially reporting
1452   // wrong location information.
1453   if (!SuccToSinkTo.empty() && InsertPos != SuccToSinkTo.end())
1454     MI.setDebugLoc(DILocation::getMergedLocation(MI.getDebugLoc(),
1455                                                  InsertPos->getDebugLoc()));
1456   else
1457     MI.setDebugLoc(DebugLoc());
1458 
1459   // Move the instruction.
1460   MachineBasicBlock *ParentBlock = MI.getParent();
1461   SuccToSinkTo.splice(InsertPos, ParentBlock, MI,
1462                       ++MachineBasicBlock::iterator(MI));
1463 
1464   // Sink a copy of debug users to the insert position. Mark the original
1465   // DBG_VALUE location as 'undef', indicating that any earlier variable
1466   // location should be terminated as we've optimised away the value at this
1467   // point.
1468   for (const auto &DbgValueToSink : DbgValuesToSink) {
1469     MachineInstr *DbgMI = DbgValueToSink.first;
1470     MachineInstr *NewDbgMI = DbgMI->getMF()->CloneMachineInstr(DbgMI);
1471     SuccToSinkTo.insert(InsertPos, NewDbgMI);
1472 
1473     bool PropagatedAllSunkOps = true;
1474     for (unsigned Reg : DbgValueToSink.second) {
1475       if (DbgMI->hasDebugOperandForReg(Reg)) {
1476         if (!attemptDebugCopyProp(MI, *DbgMI, Reg)) {
1477           PropagatedAllSunkOps = false;
1478           break;
1479         }
1480       }
1481     }
1482     if (!PropagatedAllSunkOps)
1483       DbgMI->setDebugValueUndef();
1484   }
1485 }
1486 
1487 /// hasStoreBetween - check if there is store betweeen straight line blocks From
1488 /// and To.
1489 bool MachineSinking::hasStoreBetween(MachineBasicBlock *From,
1490                                      MachineBasicBlock *To, MachineInstr &MI) {
1491   // Make sure From and To are in straight line which means From dominates To
1492   // and To post dominates From.
1493   if (!DT->dominates(From, To) || !PDT->dominates(To, From))
1494     return true;
1495 
1496   auto BlockPair = std::make_pair(From, To);
1497 
1498   // Does these two blocks pair be queried before and have a definite cached
1499   // result?
1500   if (auto It = HasStoreCache.find(BlockPair); It != HasStoreCache.end())
1501     return It->second;
1502 
1503   if (auto It = StoreInstrCache.find(BlockPair); It != StoreInstrCache.end())
1504     return llvm::any_of(It->second, [&](MachineInstr *I) {
1505       return I->mayAlias(AA, MI, false);
1506     });
1507 
1508   bool SawStore = false;
1509   bool HasAliasedStore = false;
1510   DenseSet<MachineBasicBlock *> HandledBlocks;
1511   DenseSet<MachineBasicBlock *> HandledDomBlocks;
1512   // Go through all reachable blocks from From.
1513   for (MachineBasicBlock *BB : depth_first(From)) {
1514     // We insert the instruction at the start of block To, so no need to worry
1515     // about stores inside To.
1516     // Store in block From should be already considered when just enter function
1517     // SinkInstruction.
1518     if (BB == To || BB == From)
1519       continue;
1520 
1521     // We already handle this BB in previous iteration.
1522     if (HandledBlocks.count(BB))
1523       continue;
1524 
1525     HandledBlocks.insert(BB);
1526     // To post dominates BB, it must be a path from block From.
1527     if (PDT->dominates(To, BB)) {
1528       if (!HandledDomBlocks.count(BB))
1529         HandledDomBlocks.insert(BB);
1530 
1531       // If this BB is too big or the block number in straight line between From
1532       // and To is too big, stop searching to save compiling time.
1533       if (BB->sizeWithoutDebugLargerThan(SinkLoadInstsPerBlockThreshold) ||
1534           HandledDomBlocks.size() > SinkLoadBlocksThreshold) {
1535         for (auto *DomBB : HandledDomBlocks) {
1536           if (DomBB != BB && DT->dominates(DomBB, BB))
1537             HasStoreCache[std::make_pair(DomBB, To)] = true;
1538           else if (DomBB != BB && DT->dominates(BB, DomBB))
1539             HasStoreCache[std::make_pair(From, DomBB)] = true;
1540         }
1541         HasStoreCache[BlockPair] = true;
1542         return true;
1543       }
1544 
1545       for (MachineInstr &I : *BB) {
1546         // Treat as alias conservatively for a call or an ordered memory
1547         // operation.
1548         if (I.isCall() || I.hasOrderedMemoryRef()) {
1549           for (auto *DomBB : HandledDomBlocks) {
1550             if (DomBB != BB && DT->dominates(DomBB, BB))
1551               HasStoreCache[std::make_pair(DomBB, To)] = true;
1552             else if (DomBB != BB && DT->dominates(BB, DomBB))
1553               HasStoreCache[std::make_pair(From, DomBB)] = true;
1554           }
1555           HasStoreCache[BlockPair] = true;
1556           return true;
1557         }
1558 
1559         if (I.mayStore()) {
1560           SawStore = true;
1561           // We still have chance to sink MI if all stores between are not
1562           // aliased to MI.
1563           // Cache all store instructions, so that we don't need to go through
1564           // all From reachable blocks for next load instruction.
1565           if (I.mayAlias(AA, MI, false))
1566             HasAliasedStore = true;
1567           StoreInstrCache[BlockPair].push_back(&I);
1568         }
1569       }
1570     }
1571   }
1572   // If there is no store at all, cache the result.
1573   if (!SawStore)
1574     HasStoreCache[BlockPair] = false;
1575   return HasAliasedStore;
1576 }
1577 
1578 /// Sink instructions into cycles if profitable. This especially tries to
1579 /// prevent register spills caused by register pressure if there is little to no
1580 /// overhead moving instructions into cycles.
1581 bool MachineSinking::SinkIntoCycle(MachineCycle *Cycle, MachineInstr &I) {
1582   LLVM_DEBUG(dbgs() << "CycleSink: Finding sink block for: " << I);
1583   MachineBasicBlock *Preheader = Cycle->getCyclePreheader();
1584   assert(Preheader && "Cycle sink needs a preheader block");
1585   MachineBasicBlock *SinkBlock = nullptr;
1586   bool CanSink = true;
1587   const MachineOperand &MO = I.getOperand(0);
1588 
1589   for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
1590     LLVM_DEBUG(dbgs() << "CycleSink:   Analysing use: " << MI);
1591     if (!Cycle->contains(MI.getParent())) {
1592       LLVM_DEBUG(dbgs() << "CycleSink:   Use not in cycle, can't sink.\n");
1593       CanSink = false;
1594       break;
1595     }
1596 
1597     // FIXME: Come up with a proper cost model that estimates whether sinking
1598     // the instruction (and thus possibly executing it on every cycle
1599     // iteration) is more expensive than a register.
1600     // For now assumes that copies are cheap and thus almost always worth it.
1601     if (!MI.isCopy()) {
1602       LLVM_DEBUG(dbgs() << "CycleSink:   Use is not a copy\n");
1603       CanSink = false;
1604       break;
1605     }
1606     if (!SinkBlock) {
1607       SinkBlock = MI.getParent();
1608       LLVM_DEBUG(dbgs() << "CycleSink:   Setting sink block to: "
1609                         << printMBBReference(*SinkBlock) << "\n");
1610       continue;
1611     }
1612     SinkBlock = DT->findNearestCommonDominator(SinkBlock, MI.getParent());
1613     if (!SinkBlock) {
1614       LLVM_DEBUG(dbgs() << "CycleSink:   Can't find nearest dominator\n");
1615       CanSink = false;
1616       break;
1617     }
1618     LLVM_DEBUG(dbgs() << "CycleSink:   Setting nearest common dom block: "
1619                       << printMBBReference(*SinkBlock) << "\n");
1620   }
1621 
1622   if (!CanSink) {
1623     LLVM_DEBUG(dbgs() << "CycleSink: Can't sink instruction.\n");
1624     return false;
1625   }
1626   if (!SinkBlock) {
1627     LLVM_DEBUG(dbgs() << "CycleSink: Not sinking, can't find sink block.\n");
1628     return false;
1629   }
1630   if (SinkBlock == Preheader) {
1631     LLVM_DEBUG(
1632         dbgs() << "CycleSink: Not sinking, sink block is the preheader\n");
1633     return false;
1634   }
1635   if (SinkBlock->sizeWithoutDebugLargerThan(SinkLoadInstsPerBlockThreshold)) {
1636     LLVM_DEBUG(
1637         dbgs() << "CycleSink: Not Sinking, block too large to analyse.\n");
1638     return false;
1639   }
1640 
1641   LLVM_DEBUG(dbgs() << "CycleSink: Sinking instruction!\n");
1642   SinkBlock->splice(SinkBlock->SkipPHIsAndLabels(SinkBlock->begin()), Preheader,
1643                     I);
1644 
1645   // Conservatively clear any kill flags on uses of sunk instruction
1646   for (MachineOperand &MO : I.operands()) {
1647     if (MO.isReg() && MO.readsReg())
1648       RegsToClearKillFlags.insert(MO.getReg());
1649   }
1650 
1651   // The instruction is moved from its basic block, so do not retain the
1652   // debug information.
1653   assert(!I.isDebugInstr() && "Should not sink debug inst");
1654   I.setDebugLoc(DebugLoc());
1655   return true;
1656 }
1657 
1658 /// SinkInstruction - Determine whether it is safe to sink the specified machine
1659 /// instruction out of its current block into a successor.
1660 bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
1661                                      AllSuccsCache &AllSuccessors) {
1662   // Don't sink instructions that the target prefers not to sink.
1663   if (!TII->shouldSink(MI))
1664     return false;
1665 
1666   // Check if it's safe to move the instruction.
1667   if (!MI.isSafeToMove(SawStore))
1668     return false;
1669 
1670   // Convergent operations may not be made control-dependent on additional
1671   // values.
1672   if (MI.isConvergent())
1673     return false;
1674 
1675   // Don't break implicit null checks.  This is a performance heuristic, and not
1676   // required for correctness.
1677   if (SinkingPreventsImplicitNullCheck(MI, TII, TRI))
1678     return false;
1679 
1680   // FIXME: This should include support for sinking instructions within the
1681   // block they are currently in to shorten the live ranges.  We often get
1682   // instructions sunk into the top of a large block, but it would be better to
1683   // also sink them down before their first use in the block.  This xform has to
1684   // be careful not to *increase* register pressure though, e.g. sinking
1685   // "x = y + z" down if it kills y and z would increase the live ranges of y
1686   // and z and only shrink the live range of x.
1687 
1688   bool BreakPHIEdge = false;
1689   MachineBasicBlock *ParentBlock = MI.getParent();
1690   MachineBasicBlock *SuccToSinkTo =
1691       FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
1692 
1693   // If there are no outputs, it must have side-effects.
1694   if (!SuccToSinkTo)
1695     return false;
1696 
1697   // If the instruction to move defines a dead physical register which is live
1698   // when leaving the basic block, don't move it because it could turn into a
1699   // "zombie" define of that preg. E.g., EFLAGS.
1700   for (const MachineOperand &MO : MI.all_defs()) {
1701     Register Reg = MO.getReg();
1702     if (Reg == 0 || !Reg.isPhysical())
1703       continue;
1704     if (SuccToSinkTo->isLiveIn(Reg))
1705       return false;
1706   }
1707 
1708   LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
1709 
1710   // If the block has multiple predecessors, this is a critical edge.
1711   // Decide if we can sink along it or need to break the edge.
1712   if (SuccToSinkTo->pred_size() > 1) {
1713     // We cannot sink a load across a critical edge - there may be stores in
1714     // other code paths.
1715     bool TryBreak = false;
1716     bool Store =
1717         MI.mayLoad() ? hasStoreBetween(ParentBlock, SuccToSinkTo, MI) : true;
1718     if (!MI.isSafeToMove(Store)) {
1719       LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
1720       TryBreak = true;
1721     }
1722 
1723     // We don't want to sink across a critical edge if we don't dominate the
1724     // successor. We could be introducing calculations to new code paths.
1725     if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
1726       LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
1727       TryBreak = true;
1728     }
1729 
1730     // Don't sink instructions into a cycle.
1731     if (!TryBreak && CI->getCycle(SuccToSinkTo) &&
1732         (!CI->getCycle(SuccToSinkTo)->isReducible() ||
1733          CI->getCycle(SuccToSinkTo)->getHeader() == SuccToSinkTo)) {
1734       LLVM_DEBUG(dbgs() << " *** NOTE: cycle header found\n");
1735       TryBreak = true;
1736     }
1737 
1738     // Otherwise we are OK with sinking along a critical edge.
1739     if (!TryBreak)
1740       LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
1741     else {
1742       // Mark this edge as to be split.
1743       // If the edge can actually be split, the next iteration of the main loop
1744       // will sink MI in the newly created block.
1745       bool Status = PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo,
1746                                               BreakPHIEdge);
1747       if (!Status)
1748         LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
1749                              "break critical edge\n");
1750       // The instruction will not be sunk this time.
1751       return false;
1752     }
1753   }
1754 
1755   if (BreakPHIEdge) {
1756     // BreakPHIEdge is true if all the uses are in the successor MBB being
1757     // sunken into and they are all PHI nodes. In this case, machine-sink must
1758     // break the critical edge first.
1759     bool Status =
1760         PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
1761     if (!Status)
1762       LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
1763                            "break critical edge\n");
1764     // The instruction will not be sunk this time.
1765     return false;
1766   }
1767 
1768   // Determine where to insert into. Skip phi nodes.
1769   MachineBasicBlock::iterator InsertPos =
1770       SuccToSinkTo->SkipPHIsAndLabels(SuccToSinkTo->begin());
1771   if (blockPrologueInterferes(SuccToSinkTo, InsertPos, MI, TRI, TII, MRI)) {
1772     LLVM_DEBUG(dbgs() << " *** Not sinking: prologue interference\n");
1773     return false;
1774   }
1775 
1776   // Collect debug users of any vreg that this inst defines.
1777   SmallVector<MIRegs, 4> DbgUsersToSink;
1778   for (auto &MO : MI.all_defs()) {
1779     if (!MO.getReg().isVirtual())
1780       continue;
1781     if (!SeenDbgUsers.count(MO.getReg()))
1782       continue;
1783 
1784     // Sink any users that don't pass any other DBG_VALUEs for this variable.
1785     auto &Users = SeenDbgUsers[MO.getReg()];
1786     for (auto &User : Users) {
1787       MachineInstr *DbgMI = User.getPointer();
1788       if (User.getInt()) {
1789         // This DBG_VALUE would re-order assignments. If we can't copy-propagate
1790         // it, it can't be recovered. Set it undef.
1791         if (!attemptDebugCopyProp(MI, *DbgMI, MO.getReg()))
1792           DbgMI->setDebugValueUndef();
1793       } else {
1794         DbgUsersToSink.push_back(
1795             {DbgMI, SmallVector<unsigned, 2>(1, MO.getReg())});
1796       }
1797     }
1798   }
1799 
1800   // After sinking, some debug users may not be dominated any more. If possible,
1801   // copy-propagate their operands. As it's expensive, don't do this if there's
1802   // no debuginfo in the program.
1803   if (MI.getMF()->getFunction().getSubprogram() && MI.isCopy())
1804     SalvageUnsunkDebugUsersOfCopy(MI, SuccToSinkTo);
1805 
1806   performSink(MI, *SuccToSinkTo, InsertPos, DbgUsersToSink);
1807 
1808   // Conservatively, clear any kill flags, since it's possible that they are no
1809   // longer correct.
1810   // Note that we have to clear the kill flags for any register this instruction
1811   // uses as we may sink over another instruction which currently kills the
1812   // used registers.
1813   for (MachineOperand &MO : MI.all_uses())
1814     RegsToClearKillFlags.insert(MO.getReg()); // Remember to clear kill flags.
1815 
1816   return true;
1817 }
1818 
1819 void MachineSinking::SalvageUnsunkDebugUsersOfCopy(
1820     MachineInstr &MI, MachineBasicBlock *TargetBlock) {
1821   assert(MI.isCopy());
1822   assert(MI.getOperand(1).isReg());
1823 
1824   // Enumerate all users of vreg operands that are def'd. Skip those that will
1825   // be sunk. For the rest, if they are not dominated by the block we will sink
1826   // MI into, propagate the copy source to them.
1827   SmallVector<MachineInstr *, 4> DbgDefUsers;
1828   SmallVector<Register, 4> DbgUseRegs;
1829   const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1830   for (auto &MO : MI.all_defs()) {
1831     if (!MO.getReg().isVirtual())
1832       continue;
1833     DbgUseRegs.push_back(MO.getReg());
1834     for (auto &User : MRI.use_instructions(MO.getReg())) {
1835       if (!User.isDebugValue() || DT->dominates(TargetBlock, User.getParent()))
1836         continue;
1837 
1838       // If is in same block, will either sink or be use-before-def.
1839       if (User.getParent() == MI.getParent())
1840         continue;
1841 
1842       assert(User.hasDebugOperandForReg(MO.getReg()) &&
1843              "DBG_VALUE user of vreg, but has no operand for it?");
1844       DbgDefUsers.push_back(&User);
1845     }
1846   }
1847 
1848   // Point the users of this copy that are no longer dominated, at the source
1849   // of the copy.
1850   for (auto *User : DbgDefUsers) {
1851     for (auto &Reg : DbgUseRegs) {
1852       for (auto &DbgOp : User->getDebugOperandsForReg(Reg)) {
1853         DbgOp.setReg(MI.getOperand(1).getReg());
1854         DbgOp.setSubReg(MI.getOperand(1).getSubReg());
1855       }
1856     }
1857   }
1858 }
1859 
1860 //===----------------------------------------------------------------------===//
1861 // This pass is not intended to be a replacement or a complete alternative
1862 // for the pre-ra machine sink pass. It is only designed to sink COPY
1863 // instructions which should be handled after RA.
1864 //
1865 // This pass sinks COPY instructions into a successor block, if the COPY is not
1866 // used in the current block and the COPY is live-in to a single successor
1867 // (i.e., doesn't require the COPY to be duplicated).  This avoids executing the
1868 // copy on paths where their results aren't needed.  This also exposes
1869 // additional opportunites for dead copy elimination and shrink wrapping.
1870 //
1871 // These copies were either not handled by or are inserted after the MachineSink
1872 // pass. As an example of the former case, the MachineSink pass cannot sink
1873 // COPY instructions with allocatable source registers; for AArch64 these type
1874 // of copy instructions are frequently used to move function parameters (PhyReg)
1875 // into virtual registers in the entry block.
1876 //
1877 // For the machine IR below, this pass will sink %w19 in the entry into its
1878 // successor (%bb.1) because %w19 is only live-in in %bb.1.
1879 // %bb.0:
1880 //   %wzr = SUBSWri %w1, 1
1881 //   %w19 = COPY %w0
1882 //   Bcc 11, %bb.2
1883 // %bb.1:
1884 //   Live Ins: %w19
1885 //   BL @fun
1886 //   %w0 = ADDWrr %w0, %w19
1887 //   RET %w0
1888 // %bb.2:
1889 //   %w0 = COPY %wzr
1890 //   RET %w0
1891 // As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be
1892 // able to see %bb.0 as a candidate.
1893 //===----------------------------------------------------------------------===//
1894 namespace {
1895 
1896 class PostRAMachineSinking : public MachineFunctionPass {
1897 public:
1898   bool runOnMachineFunction(MachineFunction &MF) override;
1899 
1900   static char ID;
1901   PostRAMachineSinking() : MachineFunctionPass(ID) {}
1902   StringRef getPassName() const override { return "PostRA Machine Sink"; }
1903 
1904   void getAnalysisUsage(AnalysisUsage &AU) const override {
1905     AU.setPreservesCFG();
1906     MachineFunctionPass::getAnalysisUsage(AU);
1907   }
1908 
1909   MachineFunctionProperties getRequiredProperties() const override {
1910     return MachineFunctionProperties().set(
1911         MachineFunctionProperties::Property::NoVRegs);
1912   }
1913 
1914 private:
1915   /// Track which register units have been modified and used.
1916   LiveRegUnits ModifiedRegUnits, UsedRegUnits;
1917 
1918   /// Track DBG_VALUEs of (unmodified) register units. Each DBG_VALUE has an
1919   /// entry in this map for each unit it touches. The DBG_VALUE's entry
1920   /// consists of a pointer to the instruction itself, and a vector of registers
1921   /// referred to by the instruction that overlap the key register unit.
1922   DenseMap<unsigned, SmallVector<MIRegs, 2>> SeenDbgInstrs;
1923 
1924   /// Sink Copy instructions unused in the same block close to their uses in
1925   /// successors.
1926   bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF,
1927                      const TargetRegisterInfo *TRI, const TargetInstrInfo *TII);
1928 };
1929 } // namespace
1930 
1931 char PostRAMachineSinking::ID = 0;
1932 char &llvm::PostRAMachineSinkingID = PostRAMachineSinking::ID;
1933 
1934 INITIALIZE_PASS(PostRAMachineSinking, "postra-machine-sink",
1935                 "PostRA Machine Sink", false, false)
1936 
1937 static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, unsigned Reg,
1938                                   const TargetRegisterInfo *TRI) {
1939   LiveRegUnits LiveInRegUnits(*TRI);
1940   LiveInRegUnits.addLiveIns(MBB);
1941   return !LiveInRegUnits.available(Reg);
1942 }
1943 
1944 static MachineBasicBlock *
1945 getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
1946                       const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
1947                       unsigned Reg, const TargetRegisterInfo *TRI) {
1948   // Try to find a single sinkable successor in which Reg is live-in.
1949   MachineBasicBlock *BB = nullptr;
1950   for (auto *SI : SinkableBBs) {
1951     if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) {
1952       // If BB is set here, Reg is live-in to at least two sinkable successors,
1953       // so quit.
1954       if (BB)
1955         return nullptr;
1956       BB = SI;
1957     }
1958   }
1959   // Reg is not live-in to any sinkable successors.
1960   if (!BB)
1961     return nullptr;
1962 
1963   // Check if any register aliased with Reg is live-in in other successors.
1964   for (auto *SI : CurBB.successors()) {
1965     if (!SinkableBBs.count(SI) && aliasWithRegsInLiveIn(*SI, Reg, TRI))
1966       return nullptr;
1967   }
1968   return BB;
1969 }
1970 
1971 static MachineBasicBlock *
1972 getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
1973                       const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
1974                       ArrayRef<unsigned> DefedRegsInCopy,
1975                       const TargetRegisterInfo *TRI) {
1976   MachineBasicBlock *SingleBB = nullptr;
1977   for (auto DefReg : DefedRegsInCopy) {
1978     MachineBasicBlock *BB =
1979         getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI);
1980     if (!BB || (SingleBB && SingleBB != BB))
1981       return nullptr;
1982     SingleBB = BB;
1983   }
1984   return SingleBB;
1985 }
1986 
1987 static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB,
1988                            SmallVectorImpl<unsigned> &UsedOpsInCopy,
1989                            LiveRegUnits &UsedRegUnits,
1990                            const TargetRegisterInfo *TRI) {
1991   for (auto U : UsedOpsInCopy) {
1992     MachineOperand &MO = MI->getOperand(U);
1993     Register SrcReg = MO.getReg();
1994     if (!UsedRegUnits.available(SrcReg)) {
1995       MachineBasicBlock::iterator NI = std::next(MI->getIterator());
1996       for (MachineInstr &UI : make_range(NI, CurBB.end())) {
1997         if (UI.killsRegister(SrcReg, TRI)) {
1998           UI.clearRegisterKills(SrcReg, TRI);
1999           MO.setIsKill(true);
2000           break;
2001         }
2002       }
2003     }
2004   }
2005 }
2006 
2007 static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB,
2008                          SmallVectorImpl<unsigned> &UsedOpsInCopy,
2009                          SmallVectorImpl<unsigned> &DefedRegsInCopy) {
2010   MachineFunction &MF = *SuccBB->getParent();
2011   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2012   for (unsigned DefReg : DefedRegsInCopy)
2013     for (MCPhysReg S : TRI->subregs_inclusive(DefReg))
2014       SuccBB->removeLiveIn(S);
2015   for (auto U : UsedOpsInCopy)
2016     SuccBB->addLiveIn(MI->getOperand(U).getReg());
2017   SuccBB->sortUniqueLiveIns();
2018 }
2019 
2020 static bool hasRegisterDependency(MachineInstr *MI,
2021                                   SmallVectorImpl<unsigned> &UsedOpsInCopy,
2022                                   SmallVectorImpl<unsigned> &DefedRegsInCopy,
2023                                   LiveRegUnits &ModifiedRegUnits,
2024                                   LiveRegUnits &UsedRegUnits) {
2025   bool HasRegDependency = false;
2026   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2027     MachineOperand &MO = MI->getOperand(i);
2028     if (!MO.isReg())
2029       continue;
2030     Register Reg = MO.getReg();
2031     if (!Reg)
2032       continue;
2033     if (MO.isDef()) {
2034       if (!ModifiedRegUnits.available(Reg) || !UsedRegUnits.available(Reg)) {
2035         HasRegDependency = true;
2036         break;
2037       }
2038       DefedRegsInCopy.push_back(Reg);
2039 
2040       // FIXME: instead of isUse(), readsReg() would be a better fix here,
2041       // For example, we can ignore modifications in reg with undef. However,
2042       // it's not perfectly clear if skipping the internal read is safe in all
2043       // other targets.
2044     } else if (MO.isUse()) {
2045       if (!ModifiedRegUnits.available(Reg)) {
2046         HasRegDependency = true;
2047         break;
2048       }
2049       UsedOpsInCopy.push_back(i);
2050     }
2051   }
2052   return HasRegDependency;
2053 }
2054 
2055 bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock &CurBB,
2056                                          MachineFunction &MF,
2057                                          const TargetRegisterInfo *TRI,
2058                                          const TargetInstrInfo *TII) {
2059   SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs;
2060   // FIXME: For now, we sink only to a successor which has a single predecessor
2061   // so that we can directly sink COPY instructions to the successor without
2062   // adding any new block or branch instruction.
2063   for (MachineBasicBlock *SI : CurBB.successors())
2064     if (!SI->livein_empty() && SI->pred_size() == 1)
2065       SinkableBBs.insert(SI);
2066 
2067   if (SinkableBBs.empty())
2068     return false;
2069 
2070   bool Changed = false;
2071 
2072   // Track which registers have been modified and used between the end of the
2073   // block and the current instruction.
2074   ModifiedRegUnits.clear();
2075   UsedRegUnits.clear();
2076   SeenDbgInstrs.clear();
2077 
2078   for (MachineInstr &MI : llvm::make_early_inc_range(llvm::reverse(CurBB))) {
2079     // Track the operand index for use in Copy.
2080     SmallVector<unsigned, 2> UsedOpsInCopy;
2081     // Track the register number defed in Copy.
2082     SmallVector<unsigned, 2> DefedRegsInCopy;
2083 
2084     // We must sink this DBG_VALUE if its operand is sunk. To avoid searching
2085     // for DBG_VALUEs later, record them when they're encountered.
2086     if (MI.isDebugValue() && !MI.isDebugRef()) {
2087       SmallDenseMap<MCRegister, SmallVector<unsigned, 2>, 4> MIUnits;
2088       bool IsValid = true;
2089       for (MachineOperand &MO : MI.debug_operands()) {
2090         if (MO.isReg() && MO.getReg().isPhysical()) {
2091           // Bail if we can already tell the sink would be rejected, rather
2092           // than needlessly accumulating lots of DBG_VALUEs.
2093           if (hasRegisterDependency(&MI, UsedOpsInCopy, DefedRegsInCopy,
2094                                     ModifiedRegUnits, UsedRegUnits)) {
2095             IsValid = false;
2096             break;
2097           }
2098 
2099           // Record debug use of each reg unit.
2100           for (MCRegUnit Unit : TRI->regunits(MO.getReg()))
2101             MIUnits[Unit].push_back(MO.getReg());
2102         }
2103       }
2104       if (IsValid) {
2105         for (auto &RegOps : MIUnits)
2106           SeenDbgInstrs[RegOps.first].emplace_back(&MI,
2107                                                    std::move(RegOps.second));
2108       }
2109       continue;
2110     }
2111 
2112     if (MI.isDebugOrPseudoInstr())
2113       continue;
2114 
2115     // Do not move any instruction across function call.
2116     if (MI.isCall())
2117       return false;
2118 
2119     if (!MI.isCopy() || !MI.getOperand(0).isRenamable()) {
2120       LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2121                                         TRI);
2122       continue;
2123     }
2124 
2125     // Don't sink the COPY if it would violate a register dependency.
2126     if (hasRegisterDependency(&MI, UsedOpsInCopy, DefedRegsInCopy,
2127                               ModifiedRegUnits, UsedRegUnits)) {
2128       LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2129                                         TRI);
2130       continue;
2131     }
2132     assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) &&
2133            "Unexpect SrcReg or DefReg");
2134     MachineBasicBlock *SuccBB =
2135         getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI);
2136     // Don't sink if we cannot find a single sinkable successor in which Reg
2137     // is live-in.
2138     if (!SuccBB) {
2139       LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2140                                         TRI);
2141       continue;
2142     }
2143     assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) &&
2144            "Unexpected predecessor");
2145 
2146     // Collect DBG_VALUEs that must sink with this copy. We've previously
2147     // recorded which reg units that DBG_VALUEs read, if this instruction
2148     // writes any of those units then the corresponding DBG_VALUEs must sink.
2149     MapVector<MachineInstr *, MIRegs::second_type> DbgValsToSinkMap;
2150     for (auto &MO : MI.all_defs()) {
2151       for (MCRegUnit Unit : TRI->regunits(MO.getReg())) {
2152         for (const auto &MIRegs : SeenDbgInstrs.lookup(Unit)) {
2153           auto &Regs = DbgValsToSinkMap[MIRegs.first];
2154           for (unsigned Reg : MIRegs.second)
2155             Regs.push_back(Reg);
2156         }
2157       }
2158     }
2159     auto DbgValsToSink = DbgValsToSinkMap.takeVector();
2160 
2161     LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccBB);
2162 
2163     MachineBasicBlock::iterator InsertPos =
2164         SuccBB->SkipPHIsAndLabels(SuccBB->begin());
2165     if (blockPrologueInterferes(SuccBB, InsertPos, MI, TRI, TII, nullptr)) {
2166       LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2167                                         TRI);
2168       LLVM_DEBUG(dbgs() << " *** Not sinking: prologue interference\n");
2169       continue;
2170     }
2171 
2172     // Clear the kill flag if SrcReg is killed between MI and the end of the
2173     // block.
2174     clearKillFlags(&MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI);
2175     performSink(MI, *SuccBB, InsertPos, DbgValsToSink);
2176     updateLiveIn(&MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy);
2177 
2178     Changed = true;
2179     ++NumPostRACopySink;
2180   }
2181   return Changed;
2182 }
2183 
2184 bool PostRAMachineSinking::runOnMachineFunction(MachineFunction &MF) {
2185   if (skipFunction(MF.getFunction()))
2186     return false;
2187 
2188   bool Changed = false;
2189   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2190   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
2191 
2192   ModifiedRegUnits.init(*TRI);
2193   UsedRegUnits.init(*TRI);
2194   for (auto &BB : MF)
2195     Changed |= tryToSinkCopy(BB, MF, TRI, TII);
2196 
2197   return Changed;
2198 }
2199