blob: 1ce546b578add839577f8caeb6f0e875b7cd1185 [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
Andrew Trick1df91b02012-02-08 21:22:43 +000035static cl::opt<bool>
Evan Cheng4dc301a2010-08-19 17:33:11 +000036SplitEdges("machine-sink-split",
37 cl::desc("Split critical edges during machine sinking"),
Evan Cheng44be1a82010-09-20 22:52:00 +000038 cl::init(true), cl::Hidden);
Evan Cheng4dc301a2010-08-19 17:33:11 +000039
Evan Cheng6edb0ea2010-09-17 22:28:18 +000040STATISTIC(NumSunk, "Number of machine instructions sunk");
41STATISTIC(NumSplit, "Number of critical edges split");
42STATISTIC(NumCoalesces, "Number of copies coalesced");
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000043
44namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000045 class MachineSinking : public MachineFunctionPass {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000046 const TargetInstrInfo *TII;
Dan Gohman19778e72009-09-25 22:53:29 +000047 const TargetRegisterInfo *TRI;
Evan Cheng6edb0ea2010-09-17 22:28:18 +000048 MachineRegisterInfo *MRI; // Machine register information
Dan Gohmana5225ad2009-08-05 01:19:01 +000049 MachineDominatorTree *DT; // Machine dominator tree
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +000050 MachineLoopInfo *LI;
Dan Gohmana70dca12009-10-09 23:27:56 +000051 AliasAnalysis *AA;
Dan Gohman45094e32009-09-26 02:34:00 +000052 BitVector AllocatableSet; // Which physregs are allocatable?
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000053
Evan Cheng6edb0ea2010-09-17 22:28:18 +000054 // Remember which edges have been considered for breaking.
55 SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8>
56 CEBCandidates;
57
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000058 public:
59 static char ID; // Pass identification
Owen Anderson081c34b2010-10-19 17:21:58 +000060 MachineSinking() : MachineFunctionPass(ID) {
61 initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
62 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +000063
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000064 virtual bool runOnMachineFunction(MachineFunction &MF);
Jim Grosbach6ee358b2010-06-03 23:49:57 +000065
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000066 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000067 AU.setPreservesCFG();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000068 MachineFunctionPass::getAnalysisUsage(AU);
Dan Gohmana70dca12009-10-09 23:27:56 +000069 AU.addRequired<AliasAnalysis>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000070 AU.addRequired<MachineDominatorTree>();
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +000071 AU.addRequired<MachineLoopInfo>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000072 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +000073 AU.addPreserved<MachineLoopInfo>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000074 }
Evan Cheng6edb0ea2010-09-17 22:28:18 +000075
76 virtual void releaseMemory() {
77 CEBCandidates.clear();
78 }
79
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000080 private:
81 bool ProcessBlock(MachineBasicBlock &MBB);
Evan Cheng6edb0ea2010-09-17 22:28:18 +000082 bool isWorthBreakingCriticalEdge(MachineInstr *MI,
83 MachineBasicBlock *From,
84 MachineBasicBlock *To);
85 MachineBasicBlock *SplitCriticalEdge(MachineInstr *MI,
86 MachineBasicBlock *From,
87 MachineBasicBlock *To,
Evan Cheng7af6dc42010-09-20 19:12:55 +000088 bool BreakPHIEdge);
Chris Lattneraad193a2008-01-12 00:17:41 +000089 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
Evan Chengc3439ad2010-08-18 23:09:25 +000090 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
Evan Cheng6edb0ea2010-09-17 22:28:18 +000091 MachineBasicBlock *DefMBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +000092 bool &BreakPHIEdge, bool &LocalUse) const;
Devang Patel52111342011-12-14 23:20:38 +000093 MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, MachineBasicBlock *MBB,
94 bool &BreakPHIEdge);
Andrew Trick1df91b02012-02-08 21:22:43 +000095 bool isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
Devang Patel52111342011-12-14 23:20:38 +000096 MachineBasicBlock *MBB,
97 MachineBasicBlock *SuccToSinkTo);
Devang Patele265bcf2011-12-08 21:48:01 +000098
Evan Cheng6edb0ea2010-09-17 22:28:18 +000099 bool PerformTrivialForwardCoalescing(MachineInstr *MI,
100 MachineBasicBlock *MBB);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000101 };
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000102} // end anonymous namespace
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000103
Dan Gohman844731a2008-05-13 00:00:25 +0000104char MachineSinking::ID = 0;
Andrew Trick1dd8c852012-02-08 21:23:13 +0000105char &llvm::MachineSinkingID = MachineSinking::ID;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000106INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
107 "Machine code sinking", false, false)
108INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
109INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
110INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
111INITIALIZE_PASS_END(MachineSinking, "machine-sink",
Owen Andersonce665bd2010-10-07 22:25:06 +0000112 "Machine code sinking", false, false)
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000113
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000114bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
115 MachineBasicBlock *MBB) {
116 if (!MI->isCopy())
117 return false;
118
119 unsigned SrcReg = MI->getOperand(1).getReg();
120 unsigned DstReg = MI->getOperand(0).getReg();
121 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
122 !TargetRegisterInfo::isVirtualRegister(DstReg) ||
123 !MRI->hasOneNonDBGUse(SrcReg))
124 return false;
125
126 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
127 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
128 if (SRC != DRC)
129 return false;
130
131 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
132 if (DefMI->isCopyLike())
133 return false;
134 DEBUG(dbgs() << "Coalescing: " << *DefMI);
135 DEBUG(dbgs() << "*** to: " << *MI);
136 MRI->replaceRegWith(DstReg, SrcReg);
137 MI->eraseFromParent();
138 ++NumCoalesces;
139 return true;
140}
141
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000142/// AllUsesDominatedByBlock - Return true if all uses of the specified register
Evan Chengc3439ad2010-08-18 23:09:25 +0000143/// occur in blocks dominated by the specified block. If any use is in the
144/// definition block, then return false since it is never legal to move def
145/// after uses.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000146bool
147MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
148 MachineBasicBlock *MBB,
149 MachineBasicBlock *DefMBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000150 bool &BreakPHIEdge,
151 bool &LocalUse) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000152 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
153 "Only makes sense for vregs");
Evan Cheng23997862010-09-18 06:42:17 +0000154
Devang Patelf5b9a742011-12-09 01:25:04 +0000155 // Ignore debug uses because debug info doesn't affect the code.
Evan Cheng23997862010-09-18 06:42:17 +0000156 if (MRI->use_nodbg_empty(Reg))
157 return true;
158
Evan Cheng7af6dc42010-09-20 19:12:55 +0000159 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
160 // into and they are all PHI nodes. In this case, machine-sink must break
161 // the critical edge first. e.g.
162 //
Evan Cheng23997862010-09-18 06:42:17 +0000163 // BB#1: derived from LLVM BB %bb4.preheader
164 // Predecessors according to CFG: BB#0
165 // ...
166 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
167 // ...
168 // JE_4 <BB#37>, %EFLAGS<imp-use>
169 // Successors according to CFG: BB#37 BB#2
170 //
171 // BB#2: derived from LLVM BB %bb.nph
172 // Predecessors according to CFG: BB#0 BB#1
173 // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
Evan Cheng7af6dc42010-09-20 19:12:55 +0000174 BreakPHIEdge = true;
Evan Cheng23997862010-09-18 06:42:17 +0000175 for (MachineRegisterInfo::use_nodbg_iterator
176 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
177 I != E; ++I) {
178 MachineInstr *UseInst = &*I;
179 MachineBasicBlock *UseBlock = UseInst->getParent();
180 if (!(UseBlock == MBB && UseInst->isPHI() &&
181 UseInst->getOperand(I.getOperandNo()+1).getMBB() == DefMBB)) {
Evan Cheng7af6dc42010-09-20 19:12:55 +0000182 BreakPHIEdge = false;
Evan Cheng23997862010-09-18 06:42:17 +0000183 break;
184 }
185 }
Evan Cheng7af6dc42010-09-20 19:12:55 +0000186 if (BreakPHIEdge)
Evan Cheng23997862010-09-18 06:42:17 +0000187 return true;
188
Bill Wendling05c68372010-06-02 23:04:26 +0000189 for (MachineRegisterInfo::use_nodbg_iterator
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000190 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
Bill Wendling05c68372010-06-02 23:04:26 +0000191 I != E; ++I) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000192 // Determine the block of the use.
193 MachineInstr *UseInst = &*I;
194 MachineBasicBlock *UseBlock = UseInst->getParent();
Evan Cheng23997862010-09-18 06:42:17 +0000195 if (UseInst->isPHI()) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000196 // PHI nodes use the operand in the predecessor block, not the block with
197 // the PHI.
198 UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
Evan Chenge5e79462010-08-19 18:33:29 +0000199 } else if (UseBlock == DefMBB) {
200 LocalUse = true;
201 return false;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000202 }
Bill Wendling05c68372010-06-02 23:04:26 +0000203
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000204 // Check that it dominates.
205 if (!DT->dominates(MBB, UseBlock))
206 return false;
207 }
Bill Wendling05c68372010-06-02 23:04:26 +0000208
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000209 return true;
210}
211
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000212bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
David Greenec19a9cd2010-01-05 01:26:00 +0000213 DEBUG(dbgs() << "******** Machine Sinking ********\n");
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000214
Dan Gohman4e9785e2009-10-19 14:52:05 +0000215 const TargetMachine &TM = MF.getTarget();
216 TII = TM.getInstrInfo();
217 TRI = TM.getRegisterInfo();
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000218 MRI = &MF.getRegInfo();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000219 DT = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000220 LI = &getAnalysis<MachineLoopInfo>();
Dan Gohmana70dca12009-10-09 23:27:56 +0000221 AA = &getAnalysis<AliasAnalysis>();
Dan Gohman4e9785e2009-10-19 14:52:05 +0000222 AllocatableSet = TRI->getAllocatableSet(MF);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000223
224 bool EverMadeChange = false;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000225
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000226 while (1) {
227 bool MadeChange = false;
228
229 // Process all basic blocks.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000230 CEBCandidates.clear();
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000231 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000232 I != E; ++I)
233 MadeChange |= ProcessBlock(*I);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000234
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000235 // If this iteration over the code changed anything, keep iterating.
236 if (!MadeChange) break;
237 EverMadeChange = true;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000238 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000239 return EverMadeChange;
240}
241
242bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000243 // Can't sink anything out of a block that has less than two successors.
Chris Lattner296185c2009-04-10 16:38:36 +0000244 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
245
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000246 // Don't bother sinking code out of unreachable blocks. In addition to being
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000247 // unprofitable, it can also lead to infinite looping, because in an
248 // unreachable loop there may be nowhere to stop.
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000249 if (!DT->isReachableFromEntry(&MBB)) return false;
250
Chris Lattner296185c2009-04-10 16:38:36 +0000251 bool MadeChange = false;
252
Chris Lattneraad193a2008-01-12 00:17:41 +0000253 // Walk the basic block bottom-up. Remember if we saw a store.
Chris Lattner296185c2009-04-10 16:38:36 +0000254 MachineBasicBlock::iterator I = MBB.end();
255 --I;
256 bool ProcessedBegin, SawStore = false;
257 do {
258 MachineInstr *MI = I; // The instruction to sink.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000259
Chris Lattner296185c2009-04-10 16:38:36 +0000260 // Predecrement I (if it's not begin) so that it isn't invalidated by
261 // sinking.
262 ProcessedBegin = I == MBB.begin();
263 if (!ProcessedBegin)
264 --I;
Dale Johannesenb0812f12010-03-05 00:02:59 +0000265
266 if (MI->isDebugValue())
267 continue;
268
Evan Chengcfea9852011-04-11 18:47:20 +0000269 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
270 if (Joined) {
271 MadeChange = true;
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000272 continue;
Evan Chengcfea9852011-04-11 18:47:20 +0000273 }
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000274
Chris Lattner296185c2009-04-10 16:38:36 +0000275 if (SinkInstruction(MI, SawStore))
276 ++NumSunk, MadeChange = true;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000277
Chris Lattner296185c2009-04-10 16:38:36 +0000278 // If we just processed the first instruction in the block, we're done.
279 } while (!ProcessedBegin);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000280
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000281 return MadeChange;
282}
283
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000284bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
285 MachineBasicBlock *From,
286 MachineBasicBlock *To) {
287 // FIXME: Need much better heuristics.
288
289 // If the pass has already considered breaking this edge (during this pass
290 // through the function), then let's go ahead and break it. This means
291 // sinking multiple "cheap" instructions into the same block.
292 if (!CEBCandidates.insert(std::make_pair(From, To)))
293 return true;
294
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000295 if (!MI->isCopy() && !MI->isAsCheapAsAMove())
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000296 return true;
297
298 // MI is cheap, we probably don't want to break the critical edge for it.
299 // However, if this would allow some definitions of its source operands
300 // to be sunk then it's probably worth it.
301 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
302 const MachineOperand &MO = MI->getOperand(i);
303 if (!MO.isReg()) continue;
304 unsigned Reg = MO.getReg();
305 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg))
306 continue;
307 if (MRI->hasOneNonDBGUse(Reg))
308 return true;
309 }
310
311 return false;
312}
313
314MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI,
315 MachineBasicBlock *FromBB,
316 MachineBasicBlock *ToBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000317 bool BreakPHIEdge) {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000318 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
319 return 0;
320
Evan Cheng4dc301a2010-08-19 17:33:11 +0000321 // Avoid breaking back edge. From == To means backedge for single BB loop.
Evan Cheng44be1a82010-09-20 22:52:00 +0000322 if (!SplitEdges || FromBB == ToBB)
Evan Cheng4dc301a2010-08-19 17:33:11 +0000323 return 0;
324
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000325 // Check for backedges of more "complex" loops.
326 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
327 LI->isLoopHeader(ToBB))
328 return 0;
329
330 // It's not always legal to break critical edges and sink the computation
331 // to the edge.
332 //
333 // BB#1:
334 // v1024
335 // Beq BB#3
336 // <fallthrough>
337 // BB#2:
338 // ... no uses of v1024
339 // <fallthrough>
340 // BB#3:
341 // ...
342 // = v1024
343 //
344 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
345 //
346 // BB#1:
347 // ...
348 // Bne BB#2
349 // BB#4:
350 // v1024 =
351 // B BB#3
352 // BB#2:
353 // ... no uses of v1024
354 // <fallthrough>
355 // BB#3:
356 // ...
357 // = v1024
358 //
359 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
360 // flow. We need to ensure the new basic block where the computation is
361 // sunk to dominates all the uses.
362 // It's only legal to break critical edge and sink the computation to the
363 // new block if all the predecessors of "To", except for "From", are
364 // not dominated by "From". Given SSA property, this means these
365 // predecessors are dominated by "To".
366 //
367 // There is no need to do this check if all the uses are PHI nodes. PHI
368 // sources are only defined on the specific predecessor edges.
Evan Cheng7af6dc42010-09-20 19:12:55 +0000369 if (!BreakPHIEdge) {
Evan Cheng4dc301a2010-08-19 17:33:11 +0000370 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
371 E = ToBB->pred_end(); PI != E; ++PI) {
372 if (*PI == FromBB)
373 continue;
374 if (!DT->dominates(ToBB, *PI))
375 return 0;
376 }
Evan Cheng4dc301a2010-08-19 17:33:11 +0000377 }
378
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000379 return FromBB->SplitCriticalEdge(ToBB, this);
Evan Cheng4dc301a2010-08-19 17:33:11 +0000380}
381
Evan Chengb0cdf8a2010-09-23 06:53:00 +0000382static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) {
383 return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence();
384}
385
Andrew Trick1df91b02012-02-08 21:22:43 +0000386/// collectDebgValues - Scan instructions following MI and collect any
Devang Patel541a81c2011-09-07 00:07:58 +0000387/// matching DBG_VALUEs.
Andrew Trick1df91b02012-02-08 21:22:43 +0000388static void collectDebugValues(MachineInstr *MI,
Devang Patel541a81c2011-09-07 00:07:58 +0000389 SmallVector<MachineInstr *, 2> & DbgValues) {
390 DbgValues.clear();
391 if (!MI->getOperand(0).isReg())
392 return;
393
394 MachineBasicBlock::iterator DI = MI; ++DI;
395 for (MachineBasicBlock::iterator DE = MI->getParent()->end();
396 DI != DE; ++DI) {
397 if (!DI->isDebugValue())
398 return;
399 if (DI->getOperand(0).isReg() &&
400 DI->getOperand(0).getReg() == MI->getOperand(0).getReg())
401 DbgValues.push_back(DI);
402 }
403}
404
Devang Patel52111342011-12-14 23:20:38 +0000405/// isPostDominatedBy - Return true if A is post dominated by B.
406static bool isPostDominatedBy(MachineBasicBlock *A, MachineBasicBlock *B) {
407
408 // FIXME - Use real post dominator.
409 if (A->succ_size() != 2)
410 return false;
411 MachineBasicBlock::succ_iterator I = A->succ_begin();
412 if (B == *I)
413 ++I;
414 MachineBasicBlock *OtherSuccBlock = *I;
415 if (OtherSuccBlock->succ_size() != 1 ||
416 *(OtherSuccBlock->succ_begin()) != B)
417 return false;
418
419 return true;
420}
421
422/// isProfitableToSinkTo - Return true if it is profitable to sink MI.
Andrew Trick1df91b02012-02-08 21:22:43 +0000423bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
Devang Patel52111342011-12-14 23:20:38 +0000424 MachineBasicBlock *MBB,
425 MachineBasicBlock *SuccToSinkTo) {
426 assert (MI && "Invalid MachineInstr!");
427 assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
428
429 if (MBB == SuccToSinkTo)
430 return false;
431
432 // It is profitable if SuccToSinkTo does not post dominate current block.
433 if (!isPostDominatedBy(MBB, SuccToSinkTo))
434 return true;
435
436 // Check if only use in post dominated block is PHI instruction.
437 bool NonPHIUse = false;
438 for (MachineRegisterInfo::use_nodbg_iterator
439 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
440 I != E; ++I) {
441 MachineInstr *UseInst = &*I;
442 MachineBasicBlock *UseBlock = UseInst->getParent();
443 if (UseBlock == SuccToSinkTo && !UseInst->isPHI())
444 NonPHIUse = true;
445 }
446 if (!NonPHIUse)
447 return true;
448
449 // If SuccToSinkTo post dominates then also it may be profitable if MI
450 // can further profitably sinked into another block in next round.
451 bool BreakPHIEdge = false;
452 // FIXME - If finding successor is compile time expensive then catch results.
453 if (MachineBasicBlock *MBB2 = FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge))
454 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2);
455
456 // If SuccToSinkTo is final destination and it is a post dominator of current
457 // block then it is not profitable to sink MI into SuccToSinkTo block.
458 return false;
459}
460
Devang Patele265bcf2011-12-08 21:48:01 +0000461/// FindSuccToSinkTo - Find a successor to sink this instruction to.
462MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI,
Devang Patel52111342011-12-14 23:20:38 +0000463 MachineBasicBlock *MBB,
464 bool &BreakPHIEdge) {
465
466 assert (MI && "Invalid MachineInstr!");
467 assert (MBB && "Invalid MachineBasicBlock!");
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000468
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000469 // Loop over all the operands of the specified instruction. If there is
470 // anything we can't handle, bail out.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000471
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000472 // SuccToSinkTo - This is the successor to sink this instruction to, once we
473 // decide.
474 MachineBasicBlock *SuccToSinkTo = 0;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000475 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
476 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000477 if (!MO.isReg()) continue; // Ignore non-register operands.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000478
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000479 unsigned Reg = MO.getReg();
480 if (Reg == 0) continue;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000481
Dan Gohman6f0d0242008-02-10 18:45:23 +0000482 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohman19778e72009-09-25 22:53:29 +0000483 if (MO.isUse()) {
484 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000485 // and we can freely move its uses. Alternatively, if it's allocatable,
486 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesenc035c942012-01-16 22:34:08 +0000487 if (!MRI->isConstantPhysReg(Reg, *MBB->getParent()))
Devang Patele265bcf2011-12-08 21:48:01 +0000488 return NULL;
Bill Wendling730c07e2010-06-25 20:48:10 +0000489 } else if (!MO.isDead()) {
490 // A def that isn't dead. We can't move it.
Devang Patele265bcf2011-12-08 21:48:01 +0000491 return NULL;
Dan Gohman19778e72009-09-25 22:53:29 +0000492 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000493 } else {
494 // Virtual register uses are always safe to sink.
495 if (MO.isUse()) continue;
Evan Chengb6f54172009-02-07 01:21:47 +0000496
497 // If it's not safe to move defs of the register class, then abort.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000498 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
Devang Patele265bcf2011-12-08 21:48:01 +0000499 return NULL;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000500
Chris Lattnere430e1c2008-01-05 06:47:58 +0000501 // FIXME: This picks a successor to sink into based on having one
502 // successor that dominates all the uses. However, there are cases where
503 // sinking can happen but where the sink point isn't a successor. For
504 // example:
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000505 //
Chris Lattnere430e1c2008-01-05 06:47:58 +0000506 // x = computation
507 // if () {} else {}
508 // use x
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000509 //
Bill Wendling05c68372010-06-02 23:04:26 +0000510 // the instruction could be sunk over the whole diamond for the
Chris Lattnere430e1c2008-01-05 06:47:58 +0000511 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
512 // after that.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000513
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000514 // Virtual register defs can only be sunk if all their uses are in blocks
515 // dominated by one of the successors.
516 if (SuccToSinkTo) {
517 // If a previous operand picked a block to sink to, then this operand
518 // must be sinkable to the same block.
Evan Chenge5e79462010-08-19 18:33:29 +0000519 bool LocalUse = false;
Devang Patel52111342011-12-14 23:20:38 +0000520 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000521 BreakPHIEdge, LocalUse))
Devang Patele265bcf2011-12-08 21:48:01 +0000522 return NULL;
Bill Wendling05c68372010-06-02 23:04:26 +0000523
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000524 continue;
525 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000526
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000527 // Otherwise, we should look at all the successors and decide which one
528 // we should sink to.
Devang Patel52111342011-12-14 23:20:38 +0000529 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
530 E = MBB->succ_end(); SI != E; ++SI) {
531 MachineBasicBlock *SuccBlock = *SI;
Evan Chenge5e79462010-08-19 18:33:29 +0000532 bool LocalUse = false;
Devang Patel52111342011-12-14 23:20:38 +0000533 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000534 BreakPHIEdge, LocalUse)) {
Devang Patelcf405ba2011-12-08 21:33:23 +0000535 SuccToSinkTo = SuccBlock;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000536 break;
537 }
Evan Chengc3439ad2010-08-18 23:09:25 +0000538 if (LocalUse)
539 // Def is used locally, it's never safe to move this def.
Devang Patele265bcf2011-12-08 21:48:01 +0000540 return NULL;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000541 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000542
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000543 // If we couldn't find a block to sink to, ignore this instruction.
544 if (SuccToSinkTo == 0)
Devang Patele265bcf2011-12-08 21:48:01 +0000545 return NULL;
Devang Patel52111342011-12-14 23:20:38 +0000546 else if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo))
547 return NULL;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000548 }
549 }
Devang Patel7f7f0902011-12-08 23:52:00 +0000550
551 // It is not possible to sink an instruction into its own block. This can
552 // happen with loops.
Devang Patel52111342011-12-14 23:20:38 +0000553 if (MBB == SuccToSinkTo)
Devang Patel7f7f0902011-12-08 23:52:00 +0000554 return NULL;
555
556 // It's not safe to sink instructions to EH landing pad. Control flow into
557 // landing pad is implicitly defined.
558 if (SuccToSinkTo && SuccToSinkTo->isLandingPad())
559 return NULL;
560
Devang Patele265bcf2011-12-08 21:48:01 +0000561 return SuccToSinkTo;
562}
563
564/// SinkInstruction - Determine whether it is safe to sink the specified machine
565/// instruction out of its current block into a successor.
566bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
567 // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to
568 // be close to the source to make it easier to coalesce.
569 if (AvoidsSinking(MI, MRI))
570 return false;
571
572 // Check if it's safe to move the instruction.
573 if (!MI->isSafeToMove(TII, AA, SawStore))
574 return false;
575
576 // FIXME: This should include support for sinking instructions within the
577 // block they are currently in to shorten the live ranges. We often get
578 // instructions sunk into the top of a large block, but it would be better to
579 // also sink them down before their first use in the block. This xform has to
580 // be careful not to *increase* register pressure though, e.g. sinking
581 // "x = y + z" down if it kills y and z would increase the live ranges of y
582 // and z and only shrink the live range of x.
583
584 bool BreakPHIEdge = false;
Devang Patel52111342011-12-14 23:20:38 +0000585 MachineBasicBlock *ParentBlock = MI->getParent();
586 MachineBasicBlock *SuccToSinkTo = FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000587
Chris Lattner9bb459b2008-01-05 01:39:17 +0000588 // If there are no outputs, it must have side-effects.
589 if (SuccToSinkTo == 0)
590 return false;
Evan Chengb5999792009-02-15 08:36:12 +0000591
Bill Wendling869d60d2010-06-03 07:54:20 +0000592
Daniel Dunbard24c9d52010-06-23 00:48:25 +0000593 // If the instruction to move defines a dead physical register which is live
594 // when leaving the basic block, don't move it because it could turn into a
595 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
Bill Wendling730c07e2010-06-25 20:48:10 +0000596 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
597 const MachineOperand &MO = MI->getOperand(I);
598 if (!MO.isReg()) continue;
599 unsigned Reg = MO.getReg();
600 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
601 if (SuccToSinkTo->isLiveIn(Reg))
Bill Wendling869d60d2010-06-03 07:54:20 +0000602 return false;
Bill Wendling730c07e2010-06-25 20:48:10 +0000603 }
Bill Wendling869d60d2010-06-03 07:54:20 +0000604
Bill Wendling05c68372010-06-02 23:04:26 +0000605 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
606
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000607 // If the block has multiple predecessors, this would introduce computation on
608 // a path that it doesn't already exist. We could split the critical edge,
609 // but for now we just punt.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000610 if (SuccToSinkTo->pred_size() > 1) {
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000611 // We cannot sink a load across a critical edge - there may be stores in
612 // other code paths.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000613 bool TryBreak = false;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000614 bool store = true;
615 if (!MI->isSafeToMove(TII, AA, store)) {
Evan Chengf942c132010-08-19 23:33:02 +0000616 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000617 TryBreak = true;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000618 }
619
620 // We don't want to sink across a critical edge if we don't dominate the
621 // successor. We could be introducing calculations to new code paths.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000622 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
Evan Chengf942c132010-08-19 23:33:02 +0000623 DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000624 TryBreak = true;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000625 }
626
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000627 // Don't sink instructions into a loop.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000628 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
Evan Chengf942c132010-08-19 23:33:02 +0000629 DEBUG(dbgs() << " *** NOTE: Loop header found\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000630 TryBreak = true;
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000631 }
632
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000633 // Otherwise we are OK with sinking along a critical edge.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000634 if (!TryBreak)
635 DEBUG(dbgs() << "Sinking along critical edge.\n");
636 else {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000637 MachineBasicBlock *NewSucc =
Evan Cheng7af6dc42010-09-20 19:12:55 +0000638 SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
Evan Cheng4dc301a2010-08-19 17:33:11 +0000639 if (!NewSucc) {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000640 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
641 "break critical edge\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000642 return false;
643 } else {
Evan Chengf942c132010-08-19 23:33:02 +0000644 DEBUG(dbgs() << " *** Splitting critical edge:"
Evan Cheng4dc301a2010-08-19 17:33:11 +0000645 " BB#" << ParentBlock->getNumber()
646 << " -- BB#" << NewSucc->getNumber()
647 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
Evan Cheng4dc301a2010-08-19 17:33:11 +0000648 SuccToSinkTo = NewSucc;
649 ++NumSplit;
Evan Cheng7af6dc42010-09-20 19:12:55 +0000650 BreakPHIEdge = false;
Evan Cheng4dc301a2010-08-19 17:33:11 +0000651 }
652 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000653 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000654
Evan Cheng7af6dc42010-09-20 19:12:55 +0000655 if (BreakPHIEdge) {
656 // BreakPHIEdge is true if all the uses are in the successor MBB being
657 // sunken into and they are all PHI nodes. In this case, machine-sink must
658 // break the critical edge first.
Evan Cheng23997862010-09-18 06:42:17 +0000659 MachineBasicBlock *NewSucc = SplitCriticalEdge(MI, ParentBlock,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000660 SuccToSinkTo, BreakPHIEdge);
Evan Cheng23997862010-09-18 06:42:17 +0000661 if (!NewSucc) {
662 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
663 "break critical edge\n");
664 return false;
665 }
666
667 DEBUG(dbgs() << " *** Splitting critical edge:"
668 " BB#" << ParentBlock->getNumber()
669 << " -- BB#" << NewSucc->getNumber()
670 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
671 SuccToSinkTo = NewSucc;
672 ++NumSplit;
673 }
674
Bill Wendling05c68372010-06-02 23:04:26 +0000675 // Determine where to insert into. Skip phi nodes.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000676 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
Evan Cheng23997862010-09-18 06:42:17 +0000677 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000678 ++InsertPos;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000679
Devang Patel541a81c2011-09-07 00:07:58 +0000680 // collect matching debug values.
681 SmallVector<MachineInstr *, 2> DbgValuesToSink;
682 collectDebugValues(MI, DbgValuesToSink);
683
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000684 // Move the instruction.
685 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
686 ++MachineBasicBlock::iterator(MI));
Dan Gohmane6cd7572010-05-13 20:34:42 +0000687
Devang Patel541a81c2011-09-07 00:07:58 +0000688 // Move debug values.
689 for (SmallVector<MachineInstr *, 2>::iterator DBI = DbgValuesToSink.begin(),
690 DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
691 MachineInstr *DbgMI = *DBI;
692 SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI,
693 ++MachineBasicBlock::iterator(DbgMI));
694 }
695
Bill Wendling05c68372010-06-02 23:04:26 +0000696 // Conservatively, clear any kill flags, since it's possible that they are no
697 // longer correct.
Dan Gohmane6cd7572010-05-13 20:34:42 +0000698 MI->clearKillInfo();
699
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000700 return true;
701}