blob: c4a533b09b4c05a08e45ca33b4d07f2720c2a0a5 [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"),
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 Patele265bcf2011-12-08 21:48:01 +000093 MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, bool &BreakPHIEdge);
94
Evan Cheng6edb0ea2010-09-17 22:28:18 +000095 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 Anderson2ab36d32010-10-12 19:48:12 +0000101INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
102 "Machine code sinking", false, false)
103INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
104INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
105INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
106INITIALIZE_PASS_END(MachineSinking, "machine-sink",
Owen Andersonce665bd2010-10-07 22:25:06 +0000107 "Machine code sinking", false, false)
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000108
109FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
110
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000111bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
112 MachineBasicBlock *MBB) {
113 if (!MI->isCopy())
114 return false;
115
116 unsigned SrcReg = MI->getOperand(1).getReg();
117 unsigned DstReg = MI->getOperand(0).getReg();
118 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
119 !TargetRegisterInfo::isVirtualRegister(DstReg) ||
120 !MRI->hasOneNonDBGUse(SrcReg))
121 return false;
122
123 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
124 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
125 if (SRC != DRC)
126 return false;
127
128 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
129 if (DefMI->isCopyLike())
130 return false;
131 DEBUG(dbgs() << "Coalescing: " << *DefMI);
132 DEBUG(dbgs() << "*** to: " << *MI);
133 MRI->replaceRegWith(DstReg, SrcReg);
134 MI->eraseFromParent();
135 ++NumCoalesces;
136 return true;
137}
138
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000139/// AllUsesDominatedByBlock - Return true if all uses of the specified register
Evan Chengc3439ad2010-08-18 23:09:25 +0000140/// occur in blocks dominated by the specified block. If any use is in the
141/// definition block, then return false since it is never legal to move def
142/// after uses.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000143bool
144MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
145 MachineBasicBlock *MBB,
146 MachineBasicBlock *DefMBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000147 bool &BreakPHIEdge,
148 bool &LocalUse) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000149 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
150 "Only makes sense for vregs");
Evan Cheng23997862010-09-18 06:42:17 +0000151
152 if (MRI->use_nodbg_empty(Reg))
153 return true;
154
Devang Patel2b1d7732011-12-09 01:18:48 +0000155 // Ignoring debug uses because debug info doesn't affect the code.
Evan Cheng23997862010-09-18 06:42:17 +0000156
Evan Cheng7af6dc42010-09-20 19:12:55 +0000157 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
158 // into and they are all PHI nodes. In this case, machine-sink must break
159 // the critical edge first. e.g.
160 //
Evan Cheng23997862010-09-18 06:42:17 +0000161 // BB#1: derived from LLVM BB %bb4.preheader
162 // Predecessors according to CFG: BB#0
163 // ...
164 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
165 // ...
166 // JE_4 <BB#37>, %EFLAGS<imp-use>
167 // Successors according to CFG: BB#37 BB#2
168 //
169 // BB#2: derived from LLVM BB %bb.nph
170 // Predecessors according to CFG: BB#0 BB#1
171 // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
Evan Cheng7af6dc42010-09-20 19:12:55 +0000172 BreakPHIEdge = true;
Evan Cheng23997862010-09-18 06:42:17 +0000173 for (MachineRegisterInfo::use_nodbg_iterator
174 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
175 I != E; ++I) {
176 MachineInstr *UseInst = &*I;
177 MachineBasicBlock *UseBlock = UseInst->getParent();
178 if (!(UseBlock == MBB && UseInst->isPHI() &&
179 UseInst->getOperand(I.getOperandNo()+1).getMBB() == DefMBB)) {
Evan Cheng7af6dc42010-09-20 19:12:55 +0000180 BreakPHIEdge = false;
Evan Cheng23997862010-09-18 06:42:17 +0000181 break;
182 }
183 }
Evan Cheng7af6dc42010-09-20 19:12:55 +0000184 if (BreakPHIEdge)
Evan Cheng23997862010-09-18 06:42:17 +0000185 return true;
186
Bill Wendling05c68372010-06-02 23:04:26 +0000187 for (MachineRegisterInfo::use_nodbg_iterator
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000188 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
Bill Wendling05c68372010-06-02 23:04:26 +0000189 I != E; ++I) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000190 // Determine the block of the use.
191 MachineInstr *UseInst = &*I;
192 MachineBasicBlock *UseBlock = UseInst->getParent();
Evan Cheng23997862010-09-18 06:42:17 +0000193 if (UseInst->isPHI()) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000194 // PHI nodes use the operand in the predecessor block, not the block with
195 // the PHI.
196 UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
Evan Chenge5e79462010-08-19 18:33:29 +0000197 } else if (UseBlock == DefMBB) {
198 LocalUse = true;
199 return false;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000200 }
Bill Wendling05c68372010-06-02 23:04:26 +0000201
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000202 // Check that it dominates.
203 if (!DT->dominates(MBB, UseBlock))
204 return false;
205 }
Bill Wendling05c68372010-06-02 23:04:26 +0000206
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000207 return true;
208}
209
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000210bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
David Greenec19a9cd2010-01-05 01:26:00 +0000211 DEBUG(dbgs() << "******** Machine Sinking ********\n");
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000212
Dan Gohman4e9785e2009-10-19 14:52:05 +0000213 const TargetMachine &TM = MF.getTarget();
214 TII = TM.getInstrInfo();
215 TRI = TM.getRegisterInfo();
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000216 MRI = &MF.getRegInfo();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000217 DT = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000218 LI = &getAnalysis<MachineLoopInfo>();
Dan Gohmana70dca12009-10-09 23:27:56 +0000219 AA = &getAnalysis<AliasAnalysis>();
Dan Gohman4e9785e2009-10-19 14:52:05 +0000220 AllocatableSet = TRI->getAllocatableSet(MF);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000221
222 bool EverMadeChange = false;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000223
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000224 while (1) {
225 bool MadeChange = false;
226
227 // Process all basic blocks.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000228 CEBCandidates.clear();
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000229 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000230 I != E; ++I)
231 MadeChange |= ProcessBlock(*I);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000232
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000233 // If this iteration over the code changed anything, keep iterating.
234 if (!MadeChange) break;
235 EverMadeChange = true;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000236 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000237 return EverMadeChange;
238}
239
240bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000241 // Can't sink anything out of a block that has less than two successors.
Chris Lattner296185c2009-04-10 16:38:36 +0000242 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
243
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000244 // Don't bother sinking code out of unreachable blocks. In addition to being
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000245 // unprofitable, it can also lead to infinite looping, because in an
246 // unreachable loop there may be nowhere to stop.
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000247 if (!DT->isReachableFromEntry(&MBB)) return false;
248
Chris Lattner296185c2009-04-10 16:38:36 +0000249 bool MadeChange = false;
250
Chris Lattneraad193a2008-01-12 00:17:41 +0000251 // Walk the basic block bottom-up. Remember if we saw a store.
Chris Lattner296185c2009-04-10 16:38:36 +0000252 MachineBasicBlock::iterator I = MBB.end();
253 --I;
254 bool ProcessedBegin, SawStore = false;
255 do {
256 MachineInstr *MI = I; // The instruction to sink.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000257
Chris Lattner296185c2009-04-10 16:38:36 +0000258 // Predecrement I (if it's not begin) so that it isn't invalidated by
259 // sinking.
260 ProcessedBegin = I == MBB.begin();
261 if (!ProcessedBegin)
262 --I;
Dale Johannesenb0812f12010-03-05 00:02:59 +0000263
264 if (MI->isDebugValue())
265 continue;
266
Evan Chengcfea9852011-04-11 18:47:20 +0000267 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
268 if (Joined) {
269 MadeChange = true;
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000270 continue;
Evan Chengcfea9852011-04-11 18:47:20 +0000271 }
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000272
Chris Lattner296185c2009-04-10 16:38:36 +0000273 if (SinkInstruction(MI, SawStore))
274 ++NumSunk, MadeChange = true;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000275
Chris Lattner296185c2009-04-10 16:38:36 +0000276 // If we just processed the first instruction in the block, we're done.
277 } while (!ProcessedBegin);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000278
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000279 return MadeChange;
280}
281
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000282bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
283 MachineBasicBlock *From,
284 MachineBasicBlock *To) {
285 // FIXME: Need much better heuristics.
286
287 // If the pass has already considered breaking this edge (during this pass
288 // through the function), then let's go ahead and break it. This means
289 // sinking multiple "cheap" instructions into the same block.
290 if (!CEBCandidates.insert(std::make_pair(From, To)))
291 return true;
292
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000293 if (!MI->isCopy() && !MI->isAsCheapAsAMove())
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000294 return true;
295
296 // MI is cheap, we probably don't want to break the critical edge for it.
297 // However, if this would allow some definitions of its source operands
298 // to be sunk then it's probably worth it.
299 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
300 const MachineOperand &MO = MI->getOperand(i);
301 if (!MO.isReg()) continue;
302 unsigned Reg = MO.getReg();
303 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg))
304 continue;
305 if (MRI->hasOneNonDBGUse(Reg))
306 return true;
307 }
308
309 return false;
310}
311
312MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI,
313 MachineBasicBlock *FromBB,
314 MachineBasicBlock *ToBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000315 bool BreakPHIEdge) {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000316 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
317 return 0;
318
Evan Cheng4dc301a2010-08-19 17:33:11 +0000319 // Avoid breaking back edge. From == To means backedge for single BB loop.
Evan Cheng44be1a82010-09-20 22:52:00 +0000320 if (!SplitEdges || FromBB == ToBB)
Evan Cheng4dc301a2010-08-19 17:33:11 +0000321 return 0;
322
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000323 // Check for backedges of more "complex" loops.
324 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
325 LI->isLoopHeader(ToBB))
326 return 0;
327
328 // It's not always legal to break critical edges and sink the computation
329 // to the edge.
330 //
331 // BB#1:
332 // v1024
333 // Beq BB#3
334 // <fallthrough>
335 // BB#2:
336 // ... no uses of v1024
337 // <fallthrough>
338 // BB#3:
339 // ...
340 // = v1024
341 //
342 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
343 //
344 // BB#1:
345 // ...
346 // Bne BB#2
347 // BB#4:
348 // v1024 =
349 // B BB#3
350 // BB#2:
351 // ... no uses of v1024
352 // <fallthrough>
353 // BB#3:
354 // ...
355 // = v1024
356 //
357 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
358 // flow. We need to ensure the new basic block where the computation is
359 // sunk to dominates all the uses.
360 // It's only legal to break critical edge and sink the computation to the
361 // new block if all the predecessors of "To", except for "From", are
362 // not dominated by "From". Given SSA property, this means these
363 // predecessors are dominated by "To".
364 //
365 // There is no need to do this check if all the uses are PHI nodes. PHI
366 // sources are only defined on the specific predecessor edges.
Evan Cheng7af6dc42010-09-20 19:12:55 +0000367 if (!BreakPHIEdge) {
Evan Cheng4dc301a2010-08-19 17:33:11 +0000368 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
369 E = ToBB->pred_end(); PI != E; ++PI) {
370 if (*PI == FromBB)
371 continue;
372 if (!DT->dominates(ToBB, *PI))
373 return 0;
374 }
Evan Cheng4dc301a2010-08-19 17:33:11 +0000375 }
376
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000377 return FromBB->SplitCriticalEdge(ToBB, this);
Evan Cheng4dc301a2010-08-19 17:33:11 +0000378}
379
Evan Chengb0cdf8a2010-09-23 06:53:00 +0000380static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) {
381 return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence();
382}
383
Devang Patel541a81c2011-09-07 00:07:58 +0000384/// collectDebgValues - Scan instructions following MI and collect any
385/// matching DBG_VALUEs.
386static void collectDebugValues(MachineInstr *MI,
387 SmallVector<MachineInstr *, 2> & DbgValues) {
388 DbgValues.clear();
389 if (!MI->getOperand(0).isReg())
390 return;
391
392 MachineBasicBlock::iterator DI = MI; ++DI;
393 for (MachineBasicBlock::iterator DE = MI->getParent()->end();
394 DI != DE; ++DI) {
395 if (!DI->isDebugValue())
396 return;
397 if (DI->getOperand(0).isReg() &&
398 DI->getOperand(0).getReg() == MI->getOperand(0).getReg())
399 DbgValues.push_back(DI);
400 }
401}
402
Devang Patele265bcf2011-12-08 21:48:01 +0000403/// FindSuccToSinkTo - Find a successor to sink this instruction to.
404MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI,
405 bool &BreakPHIEdge) {
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000406
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000407 // Loop over all the operands of the specified instruction. If there is
408 // anything we can't handle, bail out.
409 MachineBasicBlock *ParentBlock = MI->getParent();
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000410
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000411 // SuccToSinkTo - This is the successor to sink this instruction to, once we
412 // decide.
413 MachineBasicBlock *SuccToSinkTo = 0;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000414
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000415 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
416 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000417 if (!MO.isReg()) continue; // Ignore non-register operands.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000418
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000419 unsigned Reg = MO.getReg();
420 if (Reg == 0) continue;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000421
Dan Gohman6f0d0242008-02-10 18:45:23 +0000422 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohman19778e72009-09-25 22:53:29 +0000423 if (MO.isUse()) {
424 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000425 // and we can freely move its uses. Alternatively, if it's allocatable,
426 // it could get allocated to something with a def during allocation.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000427 if (!MRI->def_empty(Reg))
Devang Patele265bcf2011-12-08 21:48:01 +0000428 return NULL;
Bill Wendling05c68372010-06-02 23:04:26 +0000429
Dan Gohman45094e32009-09-26 02:34:00 +0000430 if (AllocatableSet.test(Reg))
Devang Patele265bcf2011-12-08 21:48:01 +0000431 return NULL;
Bill Wendling05c68372010-06-02 23:04:26 +0000432
Dan Gohman19778e72009-09-25 22:53:29 +0000433 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000434 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
435 unsigned AliasReg = *Alias;
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000436 if (!MRI->def_empty(AliasReg))
Devang Patele265bcf2011-12-08 21:48:01 +0000437 return NULL;
Bill Wendling05c68372010-06-02 23:04:26 +0000438
Dan Gohman45094e32009-09-26 02:34:00 +0000439 if (AllocatableSet.test(AliasReg))
Devang Patele265bcf2011-12-08 21:48:01 +0000440 return NULL;
Dan Gohman45094e32009-09-26 02:34:00 +0000441 }
Bill Wendling730c07e2010-06-25 20:48:10 +0000442 } else if (!MO.isDead()) {
443 // A def that isn't dead. We can't move it.
Devang Patele265bcf2011-12-08 21:48:01 +0000444 return NULL;
Dan Gohman19778e72009-09-25 22:53:29 +0000445 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000446 } else {
447 // Virtual register uses are always safe to sink.
448 if (MO.isUse()) continue;
Evan Chengb6f54172009-02-07 01:21:47 +0000449
450 // If it's not safe to move defs of the register class, then abort.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000451 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
Devang Patele265bcf2011-12-08 21:48:01 +0000452 return NULL;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000453
Chris Lattnere430e1c2008-01-05 06:47:58 +0000454 // FIXME: This picks a successor to sink into based on having one
455 // successor that dominates all the uses. However, there are cases where
456 // sinking can happen but where the sink point isn't a successor. For
457 // example:
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000458 //
Chris Lattnere430e1c2008-01-05 06:47:58 +0000459 // x = computation
460 // if () {} else {}
461 // use x
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000462 //
Bill Wendling05c68372010-06-02 23:04:26 +0000463 // the instruction could be sunk over the whole diamond for the
Chris Lattnere430e1c2008-01-05 06:47:58 +0000464 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
465 // after that.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000466
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000467 // Virtual register defs can only be sunk if all their uses are in blocks
468 // dominated by one of the successors.
469 if (SuccToSinkTo) {
470 // If a previous operand picked a block to sink to, then this operand
471 // must be sinkable to the same block.
Evan Chenge5e79462010-08-19 18:33:29 +0000472 bool LocalUse = false;
Evan Cheng23997862010-09-18 06:42:17 +0000473 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, ParentBlock,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000474 BreakPHIEdge, LocalUse))
Devang Patele265bcf2011-12-08 21:48:01 +0000475 return NULL;
Bill Wendling05c68372010-06-02 23:04:26 +0000476
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000477 continue;
478 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000479
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000480 // Otherwise, we should look at all the successors and decide which one
481 // we should sink to.
482 for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
483 E = ParentBlock->succ_end(); SI != E; ++SI) {
Devang Patelcf405ba2011-12-08 21:33:23 +0000484 MachineBasicBlock *SuccBlock = *SI;
Evan Chenge5e79462010-08-19 18:33:29 +0000485 bool LocalUse = false;
Devang Patelcf405ba2011-12-08 21:33:23 +0000486 if (AllUsesDominatedByBlock(Reg, SuccBlock, ParentBlock,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000487 BreakPHIEdge, LocalUse)) {
Devang Patelcf405ba2011-12-08 21:33:23 +0000488 SuccToSinkTo = SuccBlock;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000489 break;
490 }
Evan Chengc3439ad2010-08-18 23:09:25 +0000491 if (LocalUse)
492 // Def is used locally, it's never safe to move this def.
Devang Patele265bcf2011-12-08 21:48:01 +0000493 return NULL;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000494 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000495
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000496 // If we couldn't find a block to sink to, ignore this instruction.
497 if (SuccToSinkTo == 0)
Devang Patele265bcf2011-12-08 21:48:01 +0000498 return NULL;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000499 }
500 }
Devang Patel7f7f0902011-12-08 23:52:00 +0000501
502 // It is not possible to sink an instruction into its own block. This can
503 // happen with loops.
504 if (ParentBlock == SuccToSinkTo)
505 return NULL;
506
507 // It's not safe to sink instructions to EH landing pad. Control flow into
508 // landing pad is implicitly defined.
509 if (SuccToSinkTo && SuccToSinkTo->isLandingPad())
510 return NULL;
511
Devang Patele265bcf2011-12-08 21:48:01 +0000512 return SuccToSinkTo;
513}
514
515/// SinkInstruction - Determine whether it is safe to sink the specified machine
516/// instruction out of its current block into a successor.
517bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
518 // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to
519 // be close to the source to make it easier to coalesce.
520 if (AvoidsSinking(MI, MRI))
521 return false;
522
523 // Check if it's safe to move the instruction.
524 if (!MI->isSafeToMove(TII, AA, SawStore))
525 return false;
526
527 // FIXME: This should include support for sinking instructions within the
528 // block they are currently in to shorten the live ranges. We often get
529 // instructions sunk into the top of a large block, but it would be better to
530 // also sink them down before their first use in the block. This xform has to
531 // be careful not to *increase* register pressure though, e.g. sinking
532 // "x = y + z" down if it kills y and z would increase the live ranges of y
533 // and z and only shrink the live range of x.
534
535 bool BreakPHIEdge = false;
536 MachineBasicBlock *SuccToSinkTo = FindSuccToSinkTo(MI, BreakPHIEdge);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000537
Chris Lattner9bb459b2008-01-05 01:39:17 +0000538 // If there are no outputs, it must have side-effects.
539 if (SuccToSinkTo == 0)
540 return false;
Evan Chengb5999792009-02-15 08:36:12 +0000541
Bill Wendling869d60d2010-06-03 07:54:20 +0000542
Daniel Dunbard24c9d52010-06-23 00:48:25 +0000543 // If the instruction to move defines a dead physical register which is live
544 // when leaving the basic block, don't move it because it could turn into a
545 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
Bill Wendling730c07e2010-06-25 20:48:10 +0000546 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
547 const MachineOperand &MO = MI->getOperand(I);
548 if (!MO.isReg()) continue;
549 unsigned Reg = MO.getReg();
550 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
551 if (SuccToSinkTo->isLiveIn(Reg))
Bill Wendling869d60d2010-06-03 07:54:20 +0000552 return false;
Bill Wendling730c07e2010-06-25 20:48:10 +0000553 }
Bill Wendling869d60d2010-06-03 07:54:20 +0000554
Bill Wendling05c68372010-06-02 23:04:26 +0000555 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
556
Devang Patele265bcf2011-12-08 21:48:01 +0000557 MachineBasicBlock *ParentBlock = MI->getParent();
558
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000559 // If the block has multiple predecessors, this would introduce computation on
560 // a path that it doesn't already exist. We could split the critical edge,
561 // but for now we just punt.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000562 if (SuccToSinkTo->pred_size() > 1) {
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000563 // We cannot sink a load across a critical edge - there may be stores in
564 // other code paths.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000565 bool TryBreak = false;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000566 bool store = true;
567 if (!MI->isSafeToMove(TII, AA, store)) {
Evan Chengf942c132010-08-19 23:33:02 +0000568 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000569 TryBreak = true;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000570 }
571
572 // We don't want to sink across a critical edge if we don't dominate the
573 // successor. We could be introducing calculations to new code paths.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000574 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
Evan Chengf942c132010-08-19 23:33:02 +0000575 DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000576 TryBreak = true;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000577 }
578
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000579 // Don't sink instructions into a loop.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000580 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
Evan Chengf942c132010-08-19 23:33:02 +0000581 DEBUG(dbgs() << " *** NOTE: Loop header found\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000582 TryBreak = true;
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000583 }
584
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000585 // Otherwise we are OK with sinking along a critical edge.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000586 if (!TryBreak)
587 DEBUG(dbgs() << "Sinking along critical edge.\n");
588 else {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000589 MachineBasicBlock *NewSucc =
Evan Cheng7af6dc42010-09-20 19:12:55 +0000590 SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
Evan Cheng4dc301a2010-08-19 17:33:11 +0000591 if (!NewSucc) {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000592 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
593 "break critical edge\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000594 return false;
595 } else {
Evan Chengf942c132010-08-19 23:33:02 +0000596 DEBUG(dbgs() << " *** Splitting critical edge:"
Evan Cheng4dc301a2010-08-19 17:33:11 +0000597 " BB#" << ParentBlock->getNumber()
598 << " -- BB#" << NewSucc->getNumber()
599 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
Evan Cheng4dc301a2010-08-19 17:33:11 +0000600 SuccToSinkTo = NewSucc;
601 ++NumSplit;
Evan Cheng7af6dc42010-09-20 19:12:55 +0000602 BreakPHIEdge = false;
Evan Cheng4dc301a2010-08-19 17:33:11 +0000603 }
604 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000605 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000606
Evan Cheng7af6dc42010-09-20 19:12:55 +0000607 if (BreakPHIEdge) {
608 // BreakPHIEdge is true if all the uses are in the successor MBB being
609 // sunken into and they are all PHI nodes. In this case, machine-sink must
610 // break the critical edge first.
Evan Cheng23997862010-09-18 06:42:17 +0000611 MachineBasicBlock *NewSucc = SplitCriticalEdge(MI, ParentBlock,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000612 SuccToSinkTo, BreakPHIEdge);
Evan Cheng23997862010-09-18 06:42:17 +0000613 if (!NewSucc) {
614 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
615 "break critical edge\n");
616 return false;
617 }
618
619 DEBUG(dbgs() << " *** Splitting critical edge:"
620 " BB#" << ParentBlock->getNumber()
621 << " -- BB#" << NewSucc->getNumber()
622 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
623 SuccToSinkTo = NewSucc;
624 ++NumSplit;
625 }
626
Bill Wendling05c68372010-06-02 23:04:26 +0000627 // Determine where to insert into. Skip phi nodes.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000628 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
Evan Cheng23997862010-09-18 06:42:17 +0000629 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000630 ++InsertPos;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000631
Devang Patel541a81c2011-09-07 00:07:58 +0000632 // collect matching debug values.
633 SmallVector<MachineInstr *, 2> DbgValuesToSink;
634 collectDebugValues(MI, DbgValuesToSink);
635
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000636 // Move the instruction.
637 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
638 ++MachineBasicBlock::iterator(MI));
Dan Gohmane6cd7572010-05-13 20:34:42 +0000639
Devang Patel541a81c2011-09-07 00:07:58 +0000640 // Move debug values.
641 for (SmallVector<MachineInstr *, 2>::iterator DBI = DbgValuesToSink.begin(),
642 DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
643 MachineInstr *DbgMI = *DBI;
644 SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI,
645 ++MachineBasicBlock::iterator(DbgMI));
646 }
647
Bill Wendling05c68372010-06-02 23:04:26 +0000648 // Conservatively, clear any kill flags, since it's possible that they are no
649 // longer correct.
Dan Gohmane6cd7572010-05-13 20:34:42 +0000650 MI->clearKillInfo();
651
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000652 return true;
653}