blob: 330e675a2e6377bdb2daf7eda3080dc736dea9b7 [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//
Bill Wendling05c68372010-06-02 23:04:26 +000010// This pass moves instructions into successor blocks when possible, so that
Dan Gohmana5225ad2009-08-05 01:19:01 +000011// 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"
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +000023#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohmana70dca12009-10-09 23:27:56 +000024#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000025#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000026#include "llvm/Target/TargetInstrInfo.h"
27#include "llvm/Target/TargetMachine.h"
Evan Cheng6edb0ea2010-09-17 22:28:18 +000028#include "llvm/ADT/SmallSet.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000029#include "llvm/ADT/Statistic.h"
Evan Cheng4dc301a2010-08-19 17:33:11 +000030#include "llvm/Support/CommandLine.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000031#include "llvm/Support/Debug.h"
Bill Wendling1e973aa2009-08-22 20:26:23 +000032#include "llvm/Support/raw_ostream.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000033using namespace llvm;
34
Evan Cheng4dc301a2010-08-19 17:33:11 +000035static cl::opt<bool>
36SplitEdges("machine-sink-split",
37 cl::desc("Split critical edges during machine sinking"),
38 cl::init(false), cl::Hidden);
39static cl::opt<unsigned>
40SplitLimit("split-limit",
41 cl::init(~0u), cl::Hidden);
42
Evan Cheng6edb0ea2010-09-17 22:28:18 +000043STATISTIC(NumSunk, "Number of machine instructions sunk");
44STATISTIC(NumSplit, "Number of critical edges split");
45STATISTIC(NumCoalesces, "Number of copies coalesced");
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000046
47namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000048 class MachineSinking : public MachineFunctionPass {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000049 const TargetInstrInfo *TII;
Dan Gohman19778e72009-09-25 22:53:29 +000050 const TargetRegisterInfo *TRI;
Evan Cheng6edb0ea2010-09-17 22:28:18 +000051 MachineRegisterInfo *MRI; // Machine register information
Dan Gohmana5225ad2009-08-05 01:19:01 +000052 MachineDominatorTree *DT; // Machine dominator tree
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +000053 MachineLoopInfo *LI;
Dan Gohmana70dca12009-10-09 23:27:56 +000054 AliasAnalysis *AA;
Dan Gohman45094e32009-09-26 02:34:00 +000055 BitVector AllocatableSet; // Which physregs are allocatable?
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000056
Evan Cheng6edb0ea2010-09-17 22:28:18 +000057 // Remember which edges have been considered for breaking.
58 SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8>
59 CEBCandidates;
60
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000061 public:
62 static char ID; // Pass identification
Owen Anderson90c579d2010-08-06 18:33:48 +000063 MachineSinking() : MachineFunctionPass(ID) {}
Jim Grosbach6ee358b2010-06-03 23:49:57 +000064
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000065 virtual bool runOnMachineFunction(MachineFunction &MF);
Jim Grosbach6ee358b2010-06-03 23:49:57 +000066
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000067 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000068 AU.setPreservesCFG();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000069 MachineFunctionPass::getAnalysisUsage(AU);
Dan Gohmana70dca12009-10-09 23:27:56 +000070 AU.addRequired<AliasAnalysis>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000071 AU.addRequired<MachineDominatorTree>();
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +000072 AU.addRequired<MachineLoopInfo>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000073 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +000074 AU.addPreserved<MachineLoopInfo>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000075 }
Evan Cheng6edb0ea2010-09-17 22:28:18 +000076
77 virtual void releaseMemory() {
78 CEBCandidates.clear();
79 }
80
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000081 private:
82 bool ProcessBlock(MachineBasicBlock &MBB);
Evan Cheng6edb0ea2010-09-17 22:28:18 +000083 bool isWorthBreakingCriticalEdge(MachineInstr *MI,
84 MachineBasicBlock *From,
85 MachineBasicBlock *To);
86 MachineBasicBlock *SplitCriticalEdge(MachineInstr *MI,
87 MachineBasicBlock *From,
88 MachineBasicBlock *To,
89 bool HasNonePHIUse);
Chris Lattneraad193a2008-01-12 00:17:41 +000090 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
Evan Chengc3439ad2010-08-18 23:09:25 +000091 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
Evan Cheng6edb0ea2010-09-17 22:28:18 +000092 MachineBasicBlock *DefMBB,
93 SmallPtrSet<MachineInstr*, 4> &PHIUses,
94 bool &NonPHIUse, bool &LocalUse) const;
95 bool PerformTrivialForwardCoalescing(MachineInstr *MI,
96 MachineBasicBlock *MBB);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000097 };
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000098} // end anonymous namespace
Jim Grosbach6ee358b2010-06-03 23:49:57 +000099
Dan Gohman844731a2008-05-13 00:00:25 +0000100char MachineSinking::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000101INITIALIZE_PASS(MachineSinking, "machine-sink",
102 "Machine code sinking", false, false);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000103
104FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
105
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000106bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
107 MachineBasicBlock *MBB) {
108 if (!MI->isCopy())
109 return false;
110
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))
116 return false;
117
118 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
119 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
120 if (SRC != DRC)
121 return false;
122
123 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
124 if (DefMI->isCopyLike())
125 return false;
126 DEBUG(dbgs() << "Coalescing: " << *DefMI);
127 DEBUG(dbgs() << "*** to: " << *MI);
128 MRI->replaceRegWith(DstReg, SrcReg);
129 MI->eraseFromParent();
130 ++NumCoalesces;
131 return true;
132}
133
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000134/// AllUsesDominatedByBlock - Return true if all uses of the specified register
Evan Chengc3439ad2010-08-18 23:09:25 +0000135/// 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
137/// after uses.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000138bool
139MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
140 MachineBasicBlock *MBB,
141 MachineBasicBlock *DefMBB,
142 SmallPtrSet<MachineInstr*, 4> &PHIUses,
143 bool &NonPHIUse, bool &LocalUse) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000144 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
145 "Only makes sense for vregs");
Dale Johannesenb0812f12010-03-05 00:02:59 +0000146 // 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.
Bill Wendling05c68372010-06-02 23:04:26 +0000150 for (MachineRegisterInfo::use_nodbg_iterator
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000151 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
Bill Wendling05c68372010-06-02 23:04:26 +0000152 I != E; ++I) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000153 // Determine the block of the use.
154 MachineInstr *UseInst = &*I;
155 MachineBasicBlock *UseBlock = UseInst->getParent();
Bill Wendling05c68372010-06-02 23:04:26 +0000156
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000157 bool isPHI = UseInst->isPHI();
158 if (isPHI)
159 PHIUses.insert(UseInst);
160
161 if (isPHI) {
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
166 // ...
167 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
168 // ...
169 // JE_4 <BB#37>, %EFLAGS<imp-use>
170 // Successors according to CFG: BB#37 BB#2
171 //
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>
175 //
176 // Machine sink should break the critical edge first.
177 continue;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000178 // PHI nodes use the operand in the predecessor block, not the block with
179 // the PHI.
180 UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
Evan Chenge5e79462010-08-19 18:33:29 +0000181 } else if (UseBlock == DefMBB) {
182 LocalUse = true;
183 return false;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000184 }
Bill Wendling05c68372010-06-02 23:04:26 +0000185
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000186 // Check that it dominates.
187 if (!DT->dominates(MBB, UseBlock))
188 return false;
189 }
Bill Wendling05c68372010-06-02 23:04:26 +0000190
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000191 return true;
192}
193
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000194bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
David Greenec19a9cd2010-01-05 01:26:00 +0000195 DEBUG(dbgs() << "******** Machine Sinking ********\n");
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000196
Dan Gohman4e9785e2009-10-19 14:52:05 +0000197 const TargetMachine &TM = MF.getTarget();
198 TII = TM.getInstrInfo();
199 TRI = TM.getRegisterInfo();
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000200 MRI = &MF.getRegInfo();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000201 DT = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000202 LI = &getAnalysis<MachineLoopInfo>();
Dan Gohmana70dca12009-10-09 23:27:56 +0000203 AA = &getAnalysis<AliasAnalysis>();
Dan Gohman4e9785e2009-10-19 14:52:05 +0000204 AllocatableSet = TRI->getAllocatableSet(MF);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000205
206 bool EverMadeChange = false;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000207
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000208 while (1) {
209 bool MadeChange = false;
210
211 // Process all basic blocks.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000212 CEBCandidates.clear();
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000213 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000214 I != E; ++I)
215 MadeChange |= ProcessBlock(*I);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000216
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000217 // If this iteration over the code changed anything, keep iterating.
218 if (!MadeChange) break;
219 EverMadeChange = true;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000220 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000221 return EverMadeChange;
222}
223
224bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000225 // Can't sink anything out of a block that has less than two successors.
Chris Lattner296185c2009-04-10 16:38:36 +0000226 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
227
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000228 // Don't bother sinking code out of unreachable blocks. In addition to being
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000229 // unprofitable, it can also lead to infinite looping, because in an
230 // unreachable loop there may be nowhere to stop.
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000231 if (!DT->isReachableFromEntry(&MBB)) return false;
232
Chris Lattner296185c2009-04-10 16:38:36 +0000233 bool MadeChange = false;
234
Chris Lattneraad193a2008-01-12 00:17:41 +0000235 // Walk the basic block bottom-up. Remember if we saw a store.
Chris Lattner296185c2009-04-10 16:38:36 +0000236 MachineBasicBlock::iterator I = MBB.end();
237 --I;
238 bool ProcessedBegin, SawStore = false;
239 do {
240 MachineInstr *MI = I; // The instruction to sink.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000241
Chris Lattner296185c2009-04-10 16:38:36 +0000242 // Predecrement I (if it's not begin) so that it isn't invalidated by
243 // sinking.
244 ProcessedBegin = I == MBB.begin();
245 if (!ProcessedBegin)
246 --I;
Dale Johannesenb0812f12010-03-05 00:02:59 +0000247
248 if (MI->isDebugValue())
249 continue;
250
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000251 if (PerformTrivialForwardCoalescing(MI, &MBB))
252 continue;
253
Chris Lattner296185c2009-04-10 16:38:36 +0000254 if (SinkInstruction(MI, SawStore))
255 ++NumSunk, MadeChange = true;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000256
Chris Lattner296185c2009-04-10 16:38:36 +0000257 // If we just processed the first instruction in the block, we're done.
258 } while (!ProcessedBegin);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000259
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000260 return MadeChange;
261}
262
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000263bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
264 MachineBasicBlock *From,
265 MachineBasicBlock *To) {
266 // FIXME: Need much better heuristics.
267
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)))
272 return true;
273
274 if (!(MI->isCopyLike() || MI->getDesc().isAsCheapAsAMove()))
275 return true;
276
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))
285 continue;
286 if (MRI->hasOneNonDBGUse(Reg))
287 return true;
288 }
289
290 return false;
291}
292
293MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI,
294 MachineBasicBlock *FromBB,
295 MachineBasicBlock *ToBB,
296 bool HasNonePHIUse) {
297 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
298 return 0;
299
Evan Cheng4dc301a2010-08-19 17:33:11 +0000300 // Avoid breaking back edge. From == To means backedge for single BB loop.
301 if (!SplitEdges || NumSplit == SplitLimit || FromBB == ToBB)
302 return 0;
303
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000304 // Check for backedges of more "complex" loops.
305 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
306 LI->isLoopHeader(ToBB))
307 return 0;
308
309 // It's not always legal to break critical edges and sink the computation
310 // to the edge.
311 //
312 // BB#1:
313 // v1024
314 // Beq BB#3
315 // <fallthrough>
316 // BB#2:
317 // ... no uses of v1024
318 // <fallthrough>
319 // BB#3:
320 // ...
321 // = v1024
322 //
323 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
324 //
325 // BB#1:
326 // ...
327 // Bne BB#2
328 // BB#4:
329 // v1024 =
330 // B BB#3
331 // BB#2:
332 // ... no uses of v1024
333 // <fallthrough>
334 // BB#3:
335 // ...
336 // = v1024
337 //
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".
345 //
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.
348 if (HasNonePHIUse) {
Evan Cheng4dc301a2010-08-19 17:33:11 +0000349 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
350 E = ToBB->pred_end(); PI != E; ++PI) {
351 if (*PI == FromBB)
352 continue;
353 if (!DT->dominates(ToBB, *PI))
354 return 0;
355 }
Evan Cheng4dc301a2010-08-19 17:33:11 +0000356 }
357
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000358 return FromBB->SplitCriticalEdge(ToBB, this);
Evan Cheng4dc301a2010-08-19 17:33:11 +0000359}
360
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000361/// SinkInstruction - Determine whether it is safe to sink the specified machine
362/// instruction out of its current block into a successor.
Chris Lattneraad193a2008-01-12 00:17:41 +0000363bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
Evan Chengb27087f2008-03-13 00:44:09 +0000364 // Check if it's safe to move the instruction.
Evan Chengac1abde2010-03-02 19:03:01 +0000365 if (!MI->isSafeToMove(TII, AA, SawStore))
Chris Lattneraad193a2008-01-12 00:17:41 +0000366 return false;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000367
Chris Lattnere430e1c2008-01-05 06:47:58 +0000368 // 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
Dan Gohmana5225ad2009-08-05 01:19:01 +0000374 // and z and only shrink the live range of x.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000375
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000376 // 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();
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000379
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000380 // SuccToSinkTo - This is the successor to sink this instruction to, once we
381 // decide.
382 MachineBasicBlock *SuccToSinkTo = 0;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000383
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000384 SmallSet<unsigned, 4> Defs;
385 SmallPtrSet<MachineInstr*, 4> PHIUses;
386 bool HasNonPHIUse = false;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000387 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
388 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000389 if (!MO.isReg()) continue; // Ignore non-register operands.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000390
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000391 unsigned Reg = MO.getReg();
392 if (Reg == 0) continue;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000393
Dan Gohman6f0d0242008-02-10 18:45:23 +0000394 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohman19778e72009-09-25 22:53:29 +0000395 if (MO.isUse()) {
396 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000397 // and we can freely move its uses. Alternatively, if it's allocatable,
398 // it could get allocated to something with a def during allocation.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000399 if (!MRI->def_empty(Reg))
Dan Gohman19778e72009-09-25 22:53:29 +0000400 return false;
Bill Wendling05c68372010-06-02 23:04:26 +0000401
Dan Gohman45094e32009-09-26 02:34:00 +0000402 if (AllocatableSet.test(Reg))
403 return false;
Bill Wendling05c68372010-06-02 23:04:26 +0000404
Dan Gohman19778e72009-09-25 22:53:29 +0000405 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000406 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
407 unsigned AliasReg = *Alias;
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000408 if (!MRI->def_empty(AliasReg))
Dan Gohman19778e72009-09-25 22:53:29 +0000409 return false;
Bill Wendling05c68372010-06-02 23:04:26 +0000410
Dan Gohman45094e32009-09-26 02:34:00 +0000411 if (AllocatableSet.test(AliasReg))
412 return false;
413 }
Bill Wendling730c07e2010-06-25 20:48:10 +0000414 } else if (!MO.isDead()) {
415 // A def that isn't dead. We can't move it.
416 return false;
Dan Gohman19778e72009-09-25 22:53:29 +0000417 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000418 } else {
419 // Virtual register uses are always safe to sink.
420 if (MO.isUse()) continue;
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000421 Defs.insert(Reg);
Evan Chengb6f54172009-02-07 01:21:47 +0000422
423 // If it's not safe to move defs of the register class, then abort.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000424 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
Evan Chengb6f54172009-02-07 01:21:47 +0000425 return false;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000426
Chris Lattnere430e1c2008-01-05 06:47:58 +0000427 // 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
430 // example:
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000431 //
Chris Lattnere430e1c2008-01-05 06:47:58 +0000432 // x = computation
433 // if () {} else {}
434 // use x
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000435 //
Bill Wendling05c68372010-06-02 23:04:26 +0000436 // the instruction could be sunk over the whole diamond for the
Chris Lattnere430e1c2008-01-05 06:47:58 +0000437 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
438 // after that.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000439
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000440 // Virtual register defs can only be sunk if all their uses are in blocks
441 // dominated by one of the successors.
442 if (SuccToSinkTo) {
443 // If a previous operand picked a block to sink to, then this operand
444 // must be sinkable to the same block.
Evan Chenge5e79462010-08-19 18:33:29 +0000445 bool LocalUse = false;
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000446 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, ParentBlock, PHIUses,
447 HasNonPHIUse, LocalUse))
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000448 return false;
Bill Wendling05c68372010-06-02 23:04:26 +0000449
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000450 continue;
451 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000452
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000453 // 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) {
Evan Chenge5e79462010-08-19 18:33:29 +0000457 bool LocalUse = false;
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000458 if (AllUsesDominatedByBlock(Reg, *SI, ParentBlock, PHIUses,
459 HasNonPHIUse, LocalUse)) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000460 SuccToSinkTo = *SI;
461 break;
462 }
Evan Chengc3439ad2010-08-18 23:09:25 +0000463 if (LocalUse)
464 // Def is used locally, it's never safe to move this def.
465 return false;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000466 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000467
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000468 // If we couldn't find a block to sink to, ignore this instruction.
469 if (SuccToSinkTo == 0)
470 return false;
471 }
472 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000473
Chris Lattner9bb459b2008-01-05 01:39:17 +0000474 // If there are no outputs, it must have side-effects.
475 if (SuccToSinkTo == 0)
476 return false;
Evan Chengb5999792009-02-15 08:36:12 +0000477
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())
481 return false;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000482
Dan Gohmandfffba62009-10-19 14:56:05 +0000483 // It is not possible to sink an instruction into its own block. This can
Chris Lattner296185c2009-04-10 16:38:36 +0000484 // happen with loops.
485 if (MI->getParent() == SuccToSinkTo)
486 return false;
Bill Wendling869d60d2010-06-03 07:54:20 +0000487
Daniel Dunbard24c9d52010-06-23 00:48:25 +0000488 // 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>)
Bill Wendling730c07e2010-06-25 20:48:10 +0000491 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))
Bill Wendling869d60d2010-06-03 07:54:20 +0000497 return false;
Bill Wendling730c07e2010-06-25 20:48:10 +0000498 }
Bill Wendling869d60d2010-06-03 07:54:20 +0000499
Bill Wendling05c68372010-06-02 23:04:26 +0000500 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
501
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000502 // 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.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000505 if (SuccToSinkTo->pred_size() > 1) {
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000506 // We cannot sink a load across a critical edge - there may be stores in
507 // other code paths.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000508 bool TryBreak = false;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000509 bool store = true;
510 if (!MI->isSafeToMove(TII, AA, store)) {
Evan Chengf942c132010-08-19 23:33:02 +0000511 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000512 TryBreak = true;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000513 }
514
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.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000517 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
Evan Chengf942c132010-08-19 23:33:02 +0000518 DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000519 TryBreak = true;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000520 }
521
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000522 // Don't sink instructions into a loop.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000523 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
Evan Chengf942c132010-08-19 23:33:02 +0000524 DEBUG(dbgs() << " *** NOTE: Loop header found\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000525 TryBreak = true;
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000526 }
527
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000528 // Otherwise we are OK with sinking along a critical edge.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000529 if (!TryBreak)
530 DEBUG(dbgs() << "Sinking along critical edge.\n");
531 else {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000532 MachineBasicBlock *NewSucc =
533 SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, HasNonPHIUse);
Evan Cheng4dc301a2010-08-19 17:33:11 +0000534 if (!NewSucc) {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000535 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
536 "break critical edge\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000537 return false;
538 } else {
Evan Chengf942c132010-08-19 23:33:02 +0000539 DEBUG(dbgs() << " *** Splitting critical edge:"
Evan Cheng4dc301a2010-08-19 17:33:11 +0000540 " BB#" << ParentBlock->getNumber()
541 << " -- BB#" << NewSucc->getNumber()
542 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
Evan Cheng4dc301a2010-08-19 17:33:11 +0000543 SuccToSinkTo = NewSucc;
544 ++NumSplit;
545 }
546 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000547 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000548
Bill Wendling05c68372010-06-02 23:04:26 +0000549 // Determine where to insert into. Skip phi nodes.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000550 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000551 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI()) {
552 MachineInstr *PHI = &*InsertPos;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000553 ++InsertPos;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000554
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000555 if (SplitEdges && PHIUses.count(PHI)) {
556 if (NumSplit == SplitLimit)
557 return false;
558
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);
567 if (!NewSucc) {
568 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
569 "break critical edge\n");
570 return false;
571 }
572
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();
579 ++NumSplit;
580 break;
581 }
582 }
583 }
584 }
585
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000586 // Move the instruction.
587 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
588 ++MachineBasicBlock::iterator(MI));
Dan Gohmane6cd7572010-05-13 20:34:42 +0000589
Bill Wendling05c68372010-06-02 23:04:26 +0000590 // Conservatively, clear any kill flags, since it's possible that they are no
591 // longer correct.
Dan Gohmane6cd7572010-05-13 20:34:42 +0000592 MI->clearKillInfo();
593
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000594 return true;
595}