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