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