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/Target/TargetRegisterInfo.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
32 STATISTIC(NumSunk, "Number of machine instructions sunk");
35 class VISIBILITY_HIDDEN MachineSinking : public MachineFunctionPass {
36 const TargetMachine *TM;
37 const TargetInstrInfo *TII;
38 MachineFunction *CurMF; // Current MachineFunction
39 MachineRegisterInfo *RegInfo; // Machine register information
40 MachineDominatorTree *DT; // Machine dominator tree
43 static char ID; // Pass identification
44 MachineSinking() : MachineFunctionPass(&ID) {}
46 virtual bool runOnMachineFunction(MachineFunction &MF);
48 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
50 MachineFunctionPass::getAnalysisUsage(AU);
51 AU.addRequired<MachineDominatorTree>();
52 AU.addPreserved<MachineDominatorTree>();
55 bool ProcessBlock(MachineBasicBlock &MBB);
56 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
57 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB) const;
59 } // end anonymous namespace
61 char MachineSinking::ID = 0;
62 static RegisterPass<MachineSinking>
63 X("machine-sink", "Machine code sinking");
65 FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
67 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
68 /// occur in blocks dominated by the specified block.
69 bool MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
70 MachineBasicBlock *MBB) const {
71 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
72 "Only makes sense for vregs");
73 for (MachineRegisterInfo::use_iterator I = RegInfo->use_begin(Reg),
74 E = RegInfo->use_end(); I != E; ++I) {
75 // Determine the block of the use.
76 MachineInstr *UseInst = &*I;
77 MachineBasicBlock *UseBlock = UseInst->getParent();
78 if (UseInst->getOpcode() == TargetInstrInfo::PHI) {
79 // PHI nodes use the operand in the predecessor block, not the block with
81 UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
83 // Check that it dominates.
84 if (!DT->dominates(MBB, UseBlock))
92 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
93 DEBUG(errs() << "******** Machine Sinking ********\n");
96 TM = &CurMF->getTarget();
97 TII = TM->getInstrInfo();
98 RegInfo = &CurMF->getRegInfo();
99 DT = &getAnalysis<MachineDominatorTree>();
101 bool EverMadeChange = false;
104 bool MadeChange = false;
106 // Process all basic blocks.
107 for (MachineFunction::iterator I = CurMF->begin(), E = CurMF->end();
109 MadeChange |= ProcessBlock(*I);
111 // If this iteration over the code changed anything, keep iterating.
112 if (!MadeChange) break;
113 EverMadeChange = true;
115 return EverMadeChange;
118 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
119 // Can't sink anything out of a block that has less than two successors.
120 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
122 bool MadeChange = false;
124 // Walk the basic block bottom-up. Remember if we saw a store.
125 MachineBasicBlock::iterator I = MBB.end();
127 bool ProcessedBegin, SawStore = false;
129 MachineInstr *MI = I; // The instruction to sink.
131 // Predecrement I (if it's not begin) so that it isn't invalidated by
133 ProcessedBegin = I == MBB.begin();
137 if (SinkInstruction(MI, SawStore))
138 ++NumSunk, MadeChange = true;
140 // If we just processed the first instruction in the block, we're done.
141 } while (!ProcessedBegin);
146 /// SinkInstruction - Determine whether it is safe to sink the specified machine
147 /// instruction out of its current block into a successor.
148 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
149 // Check if it's safe to move the instruction.
150 if (!MI->isSafeToMove(TII, SawStore))
153 // FIXME: This should include support for sinking instructions within the
154 // block they are currently in to shorten the live ranges. We often get
155 // instructions sunk into the top of a large block, but it would be better to
156 // also sink them down before their first use in the block. This xform has to
157 // be careful not to *increase* register pressure though, e.g. sinking
158 // "x = y + z" down if it kills y and z would increase the live ranges of y
159 // and z and only shrink the live range of x.
161 // Loop over all the operands of the specified instruction. If there is
162 // anything we can't handle, bail out.
163 MachineBasicBlock *ParentBlock = MI->getParent();
165 // SuccToSinkTo - This is the successor to sink this instruction to, once we
167 MachineBasicBlock *SuccToSinkTo = 0;
169 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
170 const MachineOperand &MO = MI->getOperand(i);
171 if (!MO.isReg()) continue; // Ignore non-register operands.
173 unsigned Reg = MO.getReg();
174 if (Reg == 0) continue;
176 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
177 // If this is a physical register use, we can't move it. If it is a def,
178 // we can move it, but only if the def is dead.
179 if (MO.isUse() || !MO.isDead())
182 // Virtual register uses are always safe to sink.
183 if (MO.isUse()) continue;
185 // If it's not safe to move defs of the register class, then abort.
186 if (!TII->isSafeToMoveRegClassDefs(RegInfo->getRegClass(Reg)))
189 // FIXME: This picks a successor to sink into based on having one
190 // successor that dominates all the uses. However, there are cases where
191 // sinking can happen but where the sink point isn't a successor. For
196 // the instruction could be sunk over the whole diamond for the
197 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
200 // Virtual register defs can only be sunk if all their uses are in blocks
201 // dominated by one of the successors.
203 // If a previous operand picked a block to sink to, then this operand
204 // must be sinkable to the same block.
205 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo))
210 // Otherwise, we should look at all the successors and decide which one
211 // we should sink to.
212 for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
213 E = ParentBlock->succ_end(); SI != E; ++SI) {
214 if (AllUsesDominatedByBlock(Reg, *SI)) {
220 // If we couldn't find a block to sink to, ignore this instruction.
221 if (SuccToSinkTo == 0)
226 // If there are no outputs, it must have side-effects.
227 if (SuccToSinkTo == 0)
230 // It's not safe to sink instructions to EH landing pad. Control flow into
231 // landing pad is implicitly defined.
232 if (SuccToSinkTo->isLandingPad())
235 // If is not possible to sink an instruction into its own block. This can
236 // happen with loops.
237 if (MI->getParent() == SuccToSinkTo)
240 DEBUG(errs() << "Sink instr " << *MI);
241 DEBUG(errs() << "to block " << *SuccToSinkTo);
243 // If the block has multiple predecessors, this would introduce computation on
244 // a path that it doesn't already exist. We could split the critical edge,
245 // but for now we just punt.
246 // FIXME: Split critical edges if not backedges.
247 if (SuccToSinkTo->pred_size() > 1) {
248 DEBUG(errs() << " *** PUNTING: Critical edge found\n");
252 // Determine where to insert into. Skip phi nodes.
253 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
254 while (InsertPos != SuccToSinkTo->end() &&
255 InsertPos->getOpcode() == TargetInstrInfo::PHI)
258 // Move the instruction.
259 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
260 ++MachineBasicBlock::iterator(MI));