xref: /llvm-project/llvm/lib/CodeGen/MachineSink.cpp (revision f5e1b718a675a4449b71423f04d38e1e93045105)
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/SetVector.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/SparseBitVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineBasicBlock.h"
25 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
26 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
27 #include "llvm/CodeGen/MachineDominators.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineLoopInfo.h"
32 #include "llvm/CodeGen/MachineOperand.h"
33 #include "llvm/CodeGen/MachinePostDominators.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/TargetInstrInfo.h"
36 #include "llvm/CodeGen/TargetRegisterInfo.h"
37 #include "llvm/CodeGen/TargetSubtargetInfo.h"
38 #include "llvm/IR/BasicBlock.h"
39 #include "llvm/IR/DebugInfoMetadata.h"
40 #include "llvm/IR/LLVMContext.h"
41 #include "llvm/MC/MCRegisterInfo.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/BranchProbability.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include <algorithm>
48 #include <cassert>
49 #include <cstdint>
50 #include <map>
51 #include <utility>
52 #include <vector>
53 
54 using namespace llvm;
55 
56 #define DEBUG_TYPE "machine-sink"
57 
58 static cl::opt<bool>
59 SplitEdges("machine-sink-split",
60            cl::desc("Split critical edges during machine sinking"),
61            cl::init(true), cl::Hidden);
62 
63 static cl::opt<bool>
64 UseBlockFreqInfo("machine-sink-bfi",
65            cl::desc("Use block frequency info to find successors to sink"),
66            cl::init(true), cl::Hidden);
67 
68 static cl::opt<unsigned> SplitEdgeProbabilityThreshold(
69     "machine-sink-split-probability-threshold",
70     cl::desc(
71         "Percentage threshold for splitting single-instruction critical edge. "
72         "If the branch threshold is higher than this threshold, we allow "
73         "speculative execution of up to 1 instruction to avoid branching to "
74         "splitted critical edge"),
75     cl::init(40), cl::Hidden);
76 
77 STATISTIC(NumSunk,      "Number of machine instructions sunk");
78 STATISTIC(NumSplit,     "Number of critical edges split");
79 STATISTIC(NumCoalesces, "Number of copies coalesced");
80 STATISTIC(NumPostRACopySink, "Number of copies sunk after RA");
81 
82 namespace {
83 
84   class MachineSinking : public MachineFunctionPass {
85     const TargetInstrInfo *TII;
86     const TargetRegisterInfo *TRI;
87     MachineRegisterInfo  *MRI;     // Machine register information
88     MachineDominatorTree *DT;      // Machine dominator tree
89     MachinePostDominatorTree *PDT; // Machine post dominator tree
90     MachineLoopInfo *LI;
91     const MachineBlockFrequencyInfo *MBFI;
92     const MachineBranchProbabilityInfo *MBPI;
93     AliasAnalysis *AA;
94 
95     // Remember which edges have been considered for breaking.
96     SmallSet<std::pair<MachineBasicBlock*, MachineBasicBlock*>, 8>
97     CEBCandidates;
98     // Remember which edges we are about to split.
99     // This is different from CEBCandidates since those edges
100     // will be split.
101     SetVector<std::pair<MachineBasicBlock *, MachineBasicBlock *>> ToSplit;
102 
103     SparseBitVector<> RegsToClearKillFlags;
104 
105     using AllSuccsCache =
106         std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>;
107 
108     // Remember debug uses of vregs seen, so we know what to sink out of blocks.
109     DenseMap<unsigned, TinyPtrVector<MachineInstr *>> SeenDbgUsers;
110 
111   public:
112     static char ID; // Pass identification
113 
114     MachineSinking() : MachineFunctionPass(ID) {
115       initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
116     }
117 
118     bool runOnMachineFunction(MachineFunction &MF) override;
119 
120     void getAnalysisUsage(AnalysisUsage &AU) const override {
121       MachineFunctionPass::getAnalysisUsage(AU);
122       AU.addRequired<AAResultsWrapperPass>();
123       AU.addRequired<MachineDominatorTree>();
124       AU.addRequired<MachinePostDominatorTree>();
125       AU.addRequired<MachineLoopInfo>();
126       AU.addRequired<MachineBranchProbabilityInfo>();
127       AU.addPreserved<MachineLoopInfo>();
128       if (UseBlockFreqInfo)
129         AU.addRequired<MachineBlockFrequencyInfo>();
130     }
131 
132     void releaseMemory() override {
133       CEBCandidates.clear();
134     }
135 
136   private:
137     bool ProcessBlock(MachineBasicBlock &MBB);
138     void ProcessDbgInst(MachineInstr &MI);
139     bool isWorthBreakingCriticalEdge(MachineInstr &MI,
140                                      MachineBasicBlock *From,
141                                      MachineBasicBlock *To);
142 
143     /// Postpone the splitting of the given critical
144     /// edge (\p From, \p To).
145     ///
146     /// We do not split the edges on the fly. Indeed, this invalidates
147     /// the dominance information and thus triggers a lot of updates
148     /// of that information underneath.
149     /// Instead, we postpone all the splits after each iteration of
150     /// the main loop. That way, the information is at least valid
151     /// for the lifetime of an iteration.
152     ///
153     /// \return True if the edge is marked as toSplit, false otherwise.
154     /// False can be returned if, for instance, this is not profitable.
155     bool PostponeSplitCriticalEdge(MachineInstr &MI,
156                                    MachineBasicBlock *From,
157                                    MachineBasicBlock *To,
158                                    bool BreakPHIEdge);
159     bool SinkInstruction(MachineInstr &MI, bool &SawStore,
160                          AllSuccsCache &AllSuccessors);
161 
162     /// If we sink a COPY inst, some debug users of it's destination may no
163     /// longer be dominated by the COPY, and will eventually be dropped.
164     /// This is easily rectified by forwarding the non-dominated debug uses
165     /// to the copy source.
166     void SalvageUnsunkDebugUsersOfCopy(MachineInstr &,
167                                        MachineBasicBlock *TargetBlock);
168     bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
169                                  MachineBasicBlock *DefMBB,
170                                  bool &BreakPHIEdge, bool &LocalUse) const;
171     MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
172                bool &BreakPHIEdge, AllSuccsCache &AllSuccessors);
173     bool isProfitableToSinkTo(unsigned Reg, MachineInstr &MI,
174                               MachineBasicBlock *MBB,
175                               MachineBasicBlock *SuccToSinkTo,
176                               AllSuccsCache &AllSuccessors);
177 
178     bool PerformTrivialForwardCoalescing(MachineInstr &MI,
179                                          MachineBasicBlock *MBB);
180 
181     SmallVector<MachineBasicBlock *, 4> &
182     GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
183                            AllSuccsCache &AllSuccessors) const;
184   };
185 
186 } // end anonymous namespace
187 
188 char MachineSinking::ID = 0;
189 
190 char &llvm::MachineSinkingID = MachineSinking::ID;
191 
192 INITIALIZE_PASS_BEGIN(MachineSinking, DEBUG_TYPE,
193                       "Machine code sinking", false, false)
194 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
195 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
196 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
197 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
198 INITIALIZE_PASS_END(MachineSinking, DEBUG_TYPE,
199                     "Machine code sinking", false, false)
200 
201 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI,
202                                                      MachineBasicBlock *MBB) {
203   if (!MI.isCopy())
204     return false;
205 
206   Register SrcReg = MI.getOperand(1).getReg();
207   Register DstReg = MI.getOperand(0).getReg();
208   if (!Register::isVirtualRegister(SrcReg) ||
209       !Register::isVirtualRegister(DstReg) || !MRI->hasOneNonDBGUse(SrcReg))
210     return false;
211 
212   const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
213   const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
214   if (SRC != DRC)
215     return false;
216 
217   MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
218   if (DefMI->isCopyLike())
219     return false;
220   LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
221   LLVM_DEBUG(dbgs() << "*** to: " << MI);
222   MRI->replaceRegWith(DstReg, SrcReg);
223   MI.eraseFromParent();
224 
225   // Conservatively, clear any kill flags, since it's possible that they are no
226   // longer correct.
227   MRI->clearKillFlags(SrcReg);
228 
229   ++NumCoalesces;
230   return true;
231 }
232 
233 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
234 /// occur in blocks dominated by the specified block. If any use is in the
235 /// definition block, then return false since it is never legal to move def
236 /// after uses.
237 bool
238 MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
239                                         MachineBasicBlock *MBB,
240                                         MachineBasicBlock *DefMBB,
241                                         bool &BreakPHIEdge,
242                                         bool &LocalUse) const {
243   assert(Register::isVirtualRegister(Reg) && "Only makes sense for vregs");
244 
245   // Ignore debug uses because debug info doesn't affect the code.
246   if (MRI->use_nodbg_empty(Reg))
247     return true;
248 
249   // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
250   // into and they are all PHI nodes. In this case, machine-sink must break
251   // the critical edge first. e.g.
252   //
253   // %bb.1: derived from LLVM BB %bb4.preheader
254   //   Predecessors according to CFG: %bb.0
255   //     ...
256   //     %reg16385 = DEC64_32r %reg16437, implicit-def dead %eflags
257   //     ...
258   //     JE_4 <%bb.37>, implicit %eflags
259   //   Successors according to CFG: %bb.37 %bb.2
260   //
261   // %bb.2: derived from LLVM BB %bb.nph
262   //   Predecessors according to CFG: %bb.0 %bb.1
263   //     %reg16386 = PHI %reg16434, %bb.0, %reg16385, %bb.1
264   BreakPHIEdge = true;
265   for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
266     MachineInstr *UseInst = MO.getParent();
267     unsigned OpNo = &MO - &UseInst->getOperand(0);
268     MachineBasicBlock *UseBlock = UseInst->getParent();
269     if (!(UseBlock == MBB && UseInst->isPHI() &&
270           UseInst->getOperand(OpNo+1).getMBB() == DefMBB)) {
271       BreakPHIEdge = false;
272       break;
273     }
274   }
275   if (BreakPHIEdge)
276     return true;
277 
278   for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
279     // Determine the block of the use.
280     MachineInstr *UseInst = MO.getParent();
281     unsigned OpNo = &MO - &UseInst->getOperand(0);
282     MachineBasicBlock *UseBlock = UseInst->getParent();
283     if (UseInst->isPHI()) {
284       // PHI nodes use the operand in the predecessor block, not the block with
285       // the PHI.
286       UseBlock = UseInst->getOperand(OpNo+1).getMBB();
287     } else if (UseBlock == DefMBB) {
288       LocalUse = true;
289       return false;
290     }
291 
292     // Check that it dominates.
293     if (!DT->dominates(MBB, UseBlock))
294       return false;
295   }
296 
297   return true;
298 }
299 
300 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
301   if (skipFunction(MF.getFunction()))
302     return false;
303 
304   LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n");
305 
306   TII = MF.getSubtarget().getInstrInfo();
307   TRI = MF.getSubtarget().getRegisterInfo();
308   MRI = &MF.getRegInfo();
309   DT = &getAnalysis<MachineDominatorTree>();
310   PDT = &getAnalysis<MachinePostDominatorTree>();
311   LI = &getAnalysis<MachineLoopInfo>();
312   MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr;
313   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
314   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
315 
316   bool EverMadeChange = false;
317 
318   while (true) {
319     bool MadeChange = false;
320 
321     // Process all basic blocks.
322     CEBCandidates.clear();
323     ToSplit.clear();
324     for (auto &MBB: MF)
325       MadeChange |= ProcessBlock(MBB);
326 
327     // If we have anything we marked as toSplit, split it now.
328     for (auto &Pair : ToSplit) {
329       auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this);
330       if (NewSucc != nullptr) {
331         LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "
332                           << printMBBReference(*Pair.first) << " -- "
333                           << printMBBReference(*NewSucc) << " -- "
334                           << printMBBReference(*Pair.second) << '\n');
335         MadeChange = true;
336         ++NumSplit;
337       } else
338         LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n");
339     }
340     // If this iteration over the code changed anything, keep iterating.
341     if (!MadeChange) break;
342     EverMadeChange = true;
343   }
344 
345   // Now clear any kill flags for recorded registers.
346   for (auto I : RegsToClearKillFlags)
347     MRI->clearKillFlags(I);
348   RegsToClearKillFlags.clear();
349 
350   return EverMadeChange;
351 }
352 
353 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
354   // Can't sink anything out of a block that has less than two successors.
355   if (MBB.succ_size() <= 1 || MBB.empty()) return false;
356 
357   // Don't bother sinking code out of unreachable blocks. In addition to being
358   // unprofitable, it can also lead to infinite looping, because in an
359   // unreachable loop there may be nowhere to stop.
360   if (!DT->isReachableFromEntry(&MBB)) return false;
361 
362   bool MadeChange = false;
363 
364   // Cache all successors, sorted by frequency info and loop depth.
365   AllSuccsCache AllSuccessors;
366 
367   // Walk the basic block bottom-up.  Remember if we saw a store.
368   MachineBasicBlock::iterator I = MBB.end();
369   --I;
370   bool ProcessedBegin, SawStore = false;
371   do {
372     MachineInstr &MI = *I;  // The instruction to sink.
373 
374     // Predecrement I (if it's not begin) so that it isn't invalidated by
375     // sinking.
376     ProcessedBegin = I == MBB.begin();
377     if (!ProcessedBegin)
378       --I;
379 
380     if (MI.isDebugInstr()) {
381       if (MI.isDebugValue())
382         ProcessDbgInst(MI);
383       continue;
384     }
385 
386     bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
387     if (Joined) {
388       MadeChange = true;
389       continue;
390     }
391 
392     if (SinkInstruction(MI, SawStore, AllSuccessors)) {
393       ++NumSunk;
394       MadeChange = true;
395     }
396 
397     // If we just processed the first instruction in the block, we're done.
398   } while (!ProcessedBegin);
399 
400   SeenDbgUsers.clear();
401 
402   return MadeChange;
403 }
404 
405 void MachineSinking::ProcessDbgInst(MachineInstr &MI) {
406   // When we see DBG_VALUEs for registers, record any vreg it reads, so that
407   // we know what to sink if the vreg def sinks.
408   assert(MI.isDebugValue() && "Expected DBG_VALUE for processing");
409 
410   MachineOperand &MO = MI.getOperand(0);
411   if (!MO.isReg() || !MO.getReg().isVirtual())
412     return;
413 
414   SeenDbgUsers[MO.getReg()].push_back(&MI);
415 }
416 
417 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr &MI,
418                                                  MachineBasicBlock *From,
419                                                  MachineBasicBlock *To) {
420   // FIXME: Need much better heuristics.
421 
422   // If the pass has already considered breaking this edge (during this pass
423   // through the function), then let's go ahead and break it. This means
424   // sinking multiple "cheap" instructions into the same block.
425   if (!CEBCandidates.insert(std::make_pair(From, To)).second)
426     return true;
427 
428   if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI))
429     return true;
430 
431   if (From->isSuccessor(To) && MBPI->getEdgeProbability(From, To) <=
432       BranchProbability(SplitEdgeProbabilityThreshold, 100))
433     return true;
434 
435   // MI is cheap, we probably don't want to break the critical edge for it.
436   // However, if this would allow some definitions of its source operands
437   // to be sunk then it's probably worth it.
438   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
439     const MachineOperand &MO = MI.getOperand(i);
440     if (!MO.isReg() || !MO.isUse())
441       continue;
442     Register Reg = MO.getReg();
443     if (Reg == 0)
444       continue;
445 
446     // We don't move live definitions of physical registers,
447     // so sinking their uses won't enable any opportunities.
448     if (Register::isPhysicalRegister(Reg))
449       continue;
450 
451     // If this instruction is the only user of a virtual register,
452     // check if breaking the edge will enable sinking
453     // both this instruction and the defining instruction.
454     if (MRI->hasOneNonDBGUse(Reg)) {
455       // If the definition resides in same MBB,
456       // claim it's likely we can sink these together.
457       // If definition resides elsewhere, we aren't
458       // blocking it from being sunk so don't break the edge.
459       MachineInstr *DefMI = MRI->getVRegDef(Reg);
460       if (DefMI->getParent() == MI.getParent())
461         return true;
462     }
463   }
464 
465   return false;
466 }
467 
468 bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
469                                                MachineBasicBlock *FromBB,
470                                                MachineBasicBlock *ToBB,
471                                                bool BreakPHIEdge) {
472   if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
473     return false;
474 
475   // Avoid breaking back edge. From == To means backedge for single BB loop.
476   if (!SplitEdges || FromBB == ToBB)
477     return false;
478 
479   // Check for backedges of more "complex" loops.
480   if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
481       LI->isLoopHeader(ToBB))
482     return false;
483 
484   // It's not always legal to break critical edges and sink the computation
485   // to the edge.
486   //
487   // %bb.1:
488   // v1024
489   // Beq %bb.3
490   // <fallthrough>
491   // %bb.2:
492   // ... no uses of v1024
493   // <fallthrough>
494   // %bb.3:
495   // ...
496   //       = v1024
497   //
498   // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted:
499   //
500   // %bb.1:
501   // ...
502   // Bne %bb.2
503   // %bb.4:
504   // v1024 =
505   // B %bb.3
506   // %bb.2:
507   // ... no uses of v1024
508   // <fallthrough>
509   // %bb.3:
510   // ...
511   //       = v1024
512   //
513   // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3
514   // flow. We need to ensure the new basic block where the computation is
515   // sunk to dominates all the uses.
516   // It's only legal to break critical edge and sink the computation to the
517   // new block if all the predecessors of "To", except for "From", are
518   // not dominated by "From". Given SSA property, this means these
519   // predecessors are dominated by "To".
520   //
521   // There is no need to do this check if all the uses are PHI nodes. PHI
522   // sources are only defined on the specific predecessor edges.
523   if (!BreakPHIEdge) {
524     for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
525            E = ToBB->pred_end(); PI != E; ++PI) {
526       if (*PI == FromBB)
527         continue;
528       if (!DT->dominates(ToBB, *PI))
529         return false;
530     }
531   }
532 
533   ToSplit.insert(std::make_pair(FromBB, ToBB));
534 
535   return true;
536 }
537 
538 /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
539 bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr &MI,
540                                           MachineBasicBlock *MBB,
541                                           MachineBasicBlock *SuccToSinkTo,
542                                           AllSuccsCache &AllSuccessors) {
543   assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
544 
545   if (MBB == SuccToSinkTo)
546     return false;
547 
548   // It is profitable if SuccToSinkTo does not post dominate current block.
549   if (!PDT->dominates(SuccToSinkTo, MBB))
550     return true;
551 
552   // It is profitable to sink an instruction from a deeper loop to a shallower
553   // loop, even if the latter post-dominates the former (PR21115).
554   if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo))
555     return true;
556 
557   // Check if only use in post dominated block is PHI instruction.
558   bool NonPHIUse = false;
559   for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
560     MachineBasicBlock *UseBlock = UseInst.getParent();
561     if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
562       NonPHIUse = true;
563   }
564   if (!NonPHIUse)
565     return true;
566 
567   // If SuccToSinkTo post dominates then also it may be profitable if MI
568   // can further profitably sinked into another block in next round.
569   bool BreakPHIEdge = false;
570   // FIXME - If finding successor is compile time expensive then cache results.
571   if (MachineBasicBlock *MBB2 =
572           FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
573     return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
574 
575   // If SuccToSinkTo is final destination and it is a post dominator of current
576   // block then it is not profitable to sink MI into SuccToSinkTo block.
577   return false;
578 }
579 
580 /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
581 /// computing it if it was not already cached.
582 SmallVector<MachineBasicBlock *, 4> &
583 MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
584                                        AllSuccsCache &AllSuccessors) const {
585   // Do we have the sorted successors in cache ?
586   auto Succs = AllSuccessors.find(MBB);
587   if (Succs != AllSuccessors.end())
588     return Succs->second;
589 
590   SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->succ_begin(),
591                                                MBB->succ_end());
592 
593   // Handle cases where sinking can happen but where the sink point isn't a
594   // successor. For example:
595   //
596   //   x = computation
597   //   if () {} else {}
598   //   use x
599   //
600   const std::vector<MachineDomTreeNode *> &Children =
601     DT->getNode(MBB)->getChildren();
602   for (const auto &DTChild : Children)
603     // DomTree children of MBB that have MBB as immediate dominator are added.
604     if (DTChild->getIDom()->getBlock() == MI.getParent() &&
605         // Skip MBBs already added to the AllSuccs vector above.
606         !MBB->isSuccessor(DTChild->getBlock()))
607       AllSuccs.push_back(DTChild->getBlock());
608 
609   // Sort Successors according to their loop depth or block frequency info.
610   llvm::stable_sort(
611       AllSuccs, [this](const MachineBasicBlock *L, const MachineBasicBlock *R) {
612         uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
613         uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
614         bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0;
615         return HasBlockFreq ? LHSFreq < RHSFreq
616                             : LI->getLoopDepth(L) < LI->getLoopDepth(R);
617       });
618 
619   auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
620 
621   return it.first->second;
622 }
623 
624 /// FindSuccToSinkTo - Find a successor to sink this instruction to.
625 MachineBasicBlock *
626 MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
627                                  bool &BreakPHIEdge,
628                                  AllSuccsCache &AllSuccessors) {
629   assert (MBB && "Invalid MachineBasicBlock!");
630 
631   // Loop over all the operands of the specified instruction.  If there is
632   // anything we can't handle, bail out.
633 
634   // SuccToSinkTo - This is the successor to sink this instruction to, once we
635   // decide.
636   MachineBasicBlock *SuccToSinkTo = nullptr;
637   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
638     const MachineOperand &MO = MI.getOperand(i);
639     if (!MO.isReg()) continue;  // Ignore non-register operands.
640 
641     Register Reg = MO.getReg();
642     if (Reg == 0) continue;
643 
644     if (Register::isPhysicalRegister(Reg)) {
645       if (MO.isUse()) {
646         // If the physreg has no defs anywhere, it's just an ambient register
647         // and we can freely move its uses. Alternatively, if it's allocatable,
648         // it could get allocated to something with a def during allocation.
649         if (!MRI->isConstantPhysReg(Reg))
650           return nullptr;
651       } else if (!MO.isDead()) {
652         // A def that isn't dead. We can't move it.
653         return nullptr;
654       }
655     } else {
656       // Virtual register uses are always safe to sink.
657       if (MO.isUse()) continue;
658 
659       // If it's not safe to move defs of the register class, then abort.
660       if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
661         return nullptr;
662 
663       // Virtual register defs can only be sunk if all their uses are in blocks
664       // dominated by one of the successors.
665       if (SuccToSinkTo) {
666         // If a previous operand picked a block to sink to, then this operand
667         // must be sinkable to the same block.
668         bool LocalUse = false;
669         if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
670                                      BreakPHIEdge, LocalUse))
671           return nullptr;
672 
673         continue;
674       }
675 
676       // Otherwise, we should look at all the successors and decide which one
677       // we should sink to. If we have reliable block frequency information
678       // (frequency != 0) available, give successors with smaller frequencies
679       // higher priority, otherwise prioritize smaller loop depths.
680       for (MachineBasicBlock *SuccBlock :
681            GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
682         bool LocalUse = false;
683         if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
684                                     BreakPHIEdge, LocalUse)) {
685           SuccToSinkTo = SuccBlock;
686           break;
687         }
688         if (LocalUse)
689           // Def is used locally, it's never safe to move this def.
690           return nullptr;
691       }
692 
693       // If we couldn't find a block to sink to, ignore this instruction.
694       if (!SuccToSinkTo)
695         return nullptr;
696       if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
697         return nullptr;
698     }
699   }
700 
701   // It is not possible to sink an instruction into its own block.  This can
702   // happen with loops.
703   if (MBB == SuccToSinkTo)
704     return nullptr;
705 
706   // It's not safe to sink instructions to EH landing pad. Control flow into
707   // landing pad is implicitly defined.
708   if (SuccToSinkTo && SuccToSinkTo->isEHPad())
709     return nullptr;
710 
711   return SuccToSinkTo;
712 }
713 
714 /// Return true if MI is likely to be usable as a memory operation by the
715 /// implicit null check optimization.
716 ///
717 /// This is a "best effort" heuristic, and should not be relied upon for
718 /// correctness.  This returning true does not guarantee that the implicit null
719 /// check optimization is legal over MI, and this returning false does not
720 /// guarantee MI cannot possibly be used to do a null check.
721 static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI,
722                                              const TargetInstrInfo *TII,
723                                              const TargetRegisterInfo *TRI) {
724   using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
725 
726   auto *MBB = MI.getParent();
727   if (MBB->pred_size() != 1)
728     return false;
729 
730   auto *PredMBB = *MBB->pred_begin();
731   auto *PredBB = PredMBB->getBasicBlock();
732 
733   // Frontends that don't use implicit null checks have no reason to emit
734   // branches with make.implicit metadata, and this function should always
735   // return false for them.
736   if (!PredBB ||
737       !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
738     return false;
739 
740   const MachineOperand *BaseOp;
741   int64_t Offset;
742   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, TRI))
743     return false;
744 
745   if (!BaseOp->isReg())
746     return false;
747 
748   if (!(MI.mayLoad() && !MI.isPredicable()))
749     return false;
750 
751   MachineBranchPredicate MBP;
752   if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
753     return false;
754 
755   return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
756          (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
757           MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
758          MBP.LHS.getReg() == BaseOp->getReg();
759 }
760 
761 /// Sink an instruction and its associated debug instructions.
762 static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo,
763                         MachineBasicBlock::iterator InsertPos,
764                         SmallVectorImpl<MachineInstr *> &DbgValuesToSink) {
765   const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
766   const TargetInstrInfo &TII = *MI.getMF()->getSubtarget().getInstrInfo();
767 
768   // If we cannot find a location to use (merge with), then we erase the debug
769   // location to prevent debug-info driven tools from potentially reporting
770   // wrong location information.
771   if (!SuccToSinkTo.empty() && InsertPos != SuccToSinkTo.end())
772     MI.setDebugLoc(DILocation::getMergedLocation(MI.getDebugLoc(),
773                                                  InsertPos->getDebugLoc()));
774   else
775     MI.setDebugLoc(DebugLoc());
776 
777   // Move the instruction.
778   MachineBasicBlock *ParentBlock = MI.getParent();
779   SuccToSinkTo.splice(InsertPos, ParentBlock, MI,
780                       ++MachineBasicBlock::iterator(MI));
781 
782   // Sink a copy of debug users to the insert position. Mark the original
783   // DBG_VALUE location as 'undef', indicating that any earlier variable
784   // location should be terminated as we've optimised away the value at this
785   // point.
786   // If the sunk instruction is a copy, try to forward the copy instead of
787   // leaving an 'undef' DBG_VALUE in the original location. Don't do this if
788   // there's any subregister weirdness involved.
789   for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
790                                                  DBE = DbgValuesToSink.end();
791        DBI != DBE; ++DBI) {
792     MachineInstr *DbgMI = *DBI;
793     MachineInstr *NewDbgMI = DbgMI->getMF()->CloneMachineInstr(*DBI);
794     SuccToSinkTo.insert(InsertPos, NewDbgMI);
795 
796     // Copy DBG_VALUE operand and set the original to undef. We then check to
797     // see whether this is something that can be copy-forwarded. If it isn't,
798     // continue around the loop.
799     MachineOperand DbgMO = DbgMI->getOperand(0);
800     DbgMI->getOperand(0).setReg(0);
801 
802     const MachineOperand *SrcMO = nullptr, *DstMO = nullptr;
803     if (!TII.isCopyInstr(MI, SrcMO, DstMO))
804       continue;
805 
806     // Check validity of forwarding this copy.
807     bool PostRA = MRI.getNumVirtRegs() == 0;
808 
809     // Trying to forward between physical and virtual registers is too hard.
810     if (DbgMO.getReg().isVirtual() != SrcMO->getReg().isVirtual())
811       continue;
812 
813     // Only try virtual register copy-forwarding before regalloc, and physical
814     // register copy-forwarding after regalloc.
815     bool arePhysRegs = !DbgMO.getReg().isVirtual();
816     if (arePhysRegs != PostRA)
817       continue;
818 
819     // Pre-regalloc, only forward if all subregisters agree (or there are no
820     // subregs at all). More analysis might recover some forwardable copies.
821     if (!PostRA && (DbgMO.getSubReg() != SrcMO->getSubReg() ||
822                     DbgMO.getSubReg() != DstMO->getSubReg()))
823       continue;
824 
825     // Post-regalloc, we may be sinking a DBG_VALUE of a sub or super-register
826     // of this copy. Only forward the copy if the DBG_VALUE operand exactly
827     // matches the copy destination.
828     if (PostRA && DbgMO.getReg() != DstMO->getReg())
829       continue;
830 
831     DbgMI->getOperand(0).setReg(SrcMO->getReg());
832     DbgMI->getOperand(0).setSubReg(SrcMO->getSubReg());
833   }
834 }
835 
836 /// SinkInstruction - Determine whether it is safe to sink the specified machine
837 /// instruction out of its current block into a successor.
838 bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
839                                      AllSuccsCache &AllSuccessors) {
840   // Don't sink instructions that the target prefers not to sink.
841   if (!TII->shouldSink(MI))
842     return false;
843 
844   // Check if it's safe to move the instruction.
845   if (!MI.isSafeToMove(AA, SawStore))
846     return false;
847 
848   // Convergent operations may not be made control-dependent on additional
849   // values.
850   if (MI.isConvergent())
851     return false;
852 
853   // Don't break implicit null checks.  This is a performance heuristic, and not
854   // required for correctness.
855   if (SinkingPreventsImplicitNullCheck(MI, TII, TRI))
856     return false;
857 
858   // FIXME: This should include support for sinking instructions within the
859   // block they are currently in to shorten the live ranges.  We often get
860   // instructions sunk into the top of a large block, but it would be better to
861   // also sink them down before their first use in the block.  This xform has to
862   // be careful not to *increase* register pressure though, e.g. sinking
863   // "x = y + z" down if it kills y and z would increase the live ranges of y
864   // and z and only shrink the live range of x.
865 
866   bool BreakPHIEdge = false;
867   MachineBasicBlock *ParentBlock = MI.getParent();
868   MachineBasicBlock *SuccToSinkTo =
869       FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
870 
871   // If there are no outputs, it must have side-effects.
872   if (!SuccToSinkTo)
873     return false;
874 
875   // If the instruction to move defines a dead physical register which is live
876   // when leaving the basic block, don't move it because it could turn into a
877   // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
878   for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
879     const MachineOperand &MO = MI.getOperand(I);
880     if (!MO.isReg()) continue;
881     Register Reg = MO.getReg();
882     if (Reg == 0 || !Register::isPhysicalRegister(Reg))
883       continue;
884     if (SuccToSinkTo->isLiveIn(Reg))
885       return false;
886   }
887 
888   LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
889 
890   // If the block has multiple predecessors, this is a critical edge.
891   // Decide if we can sink along it or need to break the edge.
892   if (SuccToSinkTo->pred_size() > 1) {
893     // We cannot sink a load across a critical edge - there may be stores in
894     // other code paths.
895     bool TryBreak = false;
896     bool store = true;
897     if (!MI.isSafeToMove(AA, store)) {
898       LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
899       TryBreak = true;
900     }
901 
902     // We don't want to sink across a critical edge if we don't dominate the
903     // successor. We could be introducing calculations to new code paths.
904     if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
905       LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
906       TryBreak = true;
907     }
908 
909     // Don't sink instructions into a loop.
910     if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
911       LLVM_DEBUG(dbgs() << " *** NOTE: Loop header found\n");
912       TryBreak = true;
913     }
914 
915     // Otherwise we are OK with sinking along a critical edge.
916     if (!TryBreak)
917       LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
918     else {
919       // Mark this edge as to be split.
920       // If the edge can actually be split, the next iteration of the main loop
921       // will sink MI in the newly created block.
922       bool Status =
923         PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
924       if (!Status)
925         LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
926                              "break critical edge\n");
927       // The instruction will not be sunk this time.
928       return false;
929     }
930   }
931 
932   if (BreakPHIEdge) {
933     // BreakPHIEdge is true if all the uses are in the successor MBB being
934     // sunken into and they are all PHI nodes. In this case, machine-sink must
935     // break the critical edge first.
936     bool Status = PostponeSplitCriticalEdge(MI, ParentBlock,
937                                             SuccToSinkTo, BreakPHIEdge);
938     if (!Status)
939       LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
940                            "break critical edge\n");
941     // The instruction will not be sunk this time.
942     return false;
943   }
944 
945   // Determine where to insert into. Skip phi nodes.
946   MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
947   while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
948     ++InsertPos;
949 
950   // Collect debug users of any vreg that this inst defines.
951   SmallVector<MachineInstr *, 4> DbgUsersToSink;
952   for (auto &MO : MI.operands()) {
953     if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual())
954       continue;
955     if (!SeenDbgUsers.count(MO.getReg()))
956       continue;
957 
958     auto &Users = SeenDbgUsers[MO.getReg()];
959     DbgUsersToSink.insert(DbgUsersToSink.end(), Users.begin(), Users.end());
960   }
961 
962   // After sinking, some debug users may not be dominated any more. If possible,
963   // copy-propagate their operands. As it's expensive, don't do this if there's
964   // no debuginfo in the program.
965   if (MI.getMF()->getFunction().getSubprogram() && MI.isCopy())
966     SalvageUnsunkDebugUsersOfCopy(MI, SuccToSinkTo);
967 
968   performSink(MI, *SuccToSinkTo, InsertPos, DbgUsersToSink);
969 
970   // Conservatively, clear any kill flags, since it's possible that they are no
971   // longer correct.
972   // Note that we have to clear the kill flags for any register this instruction
973   // uses as we may sink over another instruction which currently kills the
974   // used registers.
975   for (MachineOperand &MO : MI.operands()) {
976     if (MO.isReg() && MO.isUse())
977       RegsToClearKillFlags.set(MO.getReg()); // Remember to clear kill flags.
978   }
979 
980   return true;
981 }
982 
983 void MachineSinking::SalvageUnsunkDebugUsersOfCopy(
984     MachineInstr &MI, MachineBasicBlock *TargetBlock) {
985   assert(MI.isCopy());
986   assert(MI.getOperand(1).isReg());
987 
988   // Enumerate all users of vreg operands that are def'd. Skip those that will
989   // be sunk. For the rest, if they are not dominated by the block we will sink
990   // MI into, propagate the copy source to them.
991   SmallVector<MachineInstr *, 4> DbgDefUsers;
992   const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
993   for (auto &MO : MI.operands()) {
994     if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual())
995       continue;
996     for (auto &User : MRI.use_instructions(MO.getReg())) {
997       if (!User.isDebugValue() || DT->dominates(TargetBlock, User.getParent()))
998         continue;
999 
1000       // If is in same block, will either sink or be use-before-def.
1001       if (User.getParent() == MI.getParent())
1002         continue;
1003 
1004       assert(User.getOperand(0).isReg() &&
1005              "DBG_VALUE user of vreg, but non reg operand?");
1006       DbgDefUsers.push_back(&User);
1007     }
1008   }
1009 
1010   // Point the users of this copy that are no longer dominated, at the source
1011   // of the copy.
1012   for (auto *User : DbgDefUsers) {
1013     User->getOperand(0).setReg(MI.getOperand(1).getReg());
1014     User->getOperand(0).setSubReg(MI.getOperand(1).getSubReg());
1015   }
1016 }
1017 
1018 //===----------------------------------------------------------------------===//
1019 // This pass is not intended to be a replacement or a complete alternative
1020 // for the pre-ra machine sink pass. It is only designed to sink COPY
1021 // instructions which should be handled after RA.
1022 //
1023 // This pass sinks COPY instructions into a successor block, if the COPY is not
1024 // used in the current block and the COPY is live-in to a single successor
1025 // (i.e., doesn't require the COPY to be duplicated).  This avoids executing the
1026 // copy on paths where their results aren't needed.  This also exposes
1027 // additional opportunites for dead copy elimination and shrink wrapping.
1028 //
1029 // These copies were either not handled by or are inserted after the MachineSink
1030 // pass. As an example of the former case, the MachineSink pass cannot sink
1031 // COPY instructions with allocatable source registers; for AArch64 these type
1032 // of copy instructions are frequently used to move function parameters (PhyReg)
1033 // into virtual registers in the entry block.
1034 //
1035 // For the machine IR below, this pass will sink %w19 in the entry into its
1036 // successor (%bb.1) because %w19 is only live-in in %bb.1.
1037 // %bb.0:
1038 //   %wzr = SUBSWri %w1, 1
1039 //   %w19 = COPY %w0
1040 //   Bcc 11, %bb.2
1041 // %bb.1:
1042 //   Live Ins: %w19
1043 //   BL @fun
1044 //   %w0 = ADDWrr %w0, %w19
1045 //   RET %w0
1046 // %bb.2:
1047 //   %w0 = COPY %wzr
1048 //   RET %w0
1049 // As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be
1050 // able to see %bb.0 as a candidate.
1051 //===----------------------------------------------------------------------===//
1052 namespace {
1053 
1054 class PostRAMachineSinking : public MachineFunctionPass {
1055 public:
1056   bool runOnMachineFunction(MachineFunction &MF) override;
1057 
1058   static char ID;
1059   PostRAMachineSinking() : MachineFunctionPass(ID) {}
1060   StringRef getPassName() const override { return "PostRA Machine Sink"; }
1061 
1062   void getAnalysisUsage(AnalysisUsage &AU) const override {
1063     AU.setPreservesCFG();
1064     MachineFunctionPass::getAnalysisUsage(AU);
1065   }
1066 
1067   MachineFunctionProperties getRequiredProperties() const override {
1068     return MachineFunctionProperties().set(
1069         MachineFunctionProperties::Property::NoVRegs);
1070   }
1071 
1072 private:
1073   /// Track which register units have been modified and used.
1074   LiveRegUnits ModifiedRegUnits, UsedRegUnits;
1075 
1076   /// Track DBG_VALUEs of (unmodified) register units. Each DBG_VALUE has an
1077   /// entry in this map for each unit it touches.
1078   DenseMap<unsigned, TinyPtrVector<MachineInstr *>> SeenDbgInstrs;
1079 
1080   /// Sink Copy instructions unused in the same block close to their uses in
1081   /// successors.
1082   bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF,
1083                      const TargetRegisterInfo *TRI, const TargetInstrInfo *TII);
1084 };
1085 } // namespace
1086 
1087 char PostRAMachineSinking::ID = 0;
1088 char &llvm::PostRAMachineSinkingID = PostRAMachineSinking::ID;
1089 
1090 INITIALIZE_PASS(PostRAMachineSinking, "postra-machine-sink",
1091                 "PostRA Machine Sink", false, false)
1092 
1093 static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, unsigned Reg,
1094                                   const TargetRegisterInfo *TRI) {
1095   LiveRegUnits LiveInRegUnits(*TRI);
1096   LiveInRegUnits.addLiveIns(MBB);
1097   return !LiveInRegUnits.available(Reg);
1098 }
1099 
1100 static MachineBasicBlock *
1101 getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
1102                       const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
1103                       unsigned Reg, const TargetRegisterInfo *TRI) {
1104   // Try to find a single sinkable successor in which Reg is live-in.
1105   MachineBasicBlock *BB = nullptr;
1106   for (auto *SI : SinkableBBs) {
1107     if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) {
1108       // If BB is set here, Reg is live-in to at least two sinkable successors,
1109       // so quit.
1110       if (BB)
1111         return nullptr;
1112       BB = SI;
1113     }
1114   }
1115   // Reg is not live-in to any sinkable successors.
1116   if (!BB)
1117     return nullptr;
1118 
1119   // Check if any register aliased with Reg is live-in in other successors.
1120   for (auto *SI : CurBB.successors()) {
1121     if (!SinkableBBs.count(SI) && aliasWithRegsInLiveIn(*SI, Reg, TRI))
1122       return nullptr;
1123   }
1124   return BB;
1125 }
1126 
1127 static MachineBasicBlock *
1128 getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
1129                       const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
1130                       ArrayRef<unsigned> DefedRegsInCopy,
1131                       const TargetRegisterInfo *TRI) {
1132   MachineBasicBlock *SingleBB = nullptr;
1133   for (auto DefReg : DefedRegsInCopy) {
1134     MachineBasicBlock *BB =
1135         getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI);
1136     if (!BB || (SingleBB && SingleBB != BB))
1137       return nullptr;
1138     SingleBB = BB;
1139   }
1140   return SingleBB;
1141 }
1142 
1143 static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB,
1144                            SmallVectorImpl<unsigned> &UsedOpsInCopy,
1145                            LiveRegUnits &UsedRegUnits,
1146                            const TargetRegisterInfo *TRI) {
1147   for (auto U : UsedOpsInCopy) {
1148     MachineOperand &MO = MI->getOperand(U);
1149     Register SrcReg = MO.getReg();
1150     if (!UsedRegUnits.available(SrcReg)) {
1151       MachineBasicBlock::iterator NI = std::next(MI->getIterator());
1152       for (MachineInstr &UI : make_range(NI, CurBB.end())) {
1153         if (UI.killsRegister(SrcReg, TRI)) {
1154           UI.clearRegisterKills(SrcReg, TRI);
1155           MO.setIsKill(true);
1156           break;
1157         }
1158       }
1159     }
1160   }
1161 }
1162 
1163 static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB,
1164                          SmallVectorImpl<unsigned> &UsedOpsInCopy,
1165                          SmallVectorImpl<unsigned> &DefedRegsInCopy) {
1166   MachineFunction &MF = *SuccBB->getParent();
1167   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1168   for (unsigned DefReg : DefedRegsInCopy)
1169     for (MCSubRegIterator S(DefReg, TRI, true); S.isValid(); ++S)
1170       SuccBB->removeLiveIn(*S);
1171   for (auto U : UsedOpsInCopy) {
1172     Register Reg = MI->getOperand(U).getReg();
1173     if (!SuccBB->isLiveIn(Reg))
1174       SuccBB->addLiveIn(Reg);
1175   }
1176 }
1177 
1178 static bool hasRegisterDependency(MachineInstr *MI,
1179                                   SmallVectorImpl<unsigned> &UsedOpsInCopy,
1180                                   SmallVectorImpl<unsigned> &DefedRegsInCopy,
1181                                   LiveRegUnits &ModifiedRegUnits,
1182                                   LiveRegUnits &UsedRegUnits) {
1183   bool HasRegDependency = false;
1184   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1185     MachineOperand &MO = MI->getOperand(i);
1186     if (!MO.isReg())
1187       continue;
1188     Register Reg = MO.getReg();
1189     if (!Reg)
1190       continue;
1191     if (MO.isDef()) {
1192       if (!ModifiedRegUnits.available(Reg) || !UsedRegUnits.available(Reg)) {
1193         HasRegDependency = true;
1194         break;
1195       }
1196       DefedRegsInCopy.push_back(Reg);
1197 
1198       // FIXME: instead of isUse(), readsReg() would be a better fix here,
1199       // For example, we can ignore modifications in reg with undef. However,
1200       // it's not perfectly clear if skipping the internal read is safe in all
1201       // other targets.
1202     } else if (MO.isUse()) {
1203       if (!ModifiedRegUnits.available(Reg)) {
1204         HasRegDependency = true;
1205         break;
1206       }
1207       UsedOpsInCopy.push_back(i);
1208     }
1209   }
1210   return HasRegDependency;
1211 }
1212 
1213 static SmallSet<unsigned, 4> getRegUnits(unsigned Reg,
1214                                          const TargetRegisterInfo *TRI) {
1215   SmallSet<unsigned, 4> RegUnits;
1216   for (auto RI = MCRegUnitIterator(Reg, TRI); RI.isValid(); ++RI)
1217     RegUnits.insert(*RI);
1218   return RegUnits;
1219 }
1220 
1221 bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock &CurBB,
1222                                          MachineFunction &MF,
1223                                          const TargetRegisterInfo *TRI,
1224                                          const TargetInstrInfo *TII) {
1225   SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs;
1226   // FIXME: For now, we sink only to a successor which has a single predecessor
1227   // so that we can directly sink COPY instructions to the successor without
1228   // adding any new block or branch instruction.
1229   for (MachineBasicBlock *SI : CurBB.successors())
1230     if (!SI->livein_empty() && SI->pred_size() == 1)
1231       SinkableBBs.insert(SI);
1232 
1233   if (SinkableBBs.empty())
1234     return false;
1235 
1236   bool Changed = false;
1237 
1238   // Track which registers have been modified and used between the end of the
1239   // block and the current instruction.
1240   ModifiedRegUnits.clear();
1241   UsedRegUnits.clear();
1242   SeenDbgInstrs.clear();
1243 
1244   for (auto I = CurBB.rbegin(), E = CurBB.rend(); I != E;) {
1245     MachineInstr *MI = &*I;
1246     ++I;
1247 
1248     // Track the operand index for use in Copy.
1249     SmallVector<unsigned, 2> UsedOpsInCopy;
1250     // Track the register number defed in Copy.
1251     SmallVector<unsigned, 2> DefedRegsInCopy;
1252 
1253     // We must sink this DBG_VALUE if its operand is sunk. To avoid searching
1254     // for DBG_VALUEs later, record them when they're encountered.
1255     if (MI->isDebugValue()) {
1256       auto &MO = MI->getOperand(0);
1257       if (MO.isReg() && Register::isPhysicalRegister(MO.getReg())) {
1258         // Bail if we can already tell the sink would be rejected, rather
1259         // than needlessly accumulating lots of DBG_VALUEs.
1260         if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy,
1261                                   ModifiedRegUnits, UsedRegUnits))
1262           continue;
1263 
1264         // Record debug use of each reg unit.
1265         SmallSet<unsigned, 4> Units = getRegUnits(MO.getReg(), TRI);
1266         for (unsigned Reg : Units)
1267           SeenDbgInstrs[Reg].push_back(MI);
1268       }
1269       continue;
1270     }
1271 
1272     if (MI->isDebugInstr())
1273       continue;
1274 
1275     // Do not move any instruction across function call.
1276     if (MI->isCall())
1277       return false;
1278 
1279     if (!MI->isCopy() || !MI->getOperand(0).isRenamable()) {
1280       LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
1281                                         TRI);
1282       continue;
1283     }
1284 
1285     // Don't sink the COPY if it would violate a register dependency.
1286     if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy,
1287                               ModifiedRegUnits, UsedRegUnits)) {
1288       LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
1289                                         TRI);
1290       continue;
1291     }
1292     assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) &&
1293            "Unexpect SrcReg or DefReg");
1294     MachineBasicBlock *SuccBB =
1295         getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI);
1296     // Don't sink if we cannot find a single sinkable successor in which Reg
1297     // is live-in.
1298     if (!SuccBB) {
1299       LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
1300                                         TRI);
1301       continue;
1302     }
1303     assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) &&
1304            "Unexpected predecessor");
1305 
1306     // Collect DBG_VALUEs that must sink with this copy. We've previously
1307     // recorded which reg units that DBG_VALUEs read, if this instruction
1308     // writes any of those units then the corresponding DBG_VALUEs must sink.
1309     SetVector<MachineInstr *> DbgValsToSinkSet;
1310     SmallVector<MachineInstr *, 4> DbgValsToSink;
1311     for (auto &MO : MI->operands()) {
1312       if (!MO.isReg() || !MO.isDef())
1313         continue;
1314 
1315       SmallSet<unsigned, 4> Units = getRegUnits(MO.getReg(), TRI);
1316       for (unsigned Reg : Units)
1317         for (auto *MI : SeenDbgInstrs.lookup(Reg))
1318           DbgValsToSinkSet.insert(MI);
1319     }
1320     DbgValsToSink.insert(DbgValsToSink.begin(), DbgValsToSinkSet.begin(),
1321                          DbgValsToSinkSet.end());
1322 
1323     // Clear the kill flag if SrcReg is killed between MI and the end of the
1324     // block.
1325     clearKillFlags(MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI);
1326     MachineBasicBlock::iterator InsertPos = SuccBB->getFirstNonPHI();
1327     performSink(*MI, *SuccBB, InsertPos, DbgValsToSink);
1328     updateLiveIn(MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy);
1329 
1330     Changed = true;
1331     ++NumPostRACopySink;
1332   }
1333   return Changed;
1334 }
1335 
1336 bool PostRAMachineSinking::runOnMachineFunction(MachineFunction &MF) {
1337   if (skipFunction(MF.getFunction()))
1338     return false;
1339 
1340   bool Changed = false;
1341   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1342   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
1343 
1344   ModifiedRegUnits.init(*TRI);
1345   UsedRegUnits.init(*TRI);
1346   for (auto &BB : MF)
1347     Changed |= tryToSinkCopy(BB, MF, TRI, TII);
1348 
1349   return Changed;
1350 }
1351