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 const TargetRegisterInfo *TRI;
39 MachineFunction *CurMF; // Current MachineFunction
40 MachineRegisterInfo *RegInfo; // Machine register information
41 MachineDominatorTree *DT; // Machine dominator tree
42 BitVector AllocatableSet; // Which physregs are allocatable?
45 static char ID; // Pass identification
46 MachineSinking() : MachineFunctionPass(&ID) {}
48 virtual bool runOnMachineFunction(MachineFunction &MF);
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
52 MachineFunctionPass::getAnalysisUsage(AU);
53 AU.addRequired<MachineDominatorTree>();
54 AU.addPreserved<MachineDominatorTree>();
57 bool ProcessBlock(MachineBasicBlock &MBB);
58 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
59 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB) const;
61 } // end anonymous namespace
63 char MachineSinking::ID = 0;
64 static RegisterPass<MachineSinking>
65 X("machine-sink", "Machine code sinking");
67 FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
69 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
70 /// occur in blocks dominated by the specified block.
71 bool MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
72 MachineBasicBlock *MBB) const {
73 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
74 "Only makes sense for vregs");
75 for (MachineRegisterInfo::use_iterator I = RegInfo->use_begin(Reg),
76 E = RegInfo->use_end(); I != E; ++I) {
77 // Determine the block of the use.
78 MachineInstr *UseInst = &*I;
79 MachineBasicBlock *UseBlock = UseInst->getParent();
80 if (UseInst->getOpcode() == TargetInstrInfo::PHI) {
81 // PHI nodes use the operand in the predecessor block, not the block with
83 UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
85 // Check that it dominates.
86 if (!DT->dominates(MBB, UseBlock))
94 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
95 DEBUG(errs() << "******** Machine Sinking ********\n");
98 TM = &CurMF->getTarget();
99 TII = TM->getInstrInfo();
100 TRI = TM->getRegisterInfo();
101 RegInfo = &CurMF->getRegInfo();
102 DT = &getAnalysis<MachineDominatorTree>();
103 AllocatableSet = TRI->getAllocatableSet(*CurMF);
105 bool EverMadeChange = false;
108 bool MadeChange = false;
110 // Process all basic blocks.
111 for (MachineFunction::iterator I = CurMF->begin(), E = CurMF->end();
113 MadeChange |= ProcessBlock(*I);
115 // If this iteration over the code changed anything, keep iterating.
116 if (!MadeChange) break;
117 EverMadeChange = true;
119 return EverMadeChange;
122 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
123 // Can't sink anything out of a block that has less than two successors.
124 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
126 bool MadeChange = false;
128 // Walk the basic block bottom-up. Remember if we saw a store.
129 MachineBasicBlock::iterator I = MBB.end();
131 bool ProcessedBegin, SawStore = false;
133 MachineInstr *MI = I; // The instruction to sink.
135 // Predecrement I (if it's not begin) so that it isn't invalidated by
137 ProcessedBegin = I == MBB.begin();
141 if (SinkInstruction(MI, SawStore))
142 ++NumSunk, MadeChange = true;
144 // If we just processed the first instruction in the block, we're done.
145 } while (!ProcessedBegin);
150 /// SinkInstruction - Determine whether it is safe to sink the specified machine
151 /// instruction out of its current block into a successor.
152 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
153 // Check if it's safe to move the instruction.
154 if (!MI->isSafeToMove(TII, SawStore))
157 // FIXME: This should include support for sinking instructions within the
158 // block they are currently in to shorten the live ranges. We often get
159 // instructions sunk into the top of a large block, but it would be better to
160 // also sink them down before their first use in the block. This xform has to
161 // be careful not to *increase* register pressure though, e.g. sinking
162 // "x = y + z" down if it kills y and z would increase the live ranges of y
163 // and z and only shrink the live range of x.
165 // Loop over all the operands of the specified instruction. If there is
166 // anything we can't handle, bail out.
167 MachineBasicBlock *ParentBlock = MI->getParent();
169 // SuccToSinkTo - This is the successor to sink this instruction to, once we
171 MachineBasicBlock *SuccToSinkTo = 0;
173 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
174 const MachineOperand &MO = MI->getOperand(i);
175 if (!MO.isReg()) continue; // Ignore non-register operands.
177 unsigned Reg = MO.getReg();
178 if (Reg == 0) continue;
180 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
181 // If this is a physical register use, we can't move it. If it is a def,
182 // we can move it, but only if the def is dead.
184 // If the physreg has no defs anywhere, it's just an ambient register
185 // and we can freely move its uses. Alternatively, if it's allocatable,
186 // it could get allocated to something with a def during allocation.
187 if (!RegInfo->def_empty(Reg))
189 if (AllocatableSet.test(Reg))
191 // Check for a def among the register's aliases too.
192 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
193 unsigned AliasReg = *Alias;
194 if (!RegInfo->def_empty(AliasReg))
196 if (AllocatableSet.test(AliasReg))
199 } else if (!MO.isDead()) {
200 // A def that isn't dead. We can't move it.
204 // Virtual register uses are always safe to sink.
205 if (MO.isUse()) continue;
207 // If it's not safe to move defs of the register class, then abort.
208 if (!TII->isSafeToMoveRegClassDefs(RegInfo->getRegClass(Reg)))
211 // FIXME: This picks a successor to sink into based on having one
212 // successor that dominates all the uses. However, there are cases where
213 // sinking can happen but where the sink point isn't a successor. For
218 // the instruction could be sunk over the whole diamond for the
219 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
222 // Virtual register defs can only be sunk if all their uses are in blocks
223 // dominated by one of the successors.
225 // If a previous operand picked a block to sink to, then this operand
226 // must be sinkable to the same block.
227 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo))
232 // Otherwise, we should look at all the successors and decide which one
233 // we should sink to.
234 for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
235 E = ParentBlock->succ_end(); SI != E; ++SI) {
236 if (AllUsesDominatedByBlock(Reg, *SI)) {
242 // If we couldn't find a block to sink to, ignore this instruction.
243 if (SuccToSinkTo == 0)
248 // If there are no outputs, it must have side-effects.
249 if (SuccToSinkTo == 0)
252 // It's not safe to sink instructions to EH landing pad. Control flow into
253 // landing pad is implicitly defined.
254 if (SuccToSinkTo->isLandingPad())
257 // If is not possible to sink an instruction into its own block. This can
258 // happen with loops.
259 if (MI->getParent() == SuccToSinkTo)
262 DEBUG(errs() << "Sink instr " << *MI);
263 DEBUG(errs() << "to block " << *SuccToSinkTo);
265 // If the block has multiple predecessors, this would introduce computation on
266 // a path that it doesn't already exist. We could split the critical edge,
267 // but for now we just punt.
268 // FIXME: Split critical edges if not backedges.
269 if (SuccToSinkTo->pred_size() > 1) {
270 DEBUG(errs() << " *** PUNTING: Critical edge found\n");
274 // Determine where to insert into. Skip phi nodes.
275 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
276 while (InsertPos != SuccToSinkTo->end() &&
277 InsertPos->getOpcode() == TargetInstrInfo::PHI)
280 // Move the instruction.
281 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
282 ++MachineBasicBlock::iterator(MI));