xref: /llvm-project/llvm/lib/CodeGen/MachineSink.cpp (revision 95fc43143d74742b44d6361a16af3bf424471e79)
1 //===-- MachineSink.cpp - Sinking for machine instructions ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass moves instructions into successor blocks when possible, so that
11 // they aren't executed on paths where their results aren't needed.
12 //
13 // This pass is not intended to be a replacement or a complete alternative
14 // for an LLVM-IR-level sinking pass. It is only designed to sink simple
15 // constructs that are not exposed before lowering and instruction selection.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SparseBitVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineBasicBlock.h"
26 #include "llvm/CodeGen/MachineBlockFrequencyInfo.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/IR/LLVMContext.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
42 #include <algorithm>
43 #include <cassert>
44 #include <cstdint>
45 #include <map>
46 #include <utility>
47 #include <vector>
48 
49 using namespace llvm;
50 
51 #define DEBUG_TYPE "machine-sink"
52 
53 static cl::opt<bool>
54 SplitEdges("machine-sink-split",
55            cl::desc("Split critical edges during machine sinking"),
56            cl::init(true), cl::Hidden);
57 
58 static cl::opt<bool>
59 UseBlockFreqInfo("machine-sink-bfi",
60            cl::desc("Use block frequency info to find successors to sink"),
61            cl::init(true), cl::Hidden);
62 
63 STATISTIC(NumSunk,      "Number of machine instructions sunk");
64 STATISTIC(NumSplit,     "Number of critical edges split");
65 STATISTIC(NumCoalesces, "Number of copies coalesced");
66 
67 namespace {
68 
69   class MachineSinking : public MachineFunctionPass {
70     const TargetInstrInfo *TII;
71     const TargetRegisterInfo *TRI;
72     MachineRegisterInfo  *MRI;     // Machine register information
73     MachineDominatorTree *DT;      // Machine dominator tree
74     MachinePostDominatorTree *PDT; // Machine post dominator tree
75     MachineLoopInfo *LI;
76     const MachineBlockFrequencyInfo *MBFI;
77     AliasAnalysis *AA;
78 
79     // Remember which edges have been considered for breaking.
80     SmallSet<std::pair<MachineBasicBlock*, MachineBasicBlock*>, 8>
81     CEBCandidates;
82     // Remember which edges we are about to split.
83     // This is different from CEBCandidates since those edges
84     // will be split.
85     SetVector<std::pair<MachineBasicBlock*, MachineBasicBlock*> > ToSplit;
86 
87     SparseBitVector<> RegsToClearKillFlags;
88 
89     typedef std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>
90         AllSuccsCache;
91 
92   public:
93     static char ID; // Pass identification
94 
95     MachineSinking() : MachineFunctionPass(ID) {
96       initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
97     }
98 
99     bool runOnMachineFunction(MachineFunction &MF) override;
100 
101     void getAnalysisUsage(AnalysisUsage &AU) const override {
102       AU.setPreservesCFG();
103       MachineFunctionPass::getAnalysisUsage(AU);
104       AU.addRequired<AAResultsWrapperPass>();
105       AU.addRequired<MachineDominatorTree>();
106       AU.addRequired<MachinePostDominatorTree>();
107       AU.addRequired<MachineLoopInfo>();
108       AU.addPreserved<MachineDominatorTree>();
109       AU.addPreserved<MachinePostDominatorTree>();
110       AU.addPreserved<MachineLoopInfo>();
111       if (UseBlockFreqInfo)
112         AU.addRequired<MachineBlockFrequencyInfo>();
113     }
114 
115     void releaseMemory() override {
116       CEBCandidates.clear();
117     }
118 
119   private:
120     bool ProcessBlock(MachineBasicBlock &MBB);
121     bool isWorthBreakingCriticalEdge(MachineInstr &MI,
122                                      MachineBasicBlock *From,
123                                      MachineBasicBlock *To);
124     /// \brief Postpone the splitting of the given critical
125     /// edge (\p From, \p To).
126     ///
127     /// We do not split the edges on the fly. Indeed, this invalidates
128     /// the dominance information and thus triggers a lot of updates
129     /// of that information underneath.
130     /// Instead, we postpone all the splits after each iteration of
131     /// the main loop. That way, the information is at least valid
132     /// for the lifetime of an iteration.
133     ///
134     /// \return True if the edge is marked as toSplit, false otherwise.
135     /// False can be returned if, for instance, this is not profitable.
136     bool PostponeSplitCriticalEdge(MachineInstr &MI,
137                                    MachineBasicBlock *From,
138                                    MachineBasicBlock *To,
139                                    bool BreakPHIEdge);
140     bool SinkInstruction(MachineInstr &MI, bool &SawStore,
141                          AllSuccsCache &AllSuccessors);
142     bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
143                                  MachineBasicBlock *DefMBB,
144                                  bool &BreakPHIEdge, bool &LocalUse) const;
145     MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
146                bool &BreakPHIEdge, AllSuccsCache &AllSuccessors);
147     bool isProfitableToSinkTo(unsigned Reg, MachineInstr &MI,
148                               MachineBasicBlock *MBB,
149                               MachineBasicBlock *SuccToSinkTo,
150                               AllSuccsCache &AllSuccessors);
151 
152     bool PerformTrivialForwardCoalescing(MachineInstr &MI,
153                                          MachineBasicBlock *MBB);
154 
155     SmallVector<MachineBasicBlock *, 4> &
156     GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
157                            AllSuccsCache &AllSuccessors) const;
158   };
159 
160 } // end anonymous namespace
161 
162 char MachineSinking::ID = 0;
163 char &llvm::MachineSinkingID = MachineSinking::ID;
164 INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
165                 "Machine code sinking", false, false)
166 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
167 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
168 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
169 INITIALIZE_PASS_END(MachineSinking, "machine-sink",
170                 "Machine code sinking", false, false)
171 
172 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI,
173                                                      MachineBasicBlock *MBB) {
174   if (!MI.isCopy())
175     return false;
176 
177   unsigned SrcReg = MI.getOperand(1).getReg();
178   unsigned DstReg = MI.getOperand(0).getReg();
179   if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
180       !TargetRegisterInfo::isVirtualRegister(DstReg) ||
181       !MRI->hasOneNonDBGUse(SrcReg))
182     return false;
183 
184   const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
185   const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
186   if (SRC != DRC)
187     return false;
188 
189   MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
190   if (DefMI->isCopyLike())
191     return false;
192   DEBUG(dbgs() << "Coalescing: " << *DefMI);
193   DEBUG(dbgs() << "*** to: " << MI);
194   MRI->replaceRegWith(DstReg, SrcReg);
195   MI.eraseFromParent();
196 
197   // Conservatively, clear any kill flags, since it's possible that they are no
198   // longer correct.
199   MRI->clearKillFlags(SrcReg);
200 
201   ++NumCoalesces;
202   return true;
203 }
204 
205 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
206 /// occur in blocks dominated by the specified block. If any use is in the
207 /// definition block, then return false since it is never legal to move def
208 /// after uses.
209 bool
210 MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
211                                         MachineBasicBlock *MBB,
212                                         MachineBasicBlock *DefMBB,
213                                         bool &BreakPHIEdge,
214                                         bool &LocalUse) const {
215   assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
216          "Only makes sense for vregs");
217 
218   // Ignore debug uses because debug info doesn't affect the code.
219   if (MRI->use_nodbg_empty(Reg))
220     return true;
221 
222   // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
223   // into and they are all PHI nodes. In this case, machine-sink must break
224   // the critical edge first. e.g.
225   //
226   // BB#1: derived from LLVM BB %bb4.preheader
227   //   Predecessors according to CFG: BB#0
228   //     ...
229   //     %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
230   //     ...
231   //     JE_4 <BB#37>, %EFLAGS<imp-use>
232   //   Successors according to CFG: BB#37 BB#2
233   //
234   // BB#2: derived from LLVM BB %bb.nph
235   //   Predecessors according to CFG: BB#0 BB#1
236   //     %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
237   BreakPHIEdge = true;
238   for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
239     MachineInstr *UseInst = MO.getParent();
240     unsigned OpNo = &MO - &UseInst->getOperand(0);
241     MachineBasicBlock *UseBlock = UseInst->getParent();
242     if (!(UseBlock == MBB && UseInst->isPHI() &&
243           UseInst->getOperand(OpNo+1).getMBB() == DefMBB)) {
244       BreakPHIEdge = false;
245       break;
246     }
247   }
248   if (BreakPHIEdge)
249     return true;
250 
251   for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
252     // Determine the block of the use.
253     MachineInstr *UseInst = MO.getParent();
254     unsigned OpNo = &MO - &UseInst->getOperand(0);
255     MachineBasicBlock *UseBlock = UseInst->getParent();
256     if (UseInst->isPHI()) {
257       // PHI nodes use the operand in the predecessor block, not the block with
258       // the PHI.
259       UseBlock = UseInst->getOperand(OpNo+1).getMBB();
260     } else if (UseBlock == DefMBB) {
261       LocalUse = true;
262       return false;
263     }
264 
265     // Check that it dominates.
266     if (!DT->dominates(MBB, UseBlock))
267       return false;
268   }
269 
270   return true;
271 }
272 
273 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
274   if (skipFunction(*MF.getFunction()))
275     return false;
276 
277   DEBUG(dbgs() << "******** Machine Sinking ********\n");
278 
279   TII = MF.getSubtarget().getInstrInfo();
280   TRI = MF.getSubtarget().getRegisterInfo();
281   MRI = &MF.getRegInfo();
282   DT = &getAnalysis<MachineDominatorTree>();
283   PDT = &getAnalysis<MachinePostDominatorTree>();
284   LI = &getAnalysis<MachineLoopInfo>();
285   MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr;
286   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
287 
288   bool EverMadeChange = false;
289 
290   while (true) {
291     bool MadeChange = false;
292 
293     // Process all basic blocks.
294     CEBCandidates.clear();
295     ToSplit.clear();
296     for (auto &MBB: MF)
297       MadeChange |= ProcessBlock(MBB);
298 
299     // If we have anything we marked as toSplit, split it now.
300     for (auto &Pair : ToSplit) {
301       auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this);
302       if (NewSucc != nullptr) {
303         DEBUG(dbgs() << " *** Splitting critical edge:"
304               " BB#" << Pair.first->getNumber()
305               << " -- BB#" << NewSucc->getNumber()
306               << " -- BB#" << Pair.second->getNumber() << '\n');
307         MadeChange = true;
308         ++NumSplit;
309       } else
310         DEBUG(dbgs() << " *** Not legal to break critical edge\n");
311     }
312     // If this iteration over the code changed anything, keep iterating.
313     if (!MadeChange) break;
314     EverMadeChange = true;
315   }
316 
317   // Now clear any kill flags for recorded registers.
318   for (auto I : RegsToClearKillFlags)
319     MRI->clearKillFlags(I);
320   RegsToClearKillFlags.clear();
321 
322   return EverMadeChange;
323 }
324 
325 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
326   // Can't sink anything out of a block that has less than two successors.
327   if (MBB.succ_size() <= 1 || MBB.empty()) return false;
328 
329   // Don't bother sinking code out of unreachable blocks. In addition to being
330   // unprofitable, it can also lead to infinite looping, because in an
331   // unreachable loop there may be nowhere to stop.
332   if (!DT->isReachableFromEntry(&MBB)) return false;
333 
334   bool MadeChange = false;
335 
336   // Cache all successors, sorted by frequency info and loop depth.
337   AllSuccsCache AllSuccessors;
338 
339   // Walk the basic block bottom-up.  Remember if we saw a store.
340   MachineBasicBlock::iterator I = MBB.end();
341   --I;
342   bool ProcessedBegin, SawStore = false;
343   do {
344     MachineInstr &MI = *I;  // The instruction to sink.
345 
346     // Predecrement I (if it's not begin) so that it isn't invalidated by
347     // sinking.
348     ProcessedBegin = I == MBB.begin();
349     if (!ProcessedBegin)
350       --I;
351 
352     if (MI.isDebugValue())
353       continue;
354 
355     bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
356     if (Joined) {
357       MadeChange = true;
358       continue;
359     }
360 
361     if (SinkInstruction(MI, SawStore, AllSuccessors)) {
362       ++NumSunk;
363       MadeChange = true;
364     }
365 
366     // If we just processed the first instruction in the block, we're done.
367   } while (!ProcessedBegin);
368 
369   return MadeChange;
370 }
371 
372 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr &MI,
373                                                  MachineBasicBlock *From,
374                                                  MachineBasicBlock *To) {
375   // FIXME: Need much better heuristics.
376 
377   // If the pass has already considered breaking this edge (during this pass
378   // through the function), then let's go ahead and break it. This means
379   // sinking multiple "cheap" instructions into the same block.
380   if (!CEBCandidates.insert(std::make_pair(From, To)).second)
381     return true;
382 
383   if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI))
384     return true;
385 
386   // MI is cheap, we probably don't want to break the critical edge for it.
387   // However, if this would allow some definitions of its source operands
388   // to be sunk then it's probably worth it.
389   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
390     const MachineOperand &MO = MI.getOperand(i);
391     if (!MO.isReg() || !MO.isUse())
392       continue;
393     unsigned Reg = MO.getReg();
394     if (Reg == 0)
395       continue;
396 
397     // We don't move live definitions of physical registers,
398     // so sinking their uses won't enable any opportunities.
399     if (TargetRegisterInfo::isPhysicalRegister(Reg))
400       continue;
401 
402     // If this instruction is the only user of a virtual register,
403     // check if breaking the edge will enable sinking
404     // both this instruction and the defining instruction.
405     if (MRI->hasOneNonDBGUse(Reg)) {
406       // If the definition resides in same MBB,
407       // claim it's likely we can sink these together.
408       // If definition resides elsewhere, we aren't
409       // blocking it from being sunk so don't break the edge.
410       MachineInstr *DefMI = MRI->getVRegDef(Reg);
411       if (DefMI->getParent() == MI.getParent())
412         return true;
413     }
414   }
415 
416   return false;
417 }
418 
419 bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
420                                                MachineBasicBlock *FromBB,
421                                                MachineBasicBlock *ToBB,
422                                                bool BreakPHIEdge) {
423   if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
424     return false;
425 
426   // Avoid breaking back edge. From == To means backedge for single BB loop.
427   if (!SplitEdges || FromBB == ToBB)
428     return false;
429 
430   // Check for backedges of more "complex" loops.
431   if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
432       LI->isLoopHeader(ToBB))
433     return false;
434 
435   // It's not always legal to break critical edges and sink the computation
436   // to the edge.
437   //
438   // BB#1:
439   // v1024
440   // Beq BB#3
441   // <fallthrough>
442   // BB#2:
443   // ... no uses of v1024
444   // <fallthrough>
445   // BB#3:
446   // ...
447   //       = v1024
448   //
449   // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
450   //
451   // BB#1:
452   // ...
453   // Bne BB#2
454   // BB#4:
455   // v1024 =
456   // B BB#3
457   // BB#2:
458   // ... no uses of v1024
459   // <fallthrough>
460   // BB#3:
461   // ...
462   //       = v1024
463   //
464   // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
465   // flow. We need to ensure the new basic block where the computation is
466   // sunk to dominates all the uses.
467   // It's only legal to break critical edge and sink the computation to the
468   // new block if all the predecessors of "To", except for "From", are
469   // not dominated by "From". Given SSA property, this means these
470   // predecessors are dominated by "To".
471   //
472   // There is no need to do this check if all the uses are PHI nodes. PHI
473   // sources are only defined on the specific predecessor edges.
474   if (!BreakPHIEdge) {
475     for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
476            E = ToBB->pred_end(); PI != E; ++PI) {
477       if (*PI == FromBB)
478         continue;
479       if (!DT->dominates(ToBB, *PI))
480         return false;
481     }
482   }
483 
484   ToSplit.insert(std::make_pair(FromBB, ToBB));
485 
486   return true;
487 }
488 
489 /// collectDebgValues - Scan instructions following MI and collect any
490 /// matching DBG_VALUEs.
491 static void collectDebugValues(MachineInstr &MI,
492                                SmallVectorImpl<MachineInstr *> &DbgValues) {
493   DbgValues.clear();
494   if (!MI.getOperand(0).isReg())
495     return;
496 
497   MachineBasicBlock::iterator DI = MI; ++DI;
498   for (MachineBasicBlock::iterator DE = MI.getParent()->end();
499        DI != DE; ++DI) {
500     if (!DI->isDebugValue())
501       return;
502     if (DI->getOperand(0).isReg() &&
503         DI->getOperand(0).getReg() == MI.getOperand(0).getReg())
504       DbgValues.push_back(&*DI);
505   }
506 }
507 
508 /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
509 bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr &MI,
510                                           MachineBasicBlock *MBB,
511                                           MachineBasicBlock *SuccToSinkTo,
512                                           AllSuccsCache &AllSuccessors) {
513   assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
514 
515   if (MBB == SuccToSinkTo)
516     return false;
517 
518   // It is profitable if SuccToSinkTo does not post dominate current block.
519   if (!PDT->dominates(SuccToSinkTo, MBB))
520     return true;
521 
522   // It is profitable to sink an instruction from a deeper loop to a shallower
523   // loop, even if the latter post-dominates the former (PR21115).
524   if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo))
525     return true;
526 
527   // Check if only use in post dominated block is PHI instruction.
528   bool NonPHIUse = false;
529   for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
530     MachineBasicBlock *UseBlock = UseInst.getParent();
531     if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
532       NonPHIUse = true;
533   }
534   if (!NonPHIUse)
535     return true;
536 
537   // If SuccToSinkTo post dominates then also it may be profitable if MI
538   // can further profitably sinked into another block in next round.
539   bool BreakPHIEdge = false;
540   // FIXME - If finding successor is compile time expensive then cache results.
541   if (MachineBasicBlock *MBB2 =
542           FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
543     return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
544 
545   // If SuccToSinkTo is final destination and it is a post dominator of current
546   // block then it is not profitable to sink MI into SuccToSinkTo block.
547   return false;
548 }
549 
550 /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
551 /// computing it if it was not already cached.
552 SmallVector<MachineBasicBlock *, 4> &
553 MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
554                                        AllSuccsCache &AllSuccessors) const {
555 
556   // Do we have the sorted successors in cache ?
557   auto Succs = AllSuccessors.find(MBB);
558   if (Succs != AllSuccessors.end())
559     return Succs->second;
560 
561   SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->succ_begin(),
562                                                MBB->succ_end());
563 
564   // Handle cases where sinking can happen but where the sink point isn't a
565   // successor. For example:
566   //
567   //   x = computation
568   //   if () {} else {}
569   //   use x
570   //
571   const std::vector<MachineDomTreeNode *> &Children =
572     DT->getNode(MBB)->getChildren();
573   for (const auto &DTChild : Children)
574     // DomTree children of MBB that have MBB as immediate dominator are added.
575     if (DTChild->getIDom()->getBlock() == MI.getParent() &&
576         // Skip MBBs already added to the AllSuccs vector above.
577         !MBB->isSuccessor(DTChild->getBlock()))
578       AllSuccs.push_back(DTChild->getBlock());
579 
580   // Sort Successors according to their loop depth or block frequency info.
581   std::stable_sort(
582       AllSuccs.begin(), AllSuccs.end(),
583       [this](const MachineBasicBlock *L, const MachineBasicBlock *R) {
584         uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
585         uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
586         bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0;
587         return HasBlockFreq ? LHSFreq < RHSFreq
588                             : LI->getLoopDepth(L) < LI->getLoopDepth(R);
589       });
590 
591   auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
592 
593   return it.first->second;
594 }
595 
596 /// FindSuccToSinkTo - Find a successor to sink this instruction to.
597 MachineBasicBlock *
598 MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
599                                  bool &BreakPHIEdge,
600                                  AllSuccsCache &AllSuccessors) {
601   assert (MBB && "Invalid MachineBasicBlock!");
602 
603   // Loop over all the operands of the specified instruction.  If there is
604   // anything we can't handle, bail out.
605 
606   // SuccToSinkTo - This is the successor to sink this instruction to, once we
607   // decide.
608   MachineBasicBlock *SuccToSinkTo = nullptr;
609   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
610     const MachineOperand &MO = MI.getOperand(i);
611     if (!MO.isReg()) continue;  // Ignore non-register operands.
612 
613     unsigned Reg = MO.getReg();
614     if (Reg == 0) continue;
615 
616     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
617       if (MO.isUse()) {
618         // If the physreg has no defs anywhere, it's just an ambient register
619         // and we can freely move its uses. Alternatively, if it's allocatable,
620         // it could get allocated to something with a def during allocation.
621         if (!MRI->isConstantPhysReg(Reg, *MBB->getParent()))
622           return nullptr;
623       } else if (!MO.isDead()) {
624         // A def that isn't dead. We can't move it.
625         return nullptr;
626       }
627     } else {
628       // Virtual register uses are always safe to sink.
629       if (MO.isUse()) continue;
630 
631       // If it's not safe to move defs of the register class, then abort.
632       if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
633         return nullptr;
634 
635       // Virtual register defs can only be sunk if all their uses are in blocks
636       // dominated by one of the successors.
637       if (SuccToSinkTo) {
638         // If a previous operand picked a block to sink to, then this operand
639         // must be sinkable to the same block.
640         bool LocalUse = false;
641         if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
642                                      BreakPHIEdge, LocalUse))
643           return nullptr;
644 
645         continue;
646       }
647 
648       // Otherwise, we should look at all the successors and decide which one
649       // we should sink to. If we have reliable block frequency information
650       // (frequency != 0) available, give successors with smaller frequencies
651       // higher priority, otherwise prioritize smaller loop depths.
652       for (MachineBasicBlock *SuccBlock :
653            GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
654         bool LocalUse = false;
655         if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
656                                     BreakPHIEdge, LocalUse)) {
657           SuccToSinkTo = SuccBlock;
658           break;
659         }
660         if (LocalUse)
661           // Def is used locally, it's never safe to move this def.
662           return nullptr;
663       }
664 
665       // If we couldn't find a block to sink to, ignore this instruction.
666       if (!SuccToSinkTo)
667         return nullptr;
668       if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
669         return nullptr;
670     }
671   }
672 
673   // It is not possible to sink an instruction into its own block.  This can
674   // happen with loops.
675   if (MBB == SuccToSinkTo)
676     return nullptr;
677 
678   // It's not safe to sink instructions to EH landing pad. Control flow into
679   // landing pad is implicitly defined.
680   if (SuccToSinkTo && SuccToSinkTo->isEHPad())
681     return nullptr;
682 
683   return SuccToSinkTo;
684 }
685 
686 /// \brief Return true if MI is likely to be usable as a memory operation by the
687 /// implicit null check optimization.
688 ///
689 /// This is a "best effort" heuristic, and should not be relied upon for
690 /// correctness.  This returning true does not guarantee that the implicit null
691 /// check optimization is legal over MI, and this returning false does not
692 /// guarantee MI cannot possibly be used to do a null check.
693 static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI,
694                                              const TargetInstrInfo *TII,
695                                              const TargetRegisterInfo *TRI) {
696   typedef TargetInstrInfo::MachineBranchPredicate MachineBranchPredicate;
697 
698   auto *MBB = MI.getParent();
699   if (MBB->pred_size() != 1)
700     return false;
701 
702   auto *PredMBB = *MBB->pred_begin();
703   auto *PredBB = PredMBB->getBasicBlock();
704 
705   // Frontends that don't use implicit null checks have no reason to emit
706   // branches with make.implicit metadata, and this function should always
707   // return false for them.
708   if (!PredBB ||
709       !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
710     return false;
711 
712   unsigned BaseReg;
713   int64_t Offset;
714   if (!TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI))
715     return false;
716 
717   if (!(MI.mayLoad() && !MI.isPredicable()))
718     return false;
719 
720   MachineBranchPredicate MBP;
721   if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
722     return false;
723 
724   return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
725          (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
726           MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
727          MBP.LHS.getReg() == BaseReg;
728 }
729 
730 /// SinkInstruction - Determine whether it is safe to sink the specified machine
731 /// instruction out of its current block into a successor.
732 bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
733                                      AllSuccsCache &AllSuccessors) {
734   // Don't sink instructions that the target prefers not to sink.
735   if (!TII->shouldSink(MI))
736     return false;
737 
738   // Check if it's safe to move the instruction.
739   if (!MI.isSafeToMove(AA, SawStore))
740     return false;
741 
742   // Convergent operations may not be made control-dependent on additional
743   // values.
744   if (MI.isConvergent())
745     return false;
746 
747   // Don't break implicit null checks.  This is a performance heuristic, and not
748   // required for correctness.
749   if (SinkingPreventsImplicitNullCheck(MI, TII, TRI))
750     return false;
751 
752   // FIXME: This should include support for sinking instructions within the
753   // block they are currently in to shorten the live ranges.  We often get
754   // instructions sunk into the top of a large block, but it would be better to
755   // also sink them down before their first use in the block.  This xform has to
756   // be careful not to *increase* register pressure though, e.g. sinking
757   // "x = y + z" down if it kills y and z would increase the live ranges of y
758   // and z and only shrink the live range of x.
759 
760   bool BreakPHIEdge = false;
761   MachineBasicBlock *ParentBlock = MI.getParent();
762   MachineBasicBlock *SuccToSinkTo =
763       FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
764 
765   // If there are no outputs, it must have side-effects.
766   if (!SuccToSinkTo)
767     return false;
768 
769 
770   // If the instruction to move defines a dead physical register which is live
771   // when leaving the basic block, don't move it because it could turn into a
772   // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
773   for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
774     const MachineOperand &MO = MI.getOperand(I);
775     if (!MO.isReg()) continue;
776     unsigned Reg = MO.getReg();
777     if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
778     if (SuccToSinkTo->isLiveIn(Reg))
779       return false;
780   }
781 
782   DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
783 
784   // If the block has multiple predecessors, this is a critical edge.
785   // Decide if we can sink along it or need to break the edge.
786   if (SuccToSinkTo->pred_size() > 1) {
787     // We cannot sink a load across a critical edge - there may be stores in
788     // other code paths.
789     bool TryBreak = false;
790     bool store = true;
791     if (!MI.isSafeToMove(AA, store)) {
792       DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
793       TryBreak = true;
794     }
795 
796     // We don't want to sink across a critical edge if we don't dominate the
797     // successor. We could be introducing calculations to new code paths.
798     if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
799       DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
800       TryBreak = true;
801     }
802 
803     // Don't sink instructions into a loop.
804     if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
805       DEBUG(dbgs() << " *** NOTE: Loop header found\n");
806       TryBreak = true;
807     }
808 
809     // Otherwise we are OK with sinking along a critical edge.
810     if (!TryBreak)
811       DEBUG(dbgs() << "Sinking along critical edge.\n");
812     else {
813       // Mark this edge as to be split.
814       // If the edge can actually be split, the next iteration of the main loop
815       // will sink MI in the newly created block.
816       bool Status =
817         PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
818       if (!Status)
819         DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
820               "break critical edge\n");
821       // The instruction will not be sunk this time.
822       return false;
823     }
824   }
825 
826   if (BreakPHIEdge) {
827     // BreakPHIEdge is true if all the uses are in the successor MBB being
828     // sunken into and they are all PHI nodes. In this case, machine-sink must
829     // break the critical edge first.
830     bool Status = PostponeSplitCriticalEdge(MI, ParentBlock,
831                                             SuccToSinkTo, BreakPHIEdge);
832     if (!Status)
833       DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
834             "break critical edge\n");
835     // The instruction will not be sunk this time.
836     return false;
837   }
838 
839   // Determine where to insert into. Skip phi nodes.
840   MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
841   while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
842     ++InsertPos;
843 
844   // collect matching debug values.
845   SmallVector<MachineInstr *, 2> DbgValuesToSink;
846   collectDebugValues(MI, DbgValuesToSink);
847 
848   // Move the instruction.
849   SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
850                        ++MachineBasicBlock::iterator(MI));
851 
852   // Move debug values.
853   for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
854          DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
855     MachineInstr *DbgMI = *DBI;
856     SuccToSinkTo->splice(InsertPos, ParentBlock,  DbgMI,
857                          ++MachineBasicBlock::iterator(DbgMI));
858   }
859 
860   // Conservatively, clear any kill flags, since it's possible that they are no
861   // longer correct.
862   // Note that we have to clear the kill flags for any register this instruction
863   // uses as we may sink over another instruction which currently kills the
864   // used registers.
865   for (MachineOperand &MO : MI.operands()) {
866     if (MO.isReg() && MO.isUse())
867       RegsToClearKillFlags.set(MO.getReg()); // Remember to clear kill flags.
868   }
869 
870   return true;
871 }
872