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