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