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