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