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(false), cl::Hidden);
39 static cl::opt<unsigned>
40 SplitLimit("split-limit",
41 cl::init(~0u), cl::Hidden);
43 STATISTIC(NumSunk, "Number of machine instructions sunk");
44 STATISTIC(NumSplit, "Number of critical edges split");
45 STATISTIC(NumCoalesces, "Number of copies coalesced");
48 class MachineSinking : public MachineFunctionPass {
49 const TargetInstrInfo *TII;
50 const TargetRegisterInfo *TRI;
51 MachineRegisterInfo *MRI; // Machine register information
52 MachineDominatorTree *DT; // Machine dominator tree
55 BitVector AllocatableSet; // Which physregs are allocatable?
57 // Remember which edges have been considered for breaking.
58 SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8>
62 static char ID; // Pass identification
63 MachineSinking() : MachineFunctionPass(ID) {}
65 virtual bool runOnMachineFunction(MachineFunction &MF);
67 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 MachineFunctionPass::getAnalysisUsage(AU);
70 AU.addRequired<AliasAnalysis>();
71 AU.addRequired<MachineDominatorTree>();
72 AU.addRequired<MachineLoopInfo>();
73 AU.addPreserved<MachineDominatorTree>();
74 AU.addPreserved<MachineLoopInfo>();
77 virtual void releaseMemory() {
78 CEBCandidates.clear();
82 bool ProcessBlock(MachineBasicBlock &MBB);
83 bool isWorthBreakingCriticalEdge(MachineInstr *MI,
84 MachineBasicBlock *From,
85 MachineBasicBlock *To);
86 MachineBasicBlock *SplitCriticalEdge(MachineInstr *MI,
87 MachineBasicBlock *From,
88 MachineBasicBlock *To,
90 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
91 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
92 MachineBasicBlock *DefMBB,
93 SmallPtrSet<MachineInstr*, 4> &PHIUses,
94 bool &NonPHIUse, bool &LocalUse) const;
95 bool PerformTrivialForwardCoalescing(MachineInstr *MI,
96 MachineBasicBlock *MBB);
98 } // end anonymous namespace
100 char MachineSinking::ID = 0;
101 INITIALIZE_PASS(MachineSinking, "machine-sink",
102 "Machine code sinking", false, false);
104 FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
106 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
107 MachineBasicBlock *MBB) {
111 unsigned SrcReg = MI->getOperand(1).getReg();
112 unsigned DstReg = MI->getOperand(0).getReg();
113 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
114 !TargetRegisterInfo::isVirtualRegister(DstReg) ||
115 !MRI->hasOneNonDBGUse(SrcReg))
118 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
119 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
123 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
124 if (DefMI->isCopyLike())
126 DEBUG(dbgs() << "Coalescing: " << *DefMI);
127 DEBUG(dbgs() << "*** to: " << *MI);
128 MRI->replaceRegWith(DstReg, SrcReg);
129 MI->eraseFromParent();
134 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
135 /// occur in blocks dominated by the specified block. If any use is in the
136 /// definition block, then return false since it is never legal to move def
139 MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
140 MachineBasicBlock *MBB,
141 MachineBasicBlock *DefMBB,
142 SmallPtrSet<MachineInstr*, 4> &PHIUses,
143 bool &NonPHIUse, bool &LocalUse) const {
144 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
145 "Only makes sense for vregs");
146 // Ignoring debug uses is necessary so debug info doesn't affect the code.
147 // This may leave a referencing dbg_value in the original block, before
148 // the definition of the vreg. Dwarf generator handles this although the
149 // user might not get the right info at runtime.
150 for (MachineRegisterInfo::use_nodbg_iterator
151 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
153 // Determine the block of the use.
154 MachineInstr *UseInst = &*I;
155 MachineBasicBlock *UseBlock = UseInst->getParent();
157 bool isPHI = UseInst->isPHI();
159 PHIUses.insert(UseInst);
162 if (SplitEdges && UseBlock == MBB)
163 // PHI is in the successor BB. 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 // Machine sink should break the critical edge first.
178 // PHI nodes use the operand in the predecessor block, not the block with
180 UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
181 } else if (UseBlock == DefMBB) {
186 // Check that it dominates.
187 if (!DT->dominates(MBB, UseBlock))
194 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
195 DEBUG(dbgs() << "******** Machine Sinking ********\n");
197 const TargetMachine &TM = MF.getTarget();
198 TII = TM.getInstrInfo();
199 TRI = TM.getRegisterInfo();
200 MRI = &MF.getRegInfo();
201 DT = &getAnalysis<MachineDominatorTree>();
202 LI = &getAnalysis<MachineLoopInfo>();
203 AA = &getAnalysis<AliasAnalysis>();
204 AllocatableSet = TRI->getAllocatableSet(MF);
206 bool EverMadeChange = false;
209 bool MadeChange = false;
211 // Process all basic blocks.
212 CEBCandidates.clear();
213 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
215 MadeChange |= ProcessBlock(*I);
217 // If this iteration over the code changed anything, keep iterating.
218 if (!MadeChange) break;
219 EverMadeChange = true;
221 return EverMadeChange;
224 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
225 // Can't sink anything out of a block that has less than two successors.
226 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
228 // Don't bother sinking code out of unreachable blocks. In addition to being
229 // unprofitable, it can also lead to infinite looping, because in an
230 // unreachable loop there may be nowhere to stop.
231 if (!DT->isReachableFromEntry(&MBB)) return false;
233 bool MadeChange = false;
235 // Walk the basic block bottom-up. Remember if we saw a store.
236 MachineBasicBlock::iterator I = MBB.end();
238 bool ProcessedBegin, SawStore = false;
240 MachineInstr *MI = I; // The instruction to sink.
242 // Predecrement I (if it's not begin) so that it isn't invalidated by
244 ProcessedBegin = I == MBB.begin();
248 if (MI->isDebugValue())
251 if (PerformTrivialForwardCoalescing(MI, &MBB))
254 if (SinkInstruction(MI, SawStore))
255 ++NumSunk, MadeChange = true;
257 // If we just processed the first instruction in the block, we're done.
258 } while (!ProcessedBegin);
263 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
264 MachineBasicBlock *From,
265 MachineBasicBlock *To) {
266 // FIXME: Need much better heuristics.
268 // If the pass has already considered breaking this edge (during this pass
269 // through the function), then let's go ahead and break it. This means
270 // sinking multiple "cheap" instructions into the same block.
271 if (!CEBCandidates.insert(std::make_pair(From, To)))
274 if (!(MI->isCopyLike() || MI->getDesc().isAsCheapAsAMove()))
277 // MI is cheap, we probably don't want to break the critical edge for it.
278 // However, if this would allow some definitions of its source operands
279 // to be sunk then it's probably worth it.
280 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
281 const MachineOperand &MO = MI->getOperand(i);
282 if (!MO.isReg()) continue;
283 unsigned Reg = MO.getReg();
284 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg))
286 if (MRI->hasOneNonDBGUse(Reg))
293 MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI,
294 MachineBasicBlock *FromBB,
295 MachineBasicBlock *ToBB,
296 bool HasNonePHIUse) {
297 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
300 // Avoid breaking back edge. From == To means backedge for single BB loop.
301 if (!SplitEdges || NumSplit == SplitLimit || FromBB == ToBB)
304 // Check for backedges of more "complex" loops.
305 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
306 LI->isLoopHeader(ToBB))
309 // It's not always legal to break critical edges and sink the computation
317 // ... no uses of v1024
323 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
332 // ... no uses of v1024
338 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
339 // flow. We need to ensure the new basic block where the computation is
340 // sunk to dominates all the uses.
341 // It's only legal to break critical edge and sink the computation to the
342 // new block if all the predecessors of "To", except for "From", are
343 // not dominated by "From". Given SSA property, this means these
344 // predecessors are dominated by "To".
346 // There is no need to do this check if all the uses are PHI nodes. PHI
347 // sources are only defined on the specific predecessor edges.
349 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
350 E = ToBB->pred_end(); PI != E; ++PI) {
353 if (!DT->dominates(ToBB, *PI))
358 return FromBB->SplitCriticalEdge(ToBB, this);
361 /// SinkInstruction - Determine whether it is safe to sink the specified machine
362 /// instruction out of its current block into a successor.
363 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
364 // Check if it's safe to move the instruction.
365 if (!MI->isSafeToMove(TII, AA, SawStore))
368 // FIXME: This should include support for sinking instructions within the
369 // block they are currently in to shorten the live ranges. We often get
370 // instructions sunk into the top of a large block, but it would be better to
371 // also sink them down before their first use in the block. This xform has to
372 // be careful not to *increase* register pressure though, e.g. sinking
373 // "x = y + z" down if it kills y and z would increase the live ranges of y
374 // and z and only shrink the live range of x.
376 // Loop over all the operands of the specified instruction. If there is
377 // anything we can't handle, bail out.
378 MachineBasicBlock *ParentBlock = MI->getParent();
380 // SuccToSinkTo - This is the successor to sink this instruction to, once we
382 MachineBasicBlock *SuccToSinkTo = 0;
384 SmallSet<unsigned, 4> Defs;
385 SmallPtrSet<MachineInstr*, 4> PHIUses;
386 bool HasNonPHIUse = false;
387 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
388 const MachineOperand &MO = MI->getOperand(i);
389 if (!MO.isReg()) continue; // Ignore non-register operands.
391 unsigned Reg = MO.getReg();
392 if (Reg == 0) continue;
394 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
396 // If the physreg has no defs anywhere, it's just an ambient register
397 // and we can freely move its uses. Alternatively, if it's allocatable,
398 // it could get allocated to something with a def during allocation.
399 if (!MRI->def_empty(Reg))
402 if (AllocatableSet.test(Reg))
405 // Check for a def among the register's aliases too.
406 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
407 unsigned AliasReg = *Alias;
408 if (!MRI->def_empty(AliasReg))
411 if (AllocatableSet.test(AliasReg))
414 } else if (!MO.isDead()) {
415 // A def that isn't dead. We can't move it.
419 // Virtual register uses are always safe to sink.
420 if (MO.isUse()) continue;
423 // If it's not safe to move defs of the register class, then abort.
424 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
427 // FIXME: This picks a successor to sink into based on having one
428 // successor that dominates all the uses. However, there are cases where
429 // sinking can happen but where the sink point isn't a successor. For
436 // the instruction could be sunk over the whole diamond for the
437 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
440 // Virtual register defs can only be sunk if all their uses are in blocks
441 // dominated by one of the successors.
443 // If a previous operand picked a block to sink to, then this operand
444 // must be sinkable to the same block.
445 bool LocalUse = false;
446 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, ParentBlock, PHIUses,
447 HasNonPHIUse, LocalUse))
453 // Otherwise, we should look at all the successors and decide which one
454 // we should sink to.
455 for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
456 E = ParentBlock->succ_end(); SI != E; ++SI) {
457 bool LocalUse = false;
458 if (AllUsesDominatedByBlock(Reg, *SI, ParentBlock, PHIUses,
459 HasNonPHIUse, LocalUse)) {
464 // Def is used locally, it's never safe to move this def.
468 // If we couldn't find a block to sink to, ignore this instruction.
469 if (SuccToSinkTo == 0)
474 // If there are no outputs, it must have side-effects.
475 if (SuccToSinkTo == 0)
478 // It's not safe to sink instructions to EH landing pad. Control flow into
479 // landing pad is implicitly defined.
480 if (SuccToSinkTo->isLandingPad())
483 // It is not possible to sink an instruction into its own block. This can
484 // happen with loops.
485 if (MI->getParent() == SuccToSinkTo)
488 // If the instruction to move defines a dead physical register which is live
489 // when leaving the basic block, don't move it because it could turn into a
490 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
491 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
492 const MachineOperand &MO = MI->getOperand(I);
493 if (!MO.isReg()) continue;
494 unsigned Reg = MO.getReg();
495 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
496 if (SuccToSinkTo->isLiveIn(Reg))
500 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
502 // If the block has multiple predecessors, this would introduce computation on
503 // a path that it doesn't already exist. We could split the critical edge,
504 // but for now we just punt.
505 if (SuccToSinkTo->pred_size() > 1) {
506 // We cannot sink a load across a critical edge - there may be stores in
508 bool TryBreak = false;
510 if (!MI->isSafeToMove(TII, AA, store)) {
511 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
515 // We don't want to sink across a critical edge if we don't dominate the
516 // successor. We could be introducing calculations to new code paths.
517 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
518 DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
522 // Don't sink instructions into a loop.
523 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
524 DEBUG(dbgs() << " *** NOTE: Loop header found\n");
528 // Otherwise we are OK with sinking along a critical edge.
530 DEBUG(dbgs() << "Sinking along critical edge.\n");
532 MachineBasicBlock *NewSucc =
533 SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, HasNonPHIUse);
535 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
536 "break critical edge\n");
539 DEBUG(dbgs() << " *** Splitting critical edge:"
540 " BB#" << ParentBlock->getNumber()
541 << " -- BB#" << NewSucc->getNumber()
542 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
543 SuccToSinkTo = NewSucc;
549 // Determine where to insert into. Skip phi nodes.
550 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
551 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI()) {
552 MachineInstr *PHI = &*InsertPos;
555 if (SplitEdges && PHIUses.count(PHI)) {
556 if (NumSplit == SplitLimit)
559 // A PHI use is in the destination successor so we can't sink the
560 // instruction here. Break the critical edge first!
561 for (unsigned i = 1, e = PHI->getNumOperands(); i != e; i += 2) {
562 unsigned SrcReg = PHI->getOperand(i).getReg();
563 if (Defs.count(SrcReg)) {
564 MachineBasicBlock *SrcMBB = PHI->getOperand(i+1).getMBB();
565 MachineBasicBlock *NewSucc =
566 SplitCriticalEdge(MI, SrcMBB, SuccToSinkTo, HasNonPHIUse);
568 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
569 "break critical edge\n");
573 DEBUG(dbgs() << " *** Splitting critical edge:"
574 " BB#" << SrcMBB->getNumber()
575 << " -- BB#" << NewSucc->getNumber()
576 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
577 SuccToSinkTo = NewSucc;
578 InsertPos = NewSucc->begin();
586 // Move the instruction.
587 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
588 ++MachineBasicBlock::iterator(MI));
590 // Conservatively, clear any kill flags, since it's possible that they are no