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