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