blob: dbff1f6440ac266e7268d9916df6fcc26eee2afe [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"
Evan Cheng6edb0ea2010-09-17 22:28:18 +000021#include "llvm/ADT/SmallSet.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000022#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/CodeGen/MachineDominators.h"
25#include "llvm/CodeGen/MachineLoopInfo.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
Evan Cheng4dc301a2010-08-19 17:33:11 +000027#include "llvm/Support/CommandLine.h"
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000028#include "llvm/Support/Debug.h"
Bill Wendling1e973aa2009-08-22 20:26:23 +000029#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000030#include "llvm/Target/TargetInstrInfo.h"
31#include "llvm/Target/TargetMachine.h"
32#include "llvm/Target/TargetRegisterInfo.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;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000052
Evan Cheng6edb0ea2010-09-17 22:28:18 +000053 // Remember which edges have been considered for breaking.
54 SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8>
55 CEBCandidates;
56
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000057 public:
58 static char ID; // Pass identification
Owen Anderson081c34b2010-10-19 17:21:58 +000059 MachineSinking() : MachineFunctionPass(ID) {
60 initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
61 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +000062
Stephen Hines36b56882014-04-23 16:57:46 -070063 bool runOnMachineFunction(MachineFunction &MF) override;
Jim Grosbach6ee358b2010-06-03 23:49:57 +000064
Stephen Hines36b56882014-04-23 16:57:46 -070065 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman845012e2009-07-31 23:37:33 +000066 AU.setPreservesCFG();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000067 MachineFunctionPass::getAnalysisUsage(AU);
Dan Gohmana70dca12009-10-09 23:27:56 +000068 AU.addRequired<AliasAnalysis>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000069 AU.addRequired<MachineDominatorTree>();
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +000070 AU.addRequired<MachineLoopInfo>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000071 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +000072 AU.addPreserved<MachineLoopInfo>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000073 }
Evan Cheng6edb0ea2010-09-17 22:28:18 +000074
Stephen Hines36b56882014-04-23 16:57:46 -070075 void releaseMemory() override {
Evan Cheng6edb0ea2010-09-17 22:28:18 +000076 CEBCandidates.clear();
77 }
78
Chris Lattnerc4ce73f2008-01-04 07:36:53 +000079 private:
80 bool ProcessBlock(MachineBasicBlock &MBB);
Evan Cheng6edb0ea2010-09-17 22:28:18 +000081 bool isWorthBreakingCriticalEdge(MachineInstr *MI,
82 MachineBasicBlock *From,
83 MachineBasicBlock *To);
84 MachineBasicBlock *SplitCriticalEdge(MachineInstr *MI,
85 MachineBasicBlock *From,
86 MachineBasicBlock *To,
Evan Cheng7af6dc42010-09-20 19:12:55 +000087 bool BreakPHIEdge);
Chris Lattneraad193a2008-01-12 00:17:41 +000088 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
Evan Chengc3439ad2010-08-18 23:09:25 +000089 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
Evan Cheng6edb0ea2010-09-17 22:28:18 +000090 MachineBasicBlock *DefMBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +000091 bool &BreakPHIEdge, bool &LocalUse) const;
Devang Patel52111342011-12-14 23:20:38 +000092 MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, MachineBasicBlock *MBB,
93 bool &BreakPHIEdge);
Andrew Trick1df91b02012-02-08 21:22:43 +000094 bool isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
Devang Patel52111342011-12-14 23:20:38 +000095 MachineBasicBlock *MBB,
96 MachineBasicBlock *SuccToSinkTo);
Devang Patele265bcf2011-12-08 21:48:01 +000097
Evan Cheng6edb0ea2010-09-17 22:28:18 +000098 bool PerformTrivialForwardCoalescing(MachineInstr *MI,
99 MachineBasicBlock *MBB);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000100 };
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000101} // end anonymous namespace
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000102
Dan Gohman844731a2008-05-13 00:00:25 +0000103char MachineSinking::ID = 0;
Andrew Trick1dd8c852012-02-08 21:23:13 +0000104char &llvm::MachineSinkingID = MachineSinking::ID;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000105INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
106 "Machine code sinking", false, false)
107INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
108INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
109INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
110INITIALIZE_PASS_END(MachineSinking, "machine-sink",
Owen Andersonce665bd2010-10-07 22:25:06 +0000111 "Machine code sinking", false, false)
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000112
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000113bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
114 MachineBasicBlock *MBB) {
115 if (!MI->isCopy())
116 return false;
117
118 unsigned SrcReg = MI->getOperand(1).getReg();
119 unsigned DstReg = MI->getOperand(0).getReg();
120 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
121 !TargetRegisterInfo::isVirtualRegister(DstReg) ||
122 !MRI->hasOneNonDBGUse(SrcReg))
123 return false;
124
125 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
126 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
127 if (SRC != DRC)
128 return false;
129
130 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
131 if (DefMI->isCopyLike())
132 return false;
133 DEBUG(dbgs() << "Coalescing: " << *DefMI);
134 DEBUG(dbgs() << "*** to: " << *MI);
135 MRI->replaceRegWith(DstReg, SrcReg);
136 MI->eraseFromParent();
137 ++NumCoalesces;
138 return true;
139}
140
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000141/// AllUsesDominatedByBlock - Return true if all uses of the specified register
Evan Chengc3439ad2010-08-18 23:09:25 +0000142/// occur in blocks dominated by the specified block. If any use is in the
143/// definition block, then return false since it is never legal to move def
144/// after uses.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000145bool
146MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
147 MachineBasicBlock *MBB,
148 MachineBasicBlock *DefMBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000149 bool &BreakPHIEdge,
150 bool &LocalUse) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000151 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
152 "Only makes sense for vregs");
Evan Cheng23997862010-09-18 06:42:17 +0000153
Devang Patelf5b9a742011-12-09 01:25:04 +0000154 // Ignore debug uses because debug info doesn't affect the code.
Evan Cheng23997862010-09-18 06:42:17 +0000155 if (MRI->use_nodbg_empty(Reg))
156 return true;
157
Evan Cheng7af6dc42010-09-20 19:12:55 +0000158 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
159 // into and they are all PHI nodes. In this case, machine-sink must break
160 // the critical edge first. e.g.
161 //
Evan Cheng23997862010-09-18 06:42:17 +0000162 // BB#1: derived from LLVM BB %bb4.preheader
163 // Predecessors according to CFG: BB#0
164 // ...
165 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
166 // ...
167 // JE_4 <BB#37>, %EFLAGS<imp-use>
168 // Successors according to CFG: BB#37 BB#2
169 //
170 // BB#2: derived from LLVM BB %bb.nph
171 // Predecessors according to CFG: BB#0 BB#1
172 // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
Evan Cheng7af6dc42010-09-20 19:12:55 +0000173 BreakPHIEdge = true;
Stephen Hines36b56882014-04-23 16:57:46 -0700174 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
175 MachineInstr *UseInst = MO.getParent();
176 unsigned OpNo = &MO - &UseInst->getOperand(0);
Evan Cheng23997862010-09-18 06:42:17 +0000177 MachineBasicBlock *UseBlock = UseInst->getParent();
178 if (!(UseBlock == MBB && UseInst->isPHI() &&
Stephen Hines36b56882014-04-23 16:57:46 -0700179 UseInst->getOperand(OpNo+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
Stephen Hines36b56882014-04-23 16:57:46 -0700187 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000188 // Determine the block of the use.
Stephen Hines36b56882014-04-23 16:57:46 -0700189 MachineInstr *UseInst = MO.getParent();
190 unsigned OpNo = &MO - &UseInst->getOperand(0);
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000191 MachineBasicBlock *UseBlock = UseInst->getParent();
Evan Cheng23997862010-09-18 06:42:17 +0000192 if (UseInst->isPHI()) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000193 // PHI nodes use the operand in the predecessor block, not the block with
194 // the PHI.
Stephen Hines36b56882014-04-23 16:57:46 -0700195 UseBlock = UseInst->getOperand(OpNo+1).getMBB();
Evan Chenge5e79462010-08-19 18:33:29 +0000196 } else if (UseBlock == DefMBB) {
197 LocalUse = true;
198 return false;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000199 }
Bill Wendling05c68372010-06-02 23:04:26 +0000200
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000201 // Check that it dominates.
202 if (!DT->dominates(MBB, UseBlock))
203 return false;
204 }
Bill Wendling05c68372010-06-02 23:04:26 +0000205
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000206 return true;
207}
208
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000209bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
Stephen Hines36b56882014-04-23 16:57:46 -0700210 if (skipOptnoneFunction(*MF.getFunction()))
211 return false;
212
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>();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000222
223 bool EverMadeChange = false;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000224
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000225 while (1) {
226 bool MadeChange = false;
227
228 // Process all basic blocks.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000229 CEBCandidates.clear();
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000230 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000231 I != E; ++I)
232 MadeChange |= ProcessBlock(*I);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000233
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000234 // If this iteration over the code changed anything, keep iterating.
235 if (!MadeChange) break;
236 EverMadeChange = true;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000237 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000238 return EverMadeChange;
239}
240
241bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000242 // Can't sink anything out of a block that has less than two successors.
Chris Lattner296185c2009-04-10 16:38:36 +0000243 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
244
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000245 // Don't bother sinking code out of unreachable blocks. In addition to being
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000246 // unprofitable, it can also lead to infinite looping, because in an
247 // unreachable loop there may be nowhere to stop.
Dan Gohmanc4ae94d2010-04-05 19:17:22 +0000248 if (!DT->isReachableFromEntry(&MBB)) return false;
249
Chris Lattner296185c2009-04-10 16:38:36 +0000250 bool MadeChange = false;
251
Chris Lattneraad193a2008-01-12 00:17:41 +0000252 // Walk the basic block bottom-up. Remember if we saw a store.
Chris Lattner296185c2009-04-10 16:38:36 +0000253 MachineBasicBlock::iterator I = MBB.end();
254 --I;
255 bool ProcessedBegin, SawStore = false;
256 do {
257 MachineInstr *MI = I; // The instruction to sink.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000258
Chris Lattner296185c2009-04-10 16:38:36 +0000259 // Predecrement I (if it's not begin) so that it isn't invalidated by
260 // sinking.
261 ProcessedBegin = I == MBB.begin();
262 if (!ProcessedBegin)
263 --I;
Dale Johannesenb0812f12010-03-05 00:02:59 +0000264
265 if (MI->isDebugValue())
266 continue;
267
Evan Chengcfea9852011-04-11 18:47:20 +0000268 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
269 if (Joined) {
270 MadeChange = true;
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000271 continue;
Evan Chengcfea9852011-04-11 18:47:20 +0000272 }
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000273
Chris Lattner296185c2009-04-10 16:38:36 +0000274 if (SinkInstruction(MI, SawStore))
275 ++NumSunk, MadeChange = true;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000276
Chris Lattner296185c2009-04-10 16:38:36 +0000277 // If we just processed the first instruction in the block, we're done.
278 } while (!ProcessedBegin);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000279
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000280 return MadeChange;
281}
282
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000283bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
284 MachineBasicBlock *From,
285 MachineBasicBlock *To) {
286 // FIXME: Need much better heuristics.
287
288 // If the pass has already considered breaking this edge (during this pass
289 // through the function), then let's go ahead and break it. This means
290 // sinking multiple "cheap" instructions into the same block.
291 if (!CEBCandidates.insert(std::make_pair(From, To)))
292 return true;
293
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000294 if (!MI->isCopy() && !MI->isAsCheapAsAMove())
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000295 return true;
296
297 // MI is cheap, we probably don't want to break the critical edge for it.
298 // However, if this would allow some definitions of its source operands
299 // to be sunk then it's probably worth it.
300 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
301 const MachineOperand &MO = MI->getOperand(i);
Will Dietze4b44c12013-10-14 16:57:17 +0000302 if (!MO.isReg() || !MO.isUse())
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000303 continue;
Will Dietze4b44c12013-10-14 16:57:17 +0000304 unsigned Reg = MO.getReg();
305 if (Reg == 0)
306 continue;
307
308 // We don't move live definitions of physical registers,
309 // so sinking their uses won't enable any opportunities.
310 if (TargetRegisterInfo::isPhysicalRegister(Reg))
311 continue;
312
313 // If this instruction is the only user of a virtual register,
314 // check if breaking the edge will enable sinking
315 // both this instruction and the defining instruction.
316 if (MRI->hasOneNonDBGUse(Reg)) {
317 // If the definition resides in same MBB,
318 // claim it's likely we can sink these together.
319 // If definition resides elsewhere, we aren't
320 // blocking it from being sunk so don't break the edge.
321 MachineInstr *DefMI = MRI->getVRegDef(Reg);
322 if (DefMI->getParent() == MI->getParent())
323 return true;
324 }
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000325 }
326
327 return false;
328}
329
330MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI,
331 MachineBasicBlock *FromBB,
332 MachineBasicBlock *ToBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000333 bool BreakPHIEdge) {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000334 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
335 return 0;
336
Evan Cheng4dc301a2010-08-19 17:33:11 +0000337 // Avoid breaking back edge. From == To means backedge for single BB loop.
Evan Cheng44be1a82010-09-20 22:52:00 +0000338 if (!SplitEdges || FromBB == ToBB)
Evan Cheng4dc301a2010-08-19 17:33:11 +0000339 return 0;
340
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000341 // Check for backedges of more "complex" loops.
342 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
343 LI->isLoopHeader(ToBB))
344 return 0;
345
346 // It's not always legal to break critical edges and sink the computation
347 // to the edge.
348 //
349 // BB#1:
350 // v1024
351 // Beq BB#3
352 // <fallthrough>
353 // BB#2:
354 // ... no uses of v1024
355 // <fallthrough>
356 // BB#3:
357 // ...
358 // = v1024
359 //
360 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
361 //
362 // BB#1:
363 // ...
364 // Bne BB#2
365 // BB#4:
366 // v1024 =
367 // B BB#3
368 // BB#2:
369 // ... no uses of v1024
370 // <fallthrough>
371 // BB#3:
372 // ...
373 // = v1024
374 //
375 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
376 // flow. We need to ensure the new basic block where the computation is
377 // sunk to dominates all the uses.
378 // It's only legal to break critical edge and sink the computation to the
379 // new block if all the predecessors of "To", except for "From", are
380 // not dominated by "From". Given SSA property, this means these
381 // predecessors are dominated by "To".
382 //
383 // There is no need to do this check if all the uses are PHI nodes. PHI
384 // sources are only defined on the specific predecessor edges.
Evan Cheng7af6dc42010-09-20 19:12:55 +0000385 if (!BreakPHIEdge) {
Evan Cheng4dc301a2010-08-19 17:33:11 +0000386 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
387 E = ToBB->pred_end(); PI != E; ++PI) {
388 if (*PI == FromBB)
389 continue;
390 if (!DT->dominates(ToBB, *PI))
391 return 0;
392 }
Evan Cheng4dc301a2010-08-19 17:33:11 +0000393 }
394
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000395 return FromBB->SplitCriticalEdge(ToBB, this);
Evan Cheng4dc301a2010-08-19 17:33:11 +0000396}
397
Evan Chengb0cdf8a2010-09-23 06:53:00 +0000398static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) {
399 return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence();
400}
401
Andrew Trick1df91b02012-02-08 21:22:43 +0000402/// collectDebgValues - Scan instructions following MI and collect any
Devang Patel541a81c2011-09-07 00:07:58 +0000403/// matching DBG_VALUEs.
Andrew Trick1df91b02012-02-08 21:22:43 +0000404static void collectDebugValues(MachineInstr *MI,
Craig Toppera0ec3f92013-07-14 04:42:23 +0000405 SmallVectorImpl<MachineInstr *> &DbgValues) {
Devang Patel541a81c2011-09-07 00:07:58 +0000406 DbgValues.clear();
407 if (!MI->getOperand(0).isReg())
408 return;
409
410 MachineBasicBlock::iterator DI = MI; ++DI;
411 for (MachineBasicBlock::iterator DE = MI->getParent()->end();
412 DI != DE; ++DI) {
413 if (!DI->isDebugValue())
414 return;
415 if (DI->getOperand(0).isReg() &&
416 DI->getOperand(0).getReg() == MI->getOperand(0).getReg())
417 DbgValues.push_back(DI);
418 }
419}
420
Devang Patel52111342011-12-14 23:20:38 +0000421/// isPostDominatedBy - Return true if A is post dominated by B.
422static bool isPostDominatedBy(MachineBasicBlock *A, MachineBasicBlock *B) {
423
424 // FIXME - Use real post dominator.
425 if (A->succ_size() != 2)
426 return false;
427 MachineBasicBlock::succ_iterator I = A->succ_begin();
428 if (B == *I)
429 ++I;
430 MachineBasicBlock *OtherSuccBlock = *I;
431 if (OtherSuccBlock->succ_size() != 1 ||
432 *(OtherSuccBlock->succ_begin()) != B)
433 return false;
434
435 return true;
436}
437
438/// isProfitableToSinkTo - Return true if it is profitable to sink MI.
Andrew Trick1df91b02012-02-08 21:22:43 +0000439bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
Devang Patel52111342011-12-14 23:20:38 +0000440 MachineBasicBlock *MBB,
441 MachineBasicBlock *SuccToSinkTo) {
442 assert (MI && "Invalid MachineInstr!");
443 assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
444
445 if (MBB == SuccToSinkTo)
446 return false;
447
448 // It is profitable if SuccToSinkTo does not post dominate current block.
449 if (!isPostDominatedBy(MBB, SuccToSinkTo))
450 return true;
451
452 // Check if only use in post dominated block is PHI instruction.
453 bool NonPHIUse = false;
Stephen Hines36b56882014-04-23 16:57:46 -0700454 for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
455 MachineBasicBlock *UseBlock = UseInst.getParent();
456 if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
Devang Patel52111342011-12-14 23:20:38 +0000457 NonPHIUse = true;
458 }
459 if (!NonPHIUse)
460 return true;
461
462 // If SuccToSinkTo post dominates then also it may be profitable if MI
463 // can further profitably sinked into another block in next round.
464 bool BreakPHIEdge = false;
465 // FIXME - If finding successor is compile time expensive then catch results.
466 if (MachineBasicBlock *MBB2 = FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge))
467 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2);
468
469 // If SuccToSinkTo is final destination and it is a post dominator of current
470 // block then it is not profitable to sink MI into SuccToSinkTo block.
471 return false;
472}
473
Devang Patele265bcf2011-12-08 21:48:01 +0000474/// FindSuccToSinkTo - Find a successor to sink this instruction to.
475MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI,
Devang Patel52111342011-12-14 23:20:38 +0000476 MachineBasicBlock *MBB,
477 bool &BreakPHIEdge) {
478
479 assert (MI && "Invalid MachineInstr!");
480 assert (MBB && "Invalid MachineBasicBlock!");
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000481
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000482 // Loop over all the operands of the specified instruction. If there is
483 // anything we can't handle, bail out.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000484
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000485 // SuccToSinkTo - This is the successor to sink this instruction to, once we
486 // decide.
487 MachineBasicBlock *SuccToSinkTo = 0;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000488 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
489 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000490 if (!MO.isReg()) continue; // Ignore non-register operands.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000491
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000492 unsigned Reg = MO.getReg();
493 if (Reg == 0) continue;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000494
Dan Gohman6f0d0242008-02-10 18:45:23 +0000495 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohman19778e72009-09-25 22:53:29 +0000496 if (MO.isUse()) {
497 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000498 // and we can freely move its uses. Alternatively, if it's allocatable,
499 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesenc035c942012-01-16 22:34:08 +0000500 if (!MRI->isConstantPhysReg(Reg, *MBB->getParent()))
Devang Patele265bcf2011-12-08 21:48:01 +0000501 return NULL;
Bill Wendling730c07e2010-06-25 20:48:10 +0000502 } else if (!MO.isDead()) {
503 // A def that isn't dead. We can't move it.
Devang Patele265bcf2011-12-08 21:48:01 +0000504 return NULL;
Dan Gohman19778e72009-09-25 22:53:29 +0000505 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000506 } else {
507 // Virtual register uses are always safe to sink.
508 if (MO.isUse()) continue;
Evan Chengb6f54172009-02-07 01:21:47 +0000509
510 // If it's not safe to move defs of the register class, then abort.
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000511 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
Devang Patele265bcf2011-12-08 21:48:01 +0000512 return NULL;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000513
Chris Lattnere430e1c2008-01-05 06:47:58 +0000514 // FIXME: This picks a successor to sink into based on having one
515 // successor that dominates all the uses. However, there are cases where
516 // sinking can happen but where the sink point isn't a successor. For
517 // example:
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000518 //
Chris Lattnere430e1c2008-01-05 06:47:58 +0000519 // x = computation
520 // if () {} else {}
521 // use x
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000522 //
Bill Wendling05c68372010-06-02 23:04:26 +0000523 // the instruction could be sunk over the whole diamond for the
Chris Lattnere430e1c2008-01-05 06:47:58 +0000524 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
525 // after that.
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000526
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000527 // Virtual register defs can only be sunk if all their uses are in blocks
528 // dominated by one of the successors.
529 if (SuccToSinkTo) {
530 // If a previous operand picked a block to sink to, then this operand
531 // must be sinkable to the same block.
Evan Chenge5e79462010-08-19 18:33:29 +0000532 bool LocalUse = false;
Devang Patel52111342011-12-14 23:20:38 +0000533 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000534 BreakPHIEdge, LocalUse))
Devang Patele265bcf2011-12-08 21:48:01 +0000535 return NULL;
Bill Wendling05c68372010-06-02 23:04:26 +0000536
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000537 continue;
538 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000539
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000540 // Otherwise, we should look at all the successors and decide which one
541 // we should sink to.
Manman Ren53b59d12012-07-31 18:10:39 +0000542 // We give successors with smaller loop depth higher priority.
543 SmallVector<MachineBasicBlock*, 4> Succs(MBB->succ_begin(), MBB->succ_end());
Stephen Hines36b56882014-04-23 16:57:46 -0700544 // Sort Successors according to their loop depth.
545 std::stable_sort(
546 Succs.begin(), Succs.end(),
547 [this](const MachineBasicBlock *LHS, const MachineBasicBlock *RHS) {
548 return LI->getLoopDepth(LHS) < LI->getLoopDepth(RHS);
549 });
Craig Topperf22fd3f2013-07-03 05:11:49 +0000550 for (SmallVectorImpl<MachineBasicBlock *>::iterator SI = Succs.begin(),
551 E = Succs.end(); SI != E; ++SI) {
Devang Patel52111342011-12-14 23:20:38 +0000552 MachineBasicBlock *SuccBlock = *SI;
Evan Chenge5e79462010-08-19 18:33:29 +0000553 bool LocalUse = false;
Devang Patel52111342011-12-14 23:20:38 +0000554 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000555 BreakPHIEdge, LocalUse)) {
Devang Patelcf405ba2011-12-08 21:33:23 +0000556 SuccToSinkTo = SuccBlock;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000557 break;
558 }
Evan Chengc3439ad2010-08-18 23:09:25 +0000559 if (LocalUse)
560 // Def is used locally, it's never safe to move this def.
Devang Patele265bcf2011-12-08 21:48:01 +0000561 return NULL;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000562 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000563
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000564 // If we couldn't find a block to sink to, ignore this instruction.
565 if (SuccToSinkTo == 0)
Devang Patele265bcf2011-12-08 21:48:01 +0000566 return NULL;
Devang Patel52111342011-12-14 23:20:38 +0000567 else if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo))
568 return NULL;
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000569 }
570 }
Devang Patel7f7f0902011-12-08 23:52:00 +0000571
572 // It is not possible to sink an instruction into its own block. This can
573 // happen with loops.
Devang Patel52111342011-12-14 23:20:38 +0000574 if (MBB == SuccToSinkTo)
Devang Patel7f7f0902011-12-08 23:52:00 +0000575 return NULL;
576
577 // It's not safe to sink instructions to EH landing pad. Control flow into
578 // landing pad is implicitly defined.
579 if (SuccToSinkTo && SuccToSinkTo->isLandingPad())
580 return NULL;
581
Devang Patele265bcf2011-12-08 21:48:01 +0000582 return SuccToSinkTo;
583}
584
585/// SinkInstruction - Determine whether it is safe to sink the specified machine
586/// instruction out of its current block into a successor.
587bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
588 // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to
589 // be close to the source to make it easier to coalesce.
590 if (AvoidsSinking(MI, MRI))
591 return false;
592
593 // Check if it's safe to move the instruction.
594 if (!MI->isSafeToMove(TII, AA, SawStore))
595 return false;
596
597 // FIXME: This should include support for sinking instructions within the
598 // block they are currently in to shorten the live ranges. We often get
599 // instructions sunk into the top of a large block, but it would be better to
600 // also sink them down before their first use in the block. This xform has to
601 // be careful not to *increase* register pressure though, e.g. sinking
602 // "x = y + z" down if it kills y and z would increase the live ranges of y
603 // and z and only shrink the live range of x.
604
605 bool BreakPHIEdge = false;
Devang Patel52111342011-12-14 23:20:38 +0000606 MachineBasicBlock *ParentBlock = MI->getParent();
607 MachineBasicBlock *SuccToSinkTo = FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge);
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000608
Chris Lattner9bb459b2008-01-05 01:39:17 +0000609 // If there are no outputs, it must have side-effects.
610 if (SuccToSinkTo == 0)
611 return false;
Evan Chengb5999792009-02-15 08:36:12 +0000612
Bill Wendling869d60d2010-06-03 07:54:20 +0000613
Daniel Dunbard24c9d52010-06-23 00:48:25 +0000614 // If the instruction to move defines a dead physical register which is live
615 // when leaving the basic block, don't move it because it could turn into a
616 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
Bill Wendling730c07e2010-06-25 20:48:10 +0000617 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
618 const MachineOperand &MO = MI->getOperand(I);
619 if (!MO.isReg()) continue;
620 unsigned Reg = MO.getReg();
621 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
622 if (SuccToSinkTo->isLiveIn(Reg))
Bill Wendling869d60d2010-06-03 07:54:20 +0000623 return false;
Bill Wendling730c07e2010-06-25 20:48:10 +0000624 }
Bill Wendling869d60d2010-06-03 07:54:20 +0000625
Bill Wendling05c68372010-06-02 23:04:26 +0000626 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
627
Will Dietze4b44c12013-10-14 16:57:17 +0000628 // If the block has multiple predecessors, this is a critical edge.
629 // Decide if we can sink along it or need to break the edge.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000630 if (SuccToSinkTo->pred_size() > 1) {
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000631 // We cannot sink a load across a critical edge - there may be stores in
632 // other code paths.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000633 bool TryBreak = false;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000634 bool store = true;
635 if (!MI->isSafeToMove(TII, AA, store)) {
Evan Chengf942c132010-08-19 23:33:02 +0000636 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000637 TryBreak = true;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000638 }
639
640 // We don't want to sink across a critical edge if we don't dominate the
641 // successor. We could be introducing calculations to new code paths.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000642 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
Evan Chengf942c132010-08-19 23:33:02 +0000643 DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000644 TryBreak = true;
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000645 }
646
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000647 // Don't sink instructions into a loop.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000648 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
Evan Chengf942c132010-08-19 23:33:02 +0000649 DEBUG(dbgs() << " *** NOTE: Loop header found\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000650 TryBreak = true;
Jakob Stoklund Olesen626f3d72010-04-15 23:41:02 +0000651 }
652
Jakob Stoklund Olesen8d171602010-04-13 19:06:14 +0000653 // Otherwise we are OK with sinking along a critical edge.
Evan Cheng4dc301a2010-08-19 17:33:11 +0000654 if (!TryBreak)
655 DEBUG(dbgs() << "Sinking along critical edge.\n");
656 else {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000657 MachineBasicBlock *NewSucc =
Evan Cheng7af6dc42010-09-20 19:12:55 +0000658 SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
Evan Cheng4dc301a2010-08-19 17:33:11 +0000659 if (!NewSucc) {
Evan Cheng6edb0ea2010-09-17 22:28:18 +0000660 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
661 "break critical edge\n");
Evan Cheng4dc301a2010-08-19 17:33:11 +0000662 return false;
663 } else {
Evan Chengf942c132010-08-19 23:33:02 +0000664 DEBUG(dbgs() << " *** Splitting critical edge:"
Evan Cheng4dc301a2010-08-19 17:33:11 +0000665 " BB#" << ParentBlock->getNumber()
666 << " -- BB#" << NewSucc->getNumber()
667 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
Evan Cheng4dc301a2010-08-19 17:33:11 +0000668 SuccToSinkTo = NewSucc;
669 ++NumSplit;
Evan Cheng7af6dc42010-09-20 19:12:55 +0000670 BreakPHIEdge = false;
Evan Cheng4dc301a2010-08-19 17:33:11 +0000671 }
672 }
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000673 }
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000674
Evan Cheng7af6dc42010-09-20 19:12:55 +0000675 if (BreakPHIEdge) {
676 // BreakPHIEdge is true if all the uses are in the successor MBB being
677 // sunken into and they are all PHI nodes. In this case, machine-sink must
678 // break the critical edge first.
Evan Cheng23997862010-09-18 06:42:17 +0000679 MachineBasicBlock *NewSucc = SplitCriticalEdge(MI, ParentBlock,
Evan Cheng7af6dc42010-09-20 19:12:55 +0000680 SuccToSinkTo, BreakPHIEdge);
Evan Cheng23997862010-09-18 06:42:17 +0000681 if (!NewSucc) {
682 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
683 "break critical edge\n");
684 return false;
685 }
686
687 DEBUG(dbgs() << " *** Splitting critical edge:"
688 " BB#" << ParentBlock->getNumber()
689 << " -- BB#" << NewSucc->getNumber()
690 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
691 SuccToSinkTo = NewSucc;
692 ++NumSplit;
693 }
694
Bill Wendling05c68372010-06-02 23:04:26 +0000695 // Determine where to insert into. Skip phi nodes.
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000696 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
Evan Cheng23997862010-09-18 06:42:17 +0000697 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000698 ++InsertPos;
Jim Grosbach6ee358b2010-06-03 23:49:57 +0000699
Devang Patel541a81c2011-09-07 00:07:58 +0000700 // collect matching debug values.
701 SmallVector<MachineInstr *, 2> DbgValuesToSink;
702 collectDebugValues(MI, DbgValuesToSink);
703
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000704 // Move the instruction.
705 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
706 ++MachineBasicBlock::iterator(MI));
Dan Gohmane6cd7572010-05-13 20:34:42 +0000707
Devang Patel541a81c2011-09-07 00:07:58 +0000708 // Move debug values.
Craig Topperf22fd3f2013-07-03 05:11:49 +0000709 for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
Devang Patel541a81c2011-09-07 00:07:58 +0000710 DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
711 MachineInstr *DbgMI = *DBI;
712 SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI,
713 ++MachineBasicBlock::iterator(DbgMI));
714 }
715
Bill Wendling05c68372010-06-02 23:04:26 +0000716 // Conservatively, clear any kill flags, since it's possible that they are no
717 // longer correct.
Dan Gohmane6cd7572010-05-13 20:34:42 +0000718 MI->clearKillInfo();
719
Chris Lattnerc4ce73f2008-01-04 07:36:53 +0000720 return true;
721}