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