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