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 #define DEBUG_TYPE "machine-sink"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/MachineDominators.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
36 SplitEdges("machine-sink-split",
37 cl::desc("Split critical edges during machine sinking"),
38 cl::init(true), cl::Hidden);
40 STATISTIC(NumSunk, "Number of machine instructions sunk");
41 STATISTIC(NumSplit, "Number of critical edges split");
42 STATISTIC(NumCoalesces, "Number of copies coalesced");
45 class MachineSinking : public MachineFunctionPass {
46 const TargetInstrInfo *TII;
47 const TargetRegisterInfo *TRI;
48 MachineRegisterInfo *MRI; // Machine register information
49 MachineDominatorTree *DT; // Machine dominator tree
52 BitVector AllocatableSet; // Which physregs are allocatable?
54 // Remember which edges have been considered for breaking.
55 SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8>
59 static char ID; // Pass identification
60 MachineSinking() : MachineFunctionPass(ID) {
61 initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
64 virtual bool runOnMachineFunction(MachineFunction &MF);
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68 MachineFunctionPass::getAnalysisUsage(AU);
69 AU.addRequired<AliasAnalysis>();
70 AU.addRequired<MachineDominatorTree>();
71 AU.addRequired<MachineLoopInfo>();
72 AU.addPreserved<MachineDominatorTree>();
73 AU.addPreserved<MachineLoopInfo>();
76 virtual void releaseMemory() {
77 CEBCandidates.clear();
81 bool ProcessBlock(MachineBasicBlock &MBB);
82 bool isWorthBreakingCriticalEdge(MachineInstr *MI,
83 MachineBasicBlock *From,
84 MachineBasicBlock *To);
85 MachineBasicBlock *SplitCriticalEdge(MachineInstr *MI,
86 MachineBasicBlock *From,
87 MachineBasicBlock *To,
89 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
90 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
91 MachineBasicBlock *DefMBB,
92 bool &BreakPHIEdge, bool &LocalUse) const;
93 MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, MachineBasicBlock *MBB,
95 bool isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
96 MachineBasicBlock *MBB,
97 MachineBasicBlock *SuccToSinkTo);
99 bool PerformTrivialForwardCoalescing(MachineInstr *MI,
100 MachineBasicBlock *MBB);
102 } // end anonymous namespace
104 char MachineSinking::ID = 0;
105 INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
106 "Machine code sinking", false, false)
107 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
108 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
109 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
110 INITIALIZE_PASS_END(MachineSinking, "machine-sink",
111 "Machine code sinking", false, false)
113 FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
115 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
116 MachineBasicBlock *MBB) {
120 unsigned SrcReg = MI->getOperand(1).getReg();
121 unsigned DstReg = MI->getOperand(0).getReg();
122 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
123 !TargetRegisterInfo::isVirtualRegister(DstReg) ||
124 !MRI->hasOneNonDBGUse(SrcReg))
127 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
128 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
132 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
133 if (DefMI->isCopyLike())
135 DEBUG(dbgs() << "Coalescing: " << *DefMI);
136 DEBUG(dbgs() << "*** to: " << *MI);
137 MRI->replaceRegWith(DstReg, SrcReg);
138 MI->eraseFromParent();
143 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
144 /// occur in blocks dominated by the specified block. If any use is in the
145 /// definition block, then return false since it is never legal to move def
148 MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
149 MachineBasicBlock *MBB,
150 MachineBasicBlock *DefMBB,
152 bool &LocalUse) const {
153 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
154 "Only makes sense for vregs");
156 // Ignore debug uses because debug info doesn't affect the code.
157 if (MRI->use_nodbg_empty(Reg))
160 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
161 // into and they are all PHI nodes. In this case, machine-sink must break
162 // the critical edge first. e.g.
164 // BB#1: derived from LLVM BB %bb4.preheader
165 // Predecessors according to CFG: BB#0
167 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
169 // JE_4 <BB#37>, %EFLAGS<imp-use>
170 // Successors according to CFG: BB#37 BB#2
172 // BB#2: derived from LLVM BB %bb.nph
173 // Predecessors according to CFG: BB#0 BB#1
174 // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
176 for (MachineRegisterInfo::use_nodbg_iterator
177 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
179 MachineInstr *UseInst = &*I;
180 MachineBasicBlock *UseBlock = UseInst->getParent();
181 if (!(UseBlock == MBB && UseInst->isPHI() &&
182 UseInst->getOperand(I.getOperandNo()+1).getMBB() == DefMBB)) {
183 BreakPHIEdge = false;
190 for (MachineRegisterInfo::use_nodbg_iterator
191 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
193 // Determine the block of the use.
194 MachineInstr *UseInst = &*I;
195 MachineBasicBlock *UseBlock = UseInst->getParent();
196 if (UseInst->isPHI()) {
197 // PHI nodes use the operand in the predecessor block, not the block with
199 UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
200 } else if (UseBlock == DefMBB) {
205 // Check that it dominates.
206 if (!DT->dominates(MBB, UseBlock))
213 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
214 DEBUG(dbgs() << "******** Machine Sinking ********\n");
216 const TargetMachine &TM = MF.getTarget();
217 TII = TM.getInstrInfo();
218 TRI = TM.getRegisterInfo();
219 MRI = &MF.getRegInfo();
220 DT = &getAnalysis<MachineDominatorTree>();
221 LI = &getAnalysis<MachineLoopInfo>();
222 AA = &getAnalysis<AliasAnalysis>();
223 AllocatableSet = TRI->getAllocatableSet(MF);
225 bool EverMadeChange = false;
228 bool MadeChange = false;
230 // Process all basic blocks.
231 CEBCandidates.clear();
232 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
234 MadeChange |= ProcessBlock(*I);
236 // If this iteration over the code changed anything, keep iterating.
237 if (!MadeChange) break;
238 EverMadeChange = true;
240 return EverMadeChange;
243 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
244 // Can't sink anything out of a block that has less than two successors.
245 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
247 // Don't bother sinking code out of unreachable blocks. In addition to being
248 // unprofitable, it can also lead to infinite looping, because in an
249 // unreachable loop there may be nowhere to stop.
250 if (!DT->isReachableFromEntry(&MBB)) return false;
252 bool MadeChange = false;
254 // Walk the basic block bottom-up. Remember if we saw a store.
255 MachineBasicBlock::iterator I = MBB.end();
257 bool ProcessedBegin, SawStore = false;
259 MachineInstr *MI = I; // The instruction to sink.
261 // Predecrement I (if it's not begin) so that it isn't invalidated by
263 ProcessedBegin = I == MBB.begin();
267 if (MI->isDebugValue())
270 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
276 if (SinkInstruction(MI, SawStore))
277 ++NumSunk, MadeChange = true;
279 // If we just processed the first instruction in the block, we're done.
280 } while (!ProcessedBegin);
285 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
286 MachineBasicBlock *From,
287 MachineBasicBlock *To) {
288 // FIXME: Need much better heuristics.
290 // If the pass has already considered breaking this edge (during this pass
291 // through the function), then let's go ahead and break it. This means
292 // sinking multiple "cheap" instructions into the same block.
293 if (!CEBCandidates.insert(std::make_pair(From, To)))
296 if (!MI->isCopy() && !MI->isAsCheapAsAMove())
299 // MI is cheap, we probably don't want to break the critical edge for it.
300 // However, if this would allow some definitions of its source operands
301 // to be sunk then it's probably worth it.
302 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
303 const MachineOperand &MO = MI->getOperand(i);
304 if (!MO.isReg()) continue;
305 unsigned Reg = MO.getReg();
306 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg))
308 if (MRI->hasOneNonDBGUse(Reg))
315 MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI,
316 MachineBasicBlock *FromBB,
317 MachineBasicBlock *ToBB,
319 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
322 // Avoid breaking back edge. From == To means backedge for single BB loop.
323 if (!SplitEdges || FromBB == ToBB)
326 // Check for backedges of more "complex" loops.
327 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
328 LI->isLoopHeader(ToBB))
331 // It's not always legal to break critical edges and sink the computation
339 // ... no uses of v1024
345 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
354 // ... no uses of v1024
360 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
361 // flow. We need to ensure the new basic block where the computation is
362 // sunk to dominates all the uses.
363 // It's only legal to break critical edge and sink the computation to the
364 // new block if all the predecessors of "To", except for "From", are
365 // not dominated by "From". Given SSA property, this means these
366 // predecessors are dominated by "To".
368 // There is no need to do this check if all the uses are PHI nodes. PHI
369 // sources are only defined on the specific predecessor edges.
371 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
372 E = ToBB->pred_end(); PI != E; ++PI) {
375 if (!DT->dominates(ToBB, *PI))
380 return FromBB->SplitCriticalEdge(ToBB, this);
383 static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) {
384 return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence();
387 /// collectDebgValues - Scan instructions following MI and collect any
388 /// matching DBG_VALUEs.
389 static void collectDebugValues(MachineInstr *MI,
390 SmallVector<MachineInstr *, 2> & DbgValues) {
392 if (!MI->getOperand(0).isReg())
395 MachineBasicBlock::iterator DI = MI; ++DI;
396 for (MachineBasicBlock::iterator DE = MI->getParent()->end();
398 if (!DI->isDebugValue())
400 if (DI->getOperand(0).isReg() &&
401 DI->getOperand(0).getReg() == MI->getOperand(0).getReg())
402 DbgValues.push_back(DI);
406 /// isPostDominatedBy - Return true if A is post dominated by B.
407 static bool isPostDominatedBy(MachineBasicBlock *A, MachineBasicBlock *B) {
409 // FIXME - Use real post dominator.
410 if (A->succ_size() != 2)
412 MachineBasicBlock::succ_iterator I = A->succ_begin();
415 MachineBasicBlock *OtherSuccBlock = *I;
416 if (OtherSuccBlock->succ_size() != 1 ||
417 *(OtherSuccBlock->succ_begin()) != B)
423 /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
424 bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
425 MachineBasicBlock *MBB,
426 MachineBasicBlock *SuccToSinkTo) {
427 assert (MI && "Invalid MachineInstr!");
428 assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
430 if (MBB == SuccToSinkTo)
433 // It is profitable if SuccToSinkTo does not post dominate current block.
434 if (!isPostDominatedBy(MBB, SuccToSinkTo))
437 // Check if only use in post dominated block is PHI instruction.
438 bool NonPHIUse = false;
439 for (MachineRegisterInfo::use_nodbg_iterator
440 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
442 MachineInstr *UseInst = &*I;
443 MachineBasicBlock *UseBlock = UseInst->getParent();
444 if (UseBlock == SuccToSinkTo && !UseInst->isPHI())
450 // If SuccToSinkTo post dominates then also it may be profitable if MI
451 // can further profitably sinked into another block in next round.
452 bool BreakPHIEdge = false;
453 // FIXME - If finding successor is compile time expensive then catch results.
454 if (MachineBasicBlock *MBB2 = FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge))
455 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2);
457 // If SuccToSinkTo is final destination and it is a post dominator of current
458 // block then it is not profitable to sink MI into SuccToSinkTo block.
462 /// FindSuccToSinkTo - Find a successor to sink this instruction to.
463 MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI,
464 MachineBasicBlock *MBB,
465 bool &BreakPHIEdge) {
467 assert (MI && "Invalid MachineInstr!");
468 assert (MBB && "Invalid MachineBasicBlock!");
470 // Loop over all the operands of the specified instruction. If there is
471 // anything we can't handle, bail out.
473 // SuccToSinkTo - This is the successor to sink this instruction to, once we
475 MachineBasicBlock *SuccToSinkTo = 0;
476 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
477 const MachineOperand &MO = MI->getOperand(i);
478 if (!MO.isReg()) continue; // Ignore non-register operands.
480 unsigned Reg = MO.getReg();
481 if (Reg == 0) continue;
483 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
485 // If the physreg has no defs anywhere, it's just an ambient register
486 // and we can freely move its uses. Alternatively, if it's allocatable,
487 // it could get allocated to something with a def during allocation.
488 if (!MRI->def_empty(Reg))
491 if (AllocatableSet.test(Reg))
494 // Check for a def among the register's aliases too.
495 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
496 unsigned AliasReg = *Alias;
497 if (!MRI->def_empty(AliasReg))
500 if (AllocatableSet.test(AliasReg))
503 } else if (!MO.isDead()) {
504 // A def that isn't dead. We can't move it.
508 // Virtual register uses are always safe to sink.
509 if (MO.isUse()) continue;
511 // If it's not safe to move defs of the register class, then abort.
512 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
515 // FIXME: This picks a successor to sink into based on having one
516 // successor that dominates all the uses. However, there are cases where
517 // sinking can happen but where the sink point isn't a successor. For
524 // the instruction could be sunk over the whole diamond for the
525 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
528 // Virtual register defs can only be sunk if all their uses are in blocks
529 // dominated by one of the successors.
531 // If a previous operand picked a block to sink to, then this operand
532 // must be sinkable to the same block.
533 bool LocalUse = false;
534 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
535 BreakPHIEdge, LocalUse))
541 // Otherwise, we should look at all the successors and decide which one
542 // we should sink to.
543 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
544 E = MBB->succ_end(); SI != E; ++SI) {
545 MachineBasicBlock *SuccBlock = *SI;
546 bool LocalUse = false;
547 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
548 BreakPHIEdge, LocalUse)) {
549 SuccToSinkTo = SuccBlock;
553 // Def is used locally, it's never safe to move this def.
557 // If we couldn't find a block to sink to, ignore this instruction.
558 if (SuccToSinkTo == 0)
560 else if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo))
565 // It is not possible to sink an instruction into its own block. This can
566 // happen with loops.
567 if (MBB == SuccToSinkTo)
570 // It's not safe to sink instructions to EH landing pad. Control flow into
571 // landing pad is implicitly defined.
572 if (SuccToSinkTo && SuccToSinkTo->isLandingPad())
578 /// SinkInstruction - Determine whether it is safe to sink the specified machine
579 /// instruction out of its current block into a successor.
580 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
581 // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to
582 // be close to the source to make it easier to coalesce.
583 if (AvoidsSinking(MI, MRI))
586 // Check if it's safe to move the instruction.
587 if (!MI->isSafeToMove(TII, AA, SawStore))
590 // FIXME: This should include support for sinking instructions within the
591 // block they are currently in to shorten the live ranges. We often get
592 // instructions sunk into the top of a large block, but it would be better to
593 // also sink them down before their first use in the block. This xform has to
594 // be careful not to *increase* register pressure though, e.g. sinking
595 // "x = y + z" down if it kills y and z would increase the live ranges of y
596 // and z and only shrink the live range of x.
598 bool BreakPHIEdge = false;
599 MachineBasicBlock *ParentBlock = MI->getParent();
600 MachineBasicBlock *SuccToSinkTo = FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge);
602 // If there are no outputs, it must have side-effects.
603 if (SuccToSinkTo == 0)
607 // If the instruction to move defines a dead physical register which is live
608 // when leaving the basic block, don't move it because it could turn into a
609 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
610 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
611 const MachineOperand &MO = MI->getOperand(I);
612 if (!MO.isReg()) continue;
613 unsigned Reg = MO.getReg();
614 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
615 if (SuccToSinkTo->isLiveIn(Reg))
619 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
621 // If the block has multiple predecessors, this would introduce computation on
622 // a path that it doesn't already exist. We could split the critical edge,
623 // but for now we just punt.
624 if (SuccToSinkTo->pred_size() > 1) {
625 // We cannot sink a load across a critical edge - there may be stores in
627 bool TryBreak = false;
629 if (!MI->isSafeToMove(TII, AA, store)) {
630 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
634 // We don't want to sink across a critical edge if we don't dominate the
635 // successor. We could be introducing calculations to new code paths.
636 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
637 DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
641 // Don't sink instructions into a loop.
642 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
643 DEBUG(dbgs() << " *** NOTE: Loop header found\n");
647 // Otherwise we are OK with sinking along a critical edge.
649 DEBUG(dbgs() << "Sinking along critical edge.\n");
651 MachineBasicBlock *NewSucc =
652 SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
654 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
655 "break critical edge\n");
658 DEBUG(dbgs() << " *** Splitting critical edge:"
659 " BB#" << ParentBlock->getNumber()
660 << " -- BB#" << NewSucc->getNumber()
661 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
662 SuccToSinkTo = NewSucc;
664 BreakPHIEdge = false;
670 // BreakPHIEdge is true if all the uses are in the successor MBB being
671 // sunken into and they are all PHI nodes. In this case, machine-sink must
672 // break the critical edge first.
673 MachineBasicBlock *NewSucc = SplitCriticalEdge(MI, ParentBlock,
674 SuccToSinkTo, BreakPHIEdge);
676 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
677 "break critical edge\n");
681 DEBUG(dbgs() << " *** Splitting critical edge:"
682 " BB#" << ParentBlock->getNumber()
683 << " -- BB#" << NewSucc->getNumber()
684 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
685 SuccToSinkTo = NewSucc;
689 // Determine where to insert into. Skip phi nodes.
690 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
691 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
694 // collect matching debug values.
695 SmallVector<MachineInstr *, 2> DbgValuesToSink;
696 collectDebugValues(MI, DbgValuesToSink);
698 // Move the instruction.
699 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
700 ++MachineBasicBlock::iterator(MI));
702 // Move debug values.
703 for (SmallVector<MachineInstr *, 2>::iterator DBI = DbgValuesToSink.begin(),
704 DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
705 MachineInstr *DbgMI = *DBI;
706 SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI,
707 ++MachineBasicBlock::iterator(DbgMI));
710 // Conservatively, clear any kill flags, since it's possible that they are no