1 //===-- MachineSink.cpp - Sinking for machine instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
17 //===----------------------------------------------------------------------===//
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"
38 #define DEBUG_TYPE "machine-sink"
41 SplitEdges("machine-sink-split",
42 cl::desc("Split critical edges during machine sinking"),
43 cl::init(true), cl::Hidden);
46 UseBlockFreqInfo("machine-sink-bfi",
47 cl::desc("Use block frequency info to find successors to sink"),
48 cl::init(true), cl::Hidden);
51 STATISTIC(NumSunk, "Number of machine instructions sunk");
52 STATISTIC(NumSplit, "Number of critical edges split");
53 STATISTIC(NumCoalesces, "Number of copies coalesced");
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
63 const MachineBlockFrequencyInfo *MBFI;
66 // Remember which edges have been considered for breaking.
67 SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8>
69 // Remember which edges we are about to split.
70 // This is different from CEBCandidates since those edges
72 SetVector<std::pair<MachineBasicBlock*,MachineBasicBlock*> > ToSplit;
74 SparseBitVector<> RegsToClearKillFlags;
76 // Cache all successors to a MachineBasicBlock, sorted by frequency info and
77 // loop depth. AllSuccessors is lazily populated.
78 std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>
82 static char ID; // Pass identification
83 MachineSinking() : MachineFunctionPass(ID) {
84 initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
87 bool runOnMachineFunction(MachineFunction &MF) override;
89 void getAnalysisUsage(AnalysisUsage &AU) const override {
91 MachineFunctionPass::getAnalysisUsage(AU);
92 AU.addRequired<AliasAnalysis>();
93 AU.addRequired<MachineDominatorTree>();
94 AU.addRequired<MachinePostDominatorTree>();
95 AU.addRequired<MachineLoopInfo>();
96 AU.addPreserved<MachineDominatorTree>();
97 AU.addPreserved<MachinePostDominatorTree>();
98 AU.addPreserved<MachineLoopInfo>();
100 AU.addRequired<MachineBlockFrequencyInfo>();
103 void releaseMemory() override {
104 CEBCandidates.clear();
108 bool ProcessBlock(MachineBasicBlock &MBB);
109 bool isWorthBreakingCriticalEdge(MachineInstr *MI,
110 MachineBasicBlock *From,
111 MachineBasicBlock *To);
112 /// \brief Postpone the splitting of the given critical
113 /// edge (\p From, \p To).
115 /// We do not split the edges on the fly. Indeed, this invalidates
116 /// the dominance information and thus triggers a lot of updates
117 /// of that information underneath.
118 /// Instead, we postpone all the splits after each iteration of
119 /// the main loop. That way, the information is at least valid
120 /// for the lifetime of an iteration.
122 /// \return True if the edge is marked as toSplit, false otherwise.
123 /// False can be returned if, for instance, this is not profitable.
124 bool PostponeSplitCriticalEdge(MachineInstr *MI,
125 MachineBasicBlock *From,
126 MachineBasicBlock *To,
128 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
129 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
130 MachineBasicBlock *DefMBB,
131 bool &BreakPHIEdge, bool &LocalUse) const;
132 MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, MachineBasicBlock *MBB,
134 bool isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
135 MachineBasicBlock *MBB,
136 MachineBasicBlock *SuccToSinkTo);
138 bool PerformTrivialForwardCoalescing(MachineInstr *MI,
139 MachineBasicBlock *MBB);
141 SmallVector<MachineBasicBlock *, 4> &
142 GetAllSortedSuccessors(MachineInstr *MI, MachineBasicBlock *MBB);
144 } // end anonymous namespace
146 char MachineSinking::ID = 0;
147 char &llvm::MachineSinkingID = MachineSinking::ID;
148 INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
149 "Machine code sinking", false, false)
150 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
151 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
152 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
153 INITIALIZE_PASS_END(MachineSinking, "machine-sink",
154 "Machine code sinking", false, false)
156 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
157 MachineBasicBlock *MBB) {
161 unsigned SrcReg = MI->getOperand(1).getReg();
162 unsigned DstReg = MI->getOperand(0).getReg();
163 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
164 !TargetRegisterInfo::isVirtualRegister(DstReg) ||
165 !MRI->hasOneNonDBGUse(SrcReg))
168 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
169 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
173 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
174 if (DefMI->isCopyLike())
176 DEBUG(dbgs() << "Coalescing: " << *DefMI);
177 DEBUG(dbgs() << "*** to: " << *MI);
178 MRI->replaceRegWith(DstReg, SrcReg);
179 MI->eraseFromParent();
181 // Conservatively, clear any kill flags, since it's possible that they are no
183 MRI->clearKillFlags(SrcReg);
189 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
190 /// occur in blocks dominated by the specified block. If any use is in the
191 /// definition block, then return false since it is never legal to move def
194 MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
195 MachineBasicBlock *MBB,
196 MachineBasicBlock *DefMBB,
198 bool &LocalUse) const {
199 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
200 "Only makes sense for vregs");
202 // Ignore debug uses because debug info doesn't affect the code.
203 if (MRI->use_nodbg_empty(Reg))
206 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
207 // into and they are all PHI nodes. In this case, machine-sink must break
208 // the critical edge first. e.g.
210 // BB#1: derived from LLVM BB %bb4.preheader
211 // Predecessors according to CFG: BB#0
213 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
215 // JE_4 <BB#37>, %EFLAGS<imp-use>
216 // Successors according to CFG: BB#37 BB#2
218 // BB#2: derived from LLVM BB %bb.nph
219 // Predecessors according to CFG: BB#0 BB#1
220 // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
222 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
223 MachineInstr *UseInst = MO.getParent();
224 unsigned OpNo = &MO - &UseInst->getOperand(0);
225 MachineBasicBlock *UseBlock = UseInst->getParent();
226 if (!(UseBlock == MBB && UseInst->isPHI() &&
227 UseInst->getOperand(OpNo+1).getMBB() == DefMBB)) {
228 BreakPHIEdge = false;
235 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
236 // Determine the block of the use.
237 MachineInstr *UseInst = MO.getParent();
238 unsigned OpNo = &MO - &UseInst->getOperand(0);
239 MachineBasicBlock *UseBlock = UseInst->getParent();
240 if (UseInst->isPHI()) {
241 // PHI nodes use the operand in the predecessor block, not the block with
243 UseBlock = UseInst->getOperand(OpNo+1).getMBB();
244 } else if (UseBlock == DefMBB) {
249 // Check that it dominates.
250 if (!DT->dominates(MBB, UseBlock))
257 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
258 if (skipOptnoneFunction(*MF.getFunction()))
261 DEBUG(dbgs() << "******** Machine Sinking ********\n");
263 TII = MF.getSubtarget().getInstrInfo();
264 TRI = MF.getSubtarget().getRegisterInfo();
265 MRI = &MF.getRegInfo();
266 DT = &getAnalysis<MachineDominatorTree>();
267 PDT = &getAnalysis<MachinePostDominatorTree>();
268 LI = &getAnalysis<MachineLoopInfo>();
269 MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr;
270 AA = &getAnalysis<AliasAnalysis>();
272 bool EverMadeChange = false;
275 bool MadeChange = false;
277 // Process all basic blocks.
278 CEBCandidates.clear();
281 MadeChange |= ProcessBlock(MBB);
283 // If we have anything we marked as toSplit, split it now.
284 for (auto &Pair : ToSplit) {
285 auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, this);
286 if (NewSucc != nullptr) {
287 DEBUG(dbgs() << " *** Splitting critical edge:"
288 " BB#" << Pair.first->getNumber()
289 << " -- BB#" << NewSucc->getNumber()
290 << " -- BB#" << Pair.second->getNumber() << '\n');
294 DEBUG(dbgs() << " *** Not legal to break critical edge\n");
296 // If this iteration over the code changed anything, keep iterating.
297 if (!MadeChange) break;
298 EverMadeChange = true;
301 // Now clear any kill flags for recorded registers.
302 for (auto I : RegsToClearKillFlags)
303 MRI->clearKillFlags(I);
304 RegsToClearKillFlags.clear();
306 return EverMadeChange;
309 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
310 // Can't sink anything out of a block that has less than two successors.
311 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
313 // Don't bother sinking code out of unreachable blocks. In addition to being
314 // unprofitable, it can also lead to infinite looping, because in an
315 // unreachable loop there may be nowhere to stop.
316 if (!DT->isReachableFromEntry(&MBB)) return false;
318 bool MadeChange = false;
320 // MBB changed, reset all cached information.
321 AllSuccessors.clear();
323 // Walk the basic block bottom-up. Remember if we saw a store.
324 MachineBasicBlock::iterator I = MBB.end();
326 bool ProcessedBegin, SawStore = false;
328 MachineInstr *MI = I; // The instruction to sink.
330 // Predecrement I (if it's not begin) so that it isn't invalidated by
332 ProcessedBegin = I == MBB.begin();
336 if (MI->isDebugValue())
339 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
345 if (SinkInstruction(MI, SawStore))
346 ++NumSunk, MadeChange = true;
348 // If we just processed the first instruction in the block, we're done.
349 } while (!ProcessedBegin);
354 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
355 MachineBasicBlock *From,
356 MachineBasicBlock *To) {
357 // FIXME: Need much better heuristics.
359 // If the pass has already considered breaking this edge (during this pass
360 // through the function), then let's go ahead and break it. This means
361 // sinking multiple "cheap" instructions into the same block.
362 if (!CEBCandidates.insert(std::make_pair(From, To)).second)
365 if (!MI->isCopy() && !TII->isAsCheapAsAMove(MI))
368 // MI is cheap, we probably don't want to break the critical edge for it.
369 // However, if this would allow some definitions of its source operands
370 // to be sunk then it's probably worth it.
371 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
372 const MachineOperand &MO = MI->getOperand(i);
373 if (!MO.isReg() || !MO.isUse())
375 unsigned Reg = MO.getReg();
379 // We don't move live definitions of physical registers,
380 // so sinking their uses won't enable any opportunities.
381 if (TargetRegisterInfo::isPhysicalRegister(Reg))
384 // If this instruction is the only user of a virtual register,
385 // check if breaking the edge will enable sinking
386 // both this instruction and the defining instruction.
387 if (MRI->hasOneNonDBGUse(Reg)) {
388 // If the definition resides in same MBB,
389 // claim it's likely we can sink these together.
390 // If definition resides elsewhere, we aren't
391 // blocking it from being sunk so don't break the edge.
392 MachineInstr *DefMI = MRI->getVRegDef(Reg);
393 if (DefMI->getParent() == MI->getParent())
401 bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr *MI,
402 MachineBasicBlock *FromBB,
403 MachineBasicBlock *ToBB,
405 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
408 // Avoid breaking back edge. From == To means backedge for single BB loop.
409 if (!SplitEdges || FromBB == ToBB)
412 // Check for backedges of more "complex" loops.
413 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
414 LI->isLoopHeader(ToBB))
417 // It's not always legal to break critical edges and sink the computation
425 // ... no uses of v1024
431 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
440 // ... no uses of v1024
446 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
447 // flow. We need to ensure the new basic block where the computation is
448 // sunk to dominates all the uses.
449 // It's only legal to break critical edge and sink the computation to the
450 // new block if all the predecessors of "To", except for "From", are
451 // not dominated by "From". Given SSA property, this means these
452 // predecessors are dominated by "To".
454 // There is no need to do this check if all the uses are PHI nodes. PHI
455 // sources are only defined on the specific predecessor edges.
457 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
458 E = ToBB->pred_end(); PI != E; ++PI) {
461 if (!DT->dominates(ToBB, *PI))
466 ToSplit.insert(std::make_pair(FromBB, ToBB));
471 static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) {
472 return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence();
475 /// collectDebgValues - Scan instructions following MI and collect any
476 /// matching DBG_VALUEs.
477 static void collectDebugValues(MachineInstr *MI,
478 SmallVectorImpl<MachineInstr *> &DbgValues) {
480 if (!MI->getOperand(0).isReg())
483 MachineBasicBlock::iterator DI = MI; ++DI;
484 for (MachineBasicBlock::iterator DE = MI->getParent()->end();
486 if (!DI->isDebugValue())
488 if (DI->getOperand(0).isReg() &&
489 DI->getOperand(0).getReg() == MI->getOperand(0).getReg())
490 DbgValues.push_back(DI);
494 /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
495 bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
496 MachineBasicBlock *MBB,
497 MachineBasicBlock *SuccToSinkTo) {
498 assert (MI && "Invalid MachineInstr!");
499 assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
501 if (MBB == SuccToSinkTo)
504 // It is profitable if SuccToSinkTo does not post dominate current block.
505 if (!PDT->dominates(SuccToSinkTo, MBB))
508 // It is profitable to sink an instruction from a deeper loop to a shallower
509 // loop, even if the latter post-dominates the former (PR21115).
510 if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo))
513 // Check if only use in post dominated block is PHI instruction.
514 bool NonPHIUse = false;
515 for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
516 MachineBasicBlock *UseBlock = UseInst.getParent();
517 if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
523 // If SuccToSinkTo post dominates then also it may be profitable if MI
524 // can further profitably sinked into another block in next round.
525 bool BreakPHIEdge = false;
526 // FIXME - If finding successor is compile time expensive then cache results.
527 if (MachineBasicBlock *MBB2 = FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge))
528 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2);
530 // If SuccToSinkTo is final destination and it is a post dominator of current
531 // block then it is not profitable to sink MI into SuccToSinkTo block.
535 /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
536 /// computing it if it was not already cached.
537 SmallVector<MachineBasicBlock *, 4> &
538 MachineSinking::GetAllSortedSuccessors(MachineInstr *MI, MachineBasicBlock *MBB) {
540 // Do we have the sorted successors in cache ?
541 auto Succs = AllSuccessors.find(MBB);
542 if (Succs != AllSuccessors.end())
543 return Succs->second;
545 SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->succ_begin(),
548 // Handle cases where sinking can happen but where the sink point isn't a
549 // successor. For example:
555 const std::vector<MachineDomTreeNode *> &Children =
556 DT->getNode(MBB)->getChildren();
557 for (const auto &DTChild : Children)
558 // DomTree children of MBB that have MBB as immediate dominator are added.
559 if (DTChild->getIDom()->getBlock() == MI->getParent() &&
560 // Skip MBBs already added to the AllSuccs vector above.
561 !MBB->isSuccessor(DTChild->getBlock()))
562 AllSuccs.push_back(DTChild->getBlock());
564 // Sort Successors according to their loop depth or block frequency info.
566 AllSuccs.begin(), AllSuccs.end(),
567 [this](const MachineBasicBlock *L, const MachineBasicBlock *R) {
568 uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
569 uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
570 bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0;
571 return HasBlockFreq ? LHSFreq < RHSFreq
572 : LI->getLoopDepth(L) < LI->getLoopDepth(R);
575 auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
577 return it.first->second;
580 /// FindSuccToSinkTo - Find a successor to sink this instruction to.
581 MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI,
582 MachineBasicBlock *MBB,
583 bool &BreakPHIEdge) {
585 assert (MI && "Invalid MachineInstr!");
586 assert (MBB && "Invalid MachineBasicBlock!");
588 // Loop over all the operands of the specified instruction. If there is
589 // anything we can't handle, bail out.
591 // SuccToSinkTo - This is the successor to sink this instruction to, once we
593 MachineBasicBlock *SuccToSinkTo = nullptr;
594 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
595 const MachineOperand &MO = MI->getOperand(i);
596 if (!MO.isReg()) continue; // Ignore non-register operands.
598 unsigned Reg = MO.getReg();
599 if (Reg == 0) continue;
601 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
603 // If the physreg has no defs anywhere, it's just an ambient register
604 // and we can freely move its uses. Alternatively, if it's allocatable,
605 // it could get allocated to something with a def during allocation.
606 if (!MRI->isConstantPhysReg(Reg, *MBB->getParent()))
608 } else if (!MO.isDead()) {
609 // A def that isn't dead. We can't move it.
613 // Virtual register uses are always safe to sink.
614 if (MO.isUse()) continue;
616 // If it's not safe to move defs of the register class, then abort.
617 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
620 // Virtual register defs can only be sunk if all their uses are in blocks
621 // dominated by one of the successors.
623 // If a previous operand picked a block to sink to, then this operand
624 // must be sinkable to the same block.
625 bool LocalUse = false;
626 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
627 BreakPHIEdge, LocalUse))
633 // Otherwise, we should look at all the successors and decide which one
634 // we should sink to. If we have reliable block frequency information
635 // (frequency != 0) available, give successors with smaller frequencies
636 // higher priority, otherwise prioritize smaller loop depths.
637 for (MachineBasicBlock *SuccBlock : GetAllSortedSuccessors(MI, MBB)) {
638 bool LocalUse = false;
639 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
640 BreakPHIEdge, LocalUse)) {
641 SuccToSinkTo = SuccBlock;
645 // Def is used locally, it's never safe to move this def.
649 // If we couldn't find a block to sink to, ignore this instruction.
652 if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo))
657 // It is not possible to sink an instruction into its own block. This can
658 // happen with loops.
659 if (MBB == SuccToSinkTo)
662 // It's not safe to sink instructions to EH landing pad. Control flow into
663 // landing pad is implicitly defined.
664 if (SuccToSinkTo && SuccToSinkTo->isLandingPad())
670 /// SinkInstruction - Determine whether it is safe to sink the specified machine
671 /// instruction out of its current block into a successor.
672 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
673 // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to
674 // be close to the source to make it easier to coalesce.
675 if (AvoidsSinking(MI, MRI))
678 // Check if it's safe to move the instruction.
679 if (!MI->isSafeToMove(AA, SawStore))
682 // Convergent operations may only be moved to control equivalent locations.
683 if (MI->isConvergent())
686 // FIXME: This should include support for sinking instructions within the
687 // block they are currently in to shorten the live ranges. We often get
688 // instructions sunk into the top of a large block, but it would be better to
689 // also sink them down before their first use in the block. This xform has to
690 // be careful not to *increase* register pressure though, e.g. sinking
691 // "x = y + z" down if it kills y and z would increase the live ranges of y
692 // and z and only shrink the live range of x.
694 bool BreakPHIEdge = false;
695 MachineBasicBlock *ParentBlock = MI->getParent();
696 MachineBasicBlock *SuccToSinkTo = FindSuccToSinkTo(MI, ParentBlock,
699 // If there are no outputs, it must have side-effects.
704 // If the instruction to move defines a dead physical register which is live
705 // when leaving the basic block, don't move it because it could turn into a
706 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
707 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
708 const MachineOperand &MO = MI->getOperand(I);
709 if (!MO.isReg()) continue;
710 unsigned Reg = MO.getReg();
711 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
712 if (SuccToSinkTo->isLiveIn(Reg))
716 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
718 // If the block has multiple predecessors, this is a critical edge.
719 // Decide if we can sink along it or need to break the edge.
720 if (SuccToSinkTo->pred_size() > 1) {
721 // We cannot sink a load across a critical edge - there may be stores in
723 bool TryBreak = false;
725 if (!MI->isSafeToMove(AA, store)) {
726 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
730 // We don't want to sink across a critical edge if we don't dominate the
731 // successor. We could be introducing calculations to new code paths.
732 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
733 DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
737 // Don't sink instructions into a loop.
738 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
739 DEBUG(dbgs() << " *** NOTE: Loop header found\n");
743 // Otherwise we are OK with sinking along a critical edge.
745 DEBUG(dbgs() << "Sinking along critical edge.\n");
747 // Mark this edge as to be split.
748 // If the edge can actually be split, the next iteration of the main loop
749 // will sink MI in the newly created block.
751 PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
753 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
754 "break critical edge\n");
755 // The instruction will not be sunk this time.
761 // BreakPHIEdge is true if all the uses are in the successor MBB being
762 // sunken into and they are all PHI nodes. In this case, machine-sink must
763 // break the critical edge first.
764 bool Status = PostponeSplitCriticalEdge(MI, ParentBlock,
765 SuccToSinkTo, BreakPHIEdge);
767 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
768 "break critical edge\n");
769 // The instruction will not be sunk this time.
773 // Determine where to insert into. Skip phi nodes.
774 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
775 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
778 // collect matching debug values.
779 SmallVector<MachineInstr *, 2> DbgValuesToSink;
780 collectDebugValues(MI, DbgValuesToSink);
782 // Move the instruction.
783 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
784 ++MachineBasicBlock::iterator(MI));
786 // Move debug values.
787 for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
788 DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
789 MachineInstr *DbgMI = *DBI;
790 SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI,
791 ++MachineBasicBlock::iterator(DbgMI));
794 // Conservatively, clear any kill flags, since it's possible that they are no
796 // Note that we have to clear the kill flags for any register this instruction
797 // uses as we may sink over another instruction which currently kills the
799 for (MachineOperand &MO : MI->operands()) {
800 if (MO.isReg() && MO.isUse())
801 RegsToClearKillFlags.set(MO.getReg()); // Remember to clear kill flags.