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