blob: 5cf17298ca482d1dace415f350c8e793c7c14078 [file] [log] [blame]
Chris Lattnerc4ce73f2008-01-04 07:36:53 +00001//===-- MachineSink.cpp - Sinking for machine instructions ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Dan Gohmana5225ad2009-08-05 01:19:01 +000010// This pass moves instructions into successor blocks, when possible, so that
11// they aren't executed on paths where their results aren't needed.
12//
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.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000016//
17//===----------------------------------------------------------------------===//
18
19#define DEBUG_TYPE "machine-sink"
20#include "llvm/CodeGen/Passes.h"
21#include "llvm/CodeGen/MachineRegisterInfo.h"
22#include "llvm/CodeGen/MachineDominators.h"
Dan Gohmana70dca12009-10-09 23:27:56 +000023#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000024#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000025#include "llvm/Target/TargetInstrInfo.h"
26#include "llvm/Target/TargetMachine.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000027#include "llvm/ADT/Statistic.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000028#include "llvm/Support/Debug.h"
Bill Wendling1e973aa2009-08-22 20:26:23 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000030using namespace llvm;
31
32STATISTIC(NumSunk, "Number of machine instructions sunk");
33
34namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000035 class MachineSinking : public MachineFunctionPass {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000036 const TargetInstrInfo *TII;
Dan Gohman19778e72009-09-25 22:53:29 +000037 const TargetRegisterInfo *TRI;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000038 MachineRegisterInfo *RegInfo; // Machine register information
Dan Gohmana5225ad2009-08-05 01:19:01 +000039 MachineDominatorTree *DT; // Machine dominator tree
Dan Gohmana70dca12009-10-09 23:27:56 +000040 AliasAnalysis *AA;
Dan Gohman45094e32009-09-26 02:34:00 +000041 BitVector AllocatableSet; // Which physregs are allocatable?
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000042
43 public:
44 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +000045 MachineSinking() : MachineFunctionPass(&ID) {}
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000046
47 virtual bool runOnMachineFunction(MachineFunction &MF);
48
49 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000050 AU.setPreservesCFG();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000051 MachineFunctionPass::getAnalysisUsage(AU);
Dan Gohmana70dca12009-10-09 23:27:56 +000052 AU.addRequired<AliasAnalysis>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000053 AU.addRequired<MachineDominatorTree>();
54 AU.addPreserved<MachineDominatorTree>();
55 }
56 private:
57 bool ProcessBlock(MachineBasicBlock &MBB);
Chris Lattneraad193a2008-01-12 00:17:41 +000058 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000059 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB) const;
60 };
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000061} // end anonymous namespace
Dan Gohman844731a2008-05-13 00:00:25 +000062
63char MachineSinking::ID = 0;
64static RegisterPass<MachineSinking>
65X("machine-sink", "Machine code sinking");
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000066
67FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
68
69/// AllUsesDominatedByBlock - Return true if all uses of the specified register
70/// occur in blocks dominated by the specified block.
71bool MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
72 MachineBasicBlock *MBB) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +000073 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
74 "Only makes sense for vregs");
Dale Johannesenb0812f12010-03-05 00:02:59 +000075 // Ignoring debug uses is necessary so debug info doesn't affect the code.
76 // This may leave a referencing dbg_value in the original block, before
77 // the definition of the vreg. Dwarf generator handles this although the
78 // user might not get the right info at runtime.
79 for (MachineRegisterInfo::use_nodbg_iterator I =
80 RegInfo->use_nodbg_begin(Reg),
81 E = RegInfo->use_nodbg_end(); I != E; ++I) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000082 // Determine the block of the use.
83 MachineInstr *UseInst = &*I;
84 MachineBasicBlock *UseBlock = UseInst->getParent();
Chris Lattner518bb532010-02-09 19:54:29 +000085 if (UseInst->isPHI()) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000086 // PHI nodes use the operand in the predecessor block, not the block with
87 // the PHI.
88 UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
89 }
90 // Check that it dominates.
91 if (!DT->dominates(MBB, UseBlock))
92 return false;
93 }
94 return true;
95}
96
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000097bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
David Greenec19a9cd2010-01-05 01:26:00 +000098 DEBUG(dbgs() << "******** Machine Sinking ********\n");
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000099
Dan Gohman4e9785e2009-10-19 14:52:05 +0000100 const TargetMachine &TM = MF.getTarget();
101 TII = TM.getInstrInfo();
102 TRI = TM.getRegisterInfo();
103 RegInfo = &MF.getRegInfo();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000104 DT = &getAnalysis<MachineDominatorTree>();
Dan Gohmana70dca12009-10-09 23:27:56 +0000105 AA = &getAnalysis<AliasAnalysis>();
Dan Gohman4e9785e2009-10-19 14:52:05 +0000106 AllocatableSet = TRI->getAllocatableSet(MF);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000107
108 bool EverMadeChange = false;
109
110 while (1) {
111 bool MadeChange = false;
112
113 // Process all basic blocks.
Dan Gohman4e9785e2009-10-19 14:52:05 +0000114 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000115 I != E; ++I)
116 MadeChange |= ProcessBlock(*I);
117
118 // If this iteration over the code changed anything, keep iterating.
119 if (!MadeChange) break;
120 EverMadeChange = true;
121 }
122 return EverMadeChange;
123}
124
125bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000126 // Can't sink anything out of a block that has less than two successors.
Chris Lattner296185c2009-04-10 16:38:36 +0000127 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
128
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000129 // Don't bother sinking code out of unreachable blocks. In addition to being
130 // unprofitable, it can also lead to infinite looping, because in an unreachable
131 // loop there may be nowhere to stop.
132 if (!DT->isReachableFromEntry(&MBB)) return false;
133
Chris Lattner296185c2009-04-10 16:38:36 +0000134 bool MadeChange = false;
135
Chris Lattneraad193a2008-01-12 00:17:41 +0000136 // Walk the basic block bottom-up. Remember if we saw a store.
Chris Lattner296185c2009-04-10 16:38:36 +0000137 MachineBasicBlock::iterator I = MBB.end();
138 --I;
139 bool ProcessedBegin, SawStore = false;
140 do {
141 MachineInstr *MI = I; // The instruction to sink.
142
143 // Predecrement I (if it's not begin) so that it isn't invalidated by
144 // sinking.
145 ProcessedBegin = I == MBB.begin();
146 if (!ProcessedBegin)
147 --I;
Dale Johannesenb0812f12010-03-05 00:02:59 +0000148
149 if (MI->isDebugValue())
150 continue;
151
Chris Lattner296185c2009-04-10 16:38:36 +0000152 if (SinkInstruction(MI, SawStore))
153 ++NumSunk, MadeChange = true;
154
155 // If we just processed the first instruction in the block, we're done.
156 } while (!ProcessedBegin);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000157
158 return MadeChange;
159}
160
161/// SinkInstruction - Determine whether it is safe to sink the specified machine
162/// instruction out of its current block into a successor.
Chris Lattneraad193a2008-01-12 00:17:41 +0000163bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
Evan Chengb27087f2008-03-13 00:44:09 +0000164 // Check if it's safe to move the instruction.
Evan Chengac1abde2010-03-02 19:03:01 +0000165 if (!MI->isSafeToMove(TII, AA, SawStore))
Chris Lattneraad193a2008-01-12 00:17:41 +0000166 return false;
Chris Lattnere430e1c2008-01-05 06:47:58 +0000167
168 // FIXME: This should include support for sinking instructions within the
169 // block they are currently in to shorten the live ranges. We often get
170 // instructions sunk into the top of a large block, but it would be better to
171 // also sink them down before their first use in the block. This xform has to
172 // be careful not to *increase* register pressure though, e.g. sinking
173 // "x = y + z" down if it kills y and z would increase the live ranges of y
Dan Gohmana5225ad2009-08-05 01:19:01 +0000174 // and z and only shrink the live range of x.
Chris Lattnere430e1c2008-01-05 06:47:58 +0000175
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000176 // Loop over all the operands of the specified instruction. If there is
177 // anything we can't handle, bail out.
178 MachineBasicBlock *ParentBlock = MI->getParent();
179
180 // SuccToSinkTo - This is the successor to sink this instruction to, once we
181 // decide.
182 MachineBasicBlock *SuccToSinkTo = 0;
183
184 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
185 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000186 if (!MO.isReg()) continue; // Ignore non-register operands.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000187
188 unsigned Reg = MO.getReg();
189 if (Reg == 0) continue;
190
Dan Gohman6f0d0242008-02-10 18:45:23 +0000191 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohman19778e72009-09-25 22:53:29 +0000192 if (MO.isUse()) {
193 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000194 // and we can freely move its uses. Alternatively, if it's allocatable,
195 // it could get allocated to something with a def during allocation.
Dan Gohman19778e72009-09-25 22:53:29 +0000196 if (!RegInfo->def_empty(Reg))
197 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000198 if (AllocatableSet.test(Reg))
199 return false;
Dan Gohman19778e72009-09-25 22:53:29 +0000200 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000201 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
202 unsigned AliasReg = *Alias;
203 if (!RegInfo->def_empty(AliasReg))
Dan Gohman19778e72009-09-25 22:53:29 +0000204 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000205 if (AllocatableSet.test(AliasReg))
206 return false;
207 }
Dan Gohman19778e72009-09-25 22:53:29 +0000208 } else if (!MO.isDead()) {
209 // A def that isn't dead. We can't move it.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000210 return false;
Dan Gohman19778e72009-09-25 22:53:29 +0000211 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000212 } else {
213 // Virtual register uses are always safe to sink.
214 if (MO.isUse()) continue;
Evan Chengb6f54172009-02-07 01:21:47 +0000215
216 // If it's not safe to move defs of the register class, then abort.
217 if (!TII->isSafeToMoveRegClassDefs(RegInfo->getRegClass(Reg)))
218 return false;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000219
Chris Lattnere430e1c2008-01-05 06:47:58 +0000220 // FIXME: This picks a successor to sink into based on having one
221 // successor that dominates all the uses. However, there are cases where
222 // sinking can happen but where the sink point isn't a successor. For
223 // example:
224 // x = computation
225 // if () {} else {}
226 // use x
227 // the instruction could be sunk over the whole diamond for the
228 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
229 // after that.
230
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000231 // Virtual register defs can only be sunk if all their uses are in blocks
232 // dominated by one of the successors.
233 if (SuccToSinkTo) {
234 // If a previous operand picked a block to sink to, then this operand
235 // must be sinkable to the same block.
236 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo))
237 return false;
238 continue;
239 }
240
241 // Otherwise, we should look at all the successors and decide which one
242 // we should sink to.
243 for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
244 E = ParentBlock->succ_end(); SI != E; ++SI) {
245 if (AllUsesDominatedByBlock(Reg, *SI)) {
246 SuccToSinkTo = *SI;
247 break;
248 }
249 }
250
251 // If we couldn't find a block to sink to, ignore this instruction.
252 if (SuccToSinkTo == 0)
253 return false;
254 }
255 }
256
Chris Lattner9bb459b2008-01-05 01:39:17 +0000257 // If there are no outputs, it must have side-effects.
258 if (SuccToSinkTo == 0)
259 return false;
Evan Chengb5999792009-02-15 08:36:12 +0000260
261 // It's not safe to sink instructions to EH landing pad. Control flow into
262 // landing pad is implicitly defined.
263 if (SuccToSinkTo->isLandingPad())
264 return false;
Chris Lattner9bb459b2008-01-05 01:39:17 +0000265
Dan Gohmandfffba62009-10-19 14:56:05 +0000266 // It is not possible to sink an instruction into its own block. This can
Chris Lattner296185c2009-04-10 16:38:36 +0000267 // happen with loops.
268 if (MI->getParent() == SuccToSinkTo)
269 return false;
270
David Greenec19a9cd2010-01-05 01:26:00 +0000271 DEBUG(dbgs() << "Sink instr " << *MI);
272 DEBUG(dbgs() << "to block " << *SuccToSinkTo);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000273
274 // If the block has multiple predecessors, this would introduce computation on
275 // a path that it doesn't already exist. We could split the critical edge,
276 // but for now we just punt.
Chris Lattnere430e1c2008-01-05 06:47:58 +0000277 // FIXME: Split critical edges if not backedges.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000278 if (SuccToSinkTo->pred_size() > 1) {
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000279 // We cannot sink a load across a critical edge - there may be stores in
280 // other code paths.
281 bool store = true;
282 if (!MI->isSafeToMove(TII, AA, store)) {
283 DEBUG(dbgs() << " *** PUNTING: Wont sink load along critical edge.\n");
284 return false;
285 }
286
287 // We don't want to sink across a critical edge if we don't dominate the
288 // successor. We could be introducing calculations to new code paths.
289 if (!DT->dominates(ParentBlock, SuccToSinkTo)) {
290 DEBUG(dbgs() << " *** PUNTING: Critical edge found\n");
291 return false;
292 }
293
294 // Otherwise we are OK with sinking along a critical edge.
295 DEBUG(dbgs() << "Sinking along critical edge.\n");
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000296 }
297
298 // Determine where to insert into. Skip phi nodes.
299 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
Chris Lattner518bb532010-02-09 19:54:29 +0000300 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000301 ++InsertPos;
302
303 // Move the instruction.
304 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
305 ++MachineBasicBlock::iterator(MI));
306 return true;
307}