blob: 3966b123cf9a2a136ef9bfaff1dc70c0e9538454 [file] [log] [blame]
Chris Lattnerf3edc092008-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 Wendling7ee730e2010-06-02 23:04:26 +000010// This pass moves instructions into successor blocks when possible, so that
Dan Gohman5d79a2c2009-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 Lattnerf3edc092008-01-04 07:36:53 +000016//
17//===----------------------------------------------------------------------===//
18
Chris Lattnerf3edc092008-01-04 07:36:53 +000019#include "llvm/CodeGen/Passes.h"
Evan Chenge53ab6d2010-09-17 22:28:18 +000020#include "llvm/ADT/SmallSet.h"
Chris Lattnerf3edc092008-01-04 07:36:53 +000021#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/CodeGen/MachineDominators.h"
24#include "llvm/CodeGen/MachineLoopInfo.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
Evan Chengae9939c2010-08-19 17:33:11 +000026#include "llvm/Support/CommandLine.h"
Chris Lattnerf3edc092008-01-04 07:36:53 +000027#include "llvm/Support/Debug.h"
Bill Wendling63aa0002009-08-22 20:26:23 +000028#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetMachine.h"
31#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000032#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnerf3edc092008-01-04 07:36:53 +000033using namespace llvm;
34
Chandler Carruth1b9dde02014-04-22 02:02:50 +000035#define DEBUG_TYPE "machine-sink"
36
Andrew Trick9e761992012-02-08 21:22:43 +000037static cl::opt<bool>
Evan Chengae9939c2010-08-19 17:33:11 +000038SplitEdges("machine-sink-split",
39 cl::desc("Split critical edges during machine sinking"),
Evan Chengf3e9a482010-09-20 22:52:00 +000040 cl::init(true), cl::Hidden);
Evan Chengae9939c2010-08-19 17:33:11 +000041
Evan Chenge53ab6d2010-09-17 22:28:18 +000042STATISTIC(NumSunk, "Number of machine instructions sunk");
43STATISTIC(NumSplit, "Number of critical edges split");
44STATISTIC(NumCoalesces, "Number of copies coalesced");
Chris Lattnerf3edc092008-01-04 07:36:53 +000045
46namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000047 class MachineSinking : public MachineFunctionPass {
Chris Lattnerf3edc092008-01-04 07:36:53 +000048 const TargetInstrInfo *TII;
Dan Gohmana3176872009-09-25 22:53:29 +000049 const TargetRegisterInfo *TRI;
Evan Chenge53ab6d2010-09-17 22:28:18 +000050 MachineRegisterInfo *MRI; // Machine register information
Dan Gohman5d79a2c2009-08-05 01:19:01 +000051 MachineDominatorTree *DT; // Machine dominator tree
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +000052 MachineLoopInfo *LI;
Dan Gohman87b02d52009-10-09 23:27:56 +000053 AliasAnalysis *AA;
Chris Lattnerf3edc092008-01-04 07:36:53 +000054
Evan Chenge53ab6d2010-09-17 22:28:18 +000055 // Remember which edges have been considered for breaking.
56 SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8>
57 CEBCandidates;
58
Chris Lattnerf3edc092008-01-04 07:36:53 +000059 public:
60 static char ID; // Pass identification
Owen Anderson6c18d1a2010-10-19 17:21:58 +000061 MachineSinking() : MachineFunctionPass(ID) {
62 initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
63 }
Jim Grosbach01edd682010-06-03 23:49:57 +000064
Craig Topper4584cd52014-03-07 09:26:03 +000065 bool runOnMachineFunction(MachineFunction &MF) override;
Jim Grosbach01edd682010-06-03 23:49:57 +000066
Craig Topper4584cd52014-03-07 09:26:03 +000067 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman04023152009-07-31 23:37:33 +000068 AU.setPreservesCFG();
Chris Lattnerf3edc092008-01-04 07:36:53 +000069 MachineFunctionPass::getAnalysisUsage(AU);
Dan Gohman87b02d52009-10-09 23:27:56 +000070 AU.addRequired<AliasAnalysis>();
Chris Lattnerf3edc092008-01-04 07:36:53 +000071 AU.addRequired<MachineDominatorTree>();
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +000072 AU.addRequired<MachineLoopInfo>();
Chris Lattnerf3edc092008-01-04 07:36:53 +000073 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +000074 AU.addPreserved<MachineLoopInfo>();
Chris Lattnerf3edc092008-01-04 07:36:53 +000075 }
Evan Chenge53ab6d2010-09-17 22:28:18 +000076
Craig Topper4584cd52014-03-07 09:26:03 +000077 void releaseMemory() override {
Evan Chenge53ab6d2010-09-17 22:28:18 +000078 CEBCandidates.clear();
79 }
80
Chris Lattnerf3edc092008-01-04 07:36:53 +000081 private:
82 bool ProcessBlock(MachineBasicBlock &MBB);
Evan Chenge53ab6d2010-09-17 22:28:18 +000083 bool isWorthBreakingCriticalEdge(MachineInstr *MI,
84 MachineBasicBlock *From,
85 MachineBasicBlock *To);
86 MachineBasicBlock *SplitCriticalEdge(MachineInstr *MI,
87 MachineBasicBlock *From,
88 MachineBasicBlock *To,
Evan Cheng2031b762010-09-20 19:12:55 +000089 bool BreakPHIEdge);
Chris Lattner08af5a92008-01-12 00:17:41 +000090 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
Evan Cheng25b60682010-08-18 23:09:25 +000091 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
Evan Chenge53ab6d2010-09-17 22:28:18 +000092 MachineBasicBlock *DefMBB,
Evan Cheng2031b762010-09-20 19:12:55 +000093 bool &BreakPHIEdge, bool &LocalUse) const;
Devang Patelc2686882011-12-14 23:20:38 +000094 MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, MachineBasicBlock *MBB,
95 bool &BreakPHIEdge);
Andrew Trick9e761992012-02-08 21:22:43 +000096 bool isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
Devang Patelc2686882011-12-14 23:20:38 +000097 MachineBasicBlock *MBB,
98 MachineBasicBlock *SuccToSinkTo);
Devang Patelb94c9a42011-12-08 21:48:01 +000099
Evan Chenge53ab6d2010-09-17 22:28:18 +0000100 bool PerformTrivialForwardCoalescing(MachineInstr *MI,
101 MachineBasicBlock *MBB);
Chris Lattnerf3edc092008-01-04 07:36:53 +0000102 };
Chris Lattnerf3edc092008-01-04 07:36:53 +0000103} // end anonymous namespace
Jim Grosbach01edd682010-06-03 23:49:57 +0000104
Dan Gohmand78c4002008-05-13 00:00:25 +0000105char MachineSinking::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000106char &llvm::MachineSinkingID = MachineSinking::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000107INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
108 "Machine code sinking", false, false)
109INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
110INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
111INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
112INITIALIZE_PASS_END(MachineSinking, "machine-sink",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000113 "Machine code sinking", false, false)
Chris Lattnerf3edc092008-01-04 07:36:53 +0000114
Evan Chenge53ab6d2010-09-17 22:28:18 +0000115bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
116 MachineBasicBlock *MBB) {
117 if (!MI->isCopy())
118 return false;
119
120 unsigned SrcReg = MI->getOperand(1).getReg();
121 unsigned DstReg = MI->getOperand(0).getReg();
122 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
123 !TargetRegisterInfo::isVirtualRegister(DstReg) ||
124 !MRI->hasOneNonDBGUse(SrcReg))
125 return false;
126
127 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
128 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
129 if (SRC != DRC)
130 return false;
131
132 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
133 if (DefMI->isCopyLike())
134 return false;
135 DEBUG(dbgs() << "Coalescing: " << *DefMI);
136 DEBUG(dbgs() << "*** to: " << *MI);
137 MRI->replaceRegWith(DstReg, SrcReg);
138 MI->eraseFromParent();
139 ++NumCoalesces;
140 return true;
141}
142
Chris Lattnerf3edc092008-01-04 07:36:53 +0000143/// AllUsesDominatedByBlock - Return true if all uses of the specified register
Evan Cheng25b60682010-08-18 23:09:25 +0000144/// occur in blocks dominated by the specified block. If any use is in the
145/// definition block, then return false since it is never legal to move def
146/// after uses.
Evan Chenge53ab6d2010-09-17 22:28:18 +0000147bool
148MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
149 MachineBasicBlock *MBB,
150 MachineBasicBlock *DefMBB,
Evan Cheng2031b762010-09-20 19:12:55 +0000151 bool &BreakPHIEdge,
152 bool &LocalUse) const {
Dan Gohman3a4be0f2008-02-10 18:45:23 +0000153 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
154 "Only makes sense for vregs");
Evan Chengb339f3d2010-09-18 06:42:17 +0000155
Devang Patel706574a2011-12-09 01:25:04 +0000156 // Ignore debug uses because debug info doesn't affect the code.
Evan Chengb339f3d2010-09-18 06:42:17 +0000157 if (MRI->use_nodbg_empty(Reg))
158 return true;
159
Evan Cheng2031b762010-09-20 19:12:55 +0000160 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
161 // into and they are all PHI nodes. In this case, machine-sink must break
162 // the critical edge first. e.g.
163 //
Evan Chengb339f3d2010-09-18 06:42:17 +0000164 // BB#1: derived from LLVM BB %bb4.preheader
165 // Predecessors according to CFG: BB#0
166 // ...
167 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
168 // ...
169 // JE_4 <BB#37>, %EFLAGS<imp-use>
170 // Successors according to CFG: BB#37 BB#2
171 //
172 // BB#2: derived from LLVM BB %bb.nph
173 // Predecessors according to CFG: BB#0 BB#1
174 // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
Evan Cheng2031b762010-09-20 19:12:55 +0000175 BreakPHIEdge = true;
Owen Andersonb36376e2014-03-17 19:36:09 +0000176 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
177 MachineInstr *UseInst = MO.getParent();
178 unsigned OpNo = &MO - &UseInst->getOperand(0);
Evan Chengb339f3d2010-09-18 06:42:17 +0000179 MachineBasicBlock *UseBlock = UseInst->getParent();
180 if (!(UseBlock == MBB && UseInst->isPHI() &&
Owen Andersonb36376e2014-03-17 19:36:09 +0000181 UseInst->getOperand(OpNo+1).getMBB() == DefMBB)) {
Evan Cheng2031b762010-09-20 19:12:55 +0000182 BreakPHIEdge = false;
Evan Chengb339f3d2010-09-18 06:42:17 +0000183 break;
184 }
185 }
Evan Cheng2031b762010-09-20 19:12:55 +0000186 if (BreakPHIEdge)
Evan Chengb339f3d2010-09-18 06:42:17 +0000187 return true;
188
Owen Andersonb36376e2014-03-17 19:36:09 +0000189 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
Chris Lattnerf3edc092008-01-04 07:36:53 +0000190 // Determine the block of the use.
Owen Andersonb36376e2014-03-17 19:36:09 +0000191 MachineInstr *UseInst = MO.getParent();
192 unsigned OpNo = &MO - &UseInst->getOperand(0);
Chris Lattnerf3edc092008-01-04 07:36:53 +0000193 MachineBasicBlock *UseBlock = UseInst->getParent();
Evan Chengb339f3d2010-09-18 06:42:17 +0000194 if (UseInst->isPHI()) {
Chris Lattnerf3edc092008-01-04 07:36:53 +0000195 // PHI nodes use the operand in the predecessor block, not the block with
196 // the PHI.
Owen Andersonb36376e2014-03-17 19:36:09 +0000197 UseBlock = UseInst->getOperand(OpNo+1).getMBB();
Evan Cheng361b9be2010-08-19 18:33:29 +0000198 } else if (UseBlock == DefMBB) {
199 LocalUse = true;
200 return false;
Chris Lattnerf3edc092008-01-04 07:36:53 +0000201 }
Bill Wendling7ee730e2010-06-02 23:04:26 +0000202
Chris Lattnerf3edc092008-01-04 07:36:53 +0000203 // Check that it dominates.
204 if (!DT->dominates(MBB, UseBlock))
205 return false;
206 }
Bill Wendling7ee730e2010-06-02 23:04:26 +0000207
Chris Lattnerf3edc092008-01-04 07:36:53 +0000208 return true;
209}
210
Chris Lattnerf3edc092008-01-04 07:36:53 +0000211bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000212 if (skipOptnoneFunction(*MF.getFunction()))
213 return false;
214
David Greene4b7aa242010-01-05 01:26:00 +0000215 DEBUG(dbgs() << "******** Machine Sinking ********\n");
Jim Grosbach01edd682010-06-03 23:49:57 +0000216
Dan Gohman20a327b2009-10-19 14:52:05 +0000217 const TargetMachine &TM = MF.getTarget();
Eric Christopherd9134482014-08-04 21:25:23 +0000218 TII = TM.getSubtargetImpl()->getInstrInfo();
219 TRI = TM.getSubtargetImpl()->getRegisterInfo();
Evan Chenge53ab6d2010-09-17 22:28:18 +0000220 MRI = &MF.getRegInfo();
Chris Lattnerf3edc092008-01-04 07:36:53 +0000221 DT = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +0000222 LI = &getAnalysis<MachineLoopInfo>();
Dan Gohman87b02d52009-10-09 23:27:56 +0000223 AA = &getAnalysis<AliasAnalysis>();
Chris Lattnerf3edc092008-01-04 07:36:53 +0000224
225 bool EverMadeChange = false;
Jim Grosbach01edd682010-06-03 23:49:57 +0000226
Chris Lattnerf3edc092008-01-04 07:36:53 +0000227 while (1) {
228 bool MadeChange = false;
229
230 // Process all basic blocks.
Evan Chenge53ab6d2010-09-17 22:28:18 +0000231 CEBCandidates.clear();
Jim Grosbach01edd682010-06-03 23:49:57 +0000232 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
Chris Lattnerf3edc092008-01-04 07:36:53 +0000233 I != E; ++I)
234 MadeChange |= ProcessBlock(*I);
Jim Grosbach01edd682010-06-03 23:49:57 +0000235
Chris Lattnerf3edc092008-01-04 07:36:53 +0000236 // If this iteration over the code changed anything, keep iterating.
237 if (!MadeChange) break;
238 EverMadeChange = true;
Jim Grosbach01edd682010-06-03 23:49:57 +0000239 }
Chris Lattnerf3edc092008-01-04 07:36:53 +0000240 return EverMadeChange;
241}
242
243bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
Chris Lattnerf3edc092008-01-04 07:36:53 +0000244 // Can't sink anything out of a block that has less than two successors.
Chris Lattner30c3de62009-04-10 16:38:36 +0000245 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
246
Dan Gohman918a90a2010-04-05 19:17:22 +0000247 // Don't bother sinking code out of unreachable blocks. In addition to being
Jim Grosbach01edd682010-06-03 23:49:57 +0000248 // unprofitable, it can also lead to infinite looping, because in an
249 // unreachable loop there may be nowhere to stop.
Dan Gohman918a90a2010-04-05 19:17:22 +0000250 if (!DT->isReachableFromEntry(&MBB)) return false;
251
Chris Lattner30c3de62009-04-10 16:38:36 +0000252 bool MadeChange = false;
253
Chris Lattner08af5a92008-01-12 00:17:41 +0000254 // Walk the basic block bottom-up. Remember if we saw a store.
Chris Lattner30c3de62009-04-10 16:38:36 +0000255 MachineBasicBlock::iterator I = MBB.end();
256 --I;
257 bool ProcessedBegin, SawStore = false;
258 do {
259 MachineInstr *MI = I; // The instruction to sink.
Jim Grosbach01edd682010-06-03 23:49:57 +0000260
Chris Lattner30c3de62009-04-10 16:38:36 +0000261 // Predecrement I (if it's not begin) so that it isn't invalidated by
262 // sinking.
263 ProcessedBegin = I == MBB.begin();
264 if (!ProcessedBegin)
265 --I;
Dale Johannesen2061c842010-03-05 00:02:59 +0000266
267 if (MI->isDebugValue())
268 continue;
269
Evan Chengfe917ef2011-04-11 18:47:20 +0000270 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
271 if (Joined) {
272 MadeChange = true;
Evan Chenge53ab6d2010-09-17 22:28:18 +0000273 continue;
Evan Chengfe917ef2011-04-11 18:47:20 +0000274 }
Evan Chenge53ab6d2010-09-17 22:28:18 +0000275
Chris Lattner30c3de62009-04-10 16:38:36 +0000276 if (SinkInstruction(MI, SawStore))
277 ++NumSunk, MadeChange = true;
Jim Grosbach01edd682010-06-03 23:49:57 +0000278
Chris Lattner30c3de62009-04-10 16:38:36 +0000279 // If we just processed the first instruction in the block, we're done.
280 } while (!ProcessedBegin);
Jim Grosbach01edd682010-06-03 23:49:57 +0000281
Chris Lattnerf3edc092008-01-04 07:36:53 +0000282 return MadeChange;
283}
284
Evan Chenge53ab6d2010-09-17 22:28:18 +0000285bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
286 MachineBasicBlock *From,
287 MachineBasicBlock *To) {
288 // FIXME: Need much better heuristics.
289
290 // If the pass has already considered breaking this edge (during this pass
291 // through the function), then let's go ahead and break it. This means
292 // sinking multiple "cheap" instructions into the same block.
293 if (!CEBCandidates.insert(std::make_pair(From, To)))
294 return true;
295
Jiangning Liuc3053122014-07-29 01:55:19 +0000296 if (!MI->isCopy() && !TII->isAsCheapAsAMove(MI))
Evan Chenge53ab6d2010-09-17 22:28:18 +0000297 return true;
298
299 // MI is cheap, we probably don't want to break the critical edge for it.
300 // However, if this would allow some definitions of its source operands
301 // to be sunk then it's probably worth it.
302 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
303 const MachineOperand &MO = MI->getOperand(i);
Will Dietz5cb7f4e2013-10-14 16:57:17 +0000304 if (!MO.isReg() || !MO.isUse())
Evan Chenge53ab6d2010-09-17 22:28:18 +0000305 continue;
Will Dietz5cb7f4e2013-10-14 16:57:17 +0000306 unsigned Reg = MO.getReg();
307 if (Reg == 0)
308 continue;
309
310 // We don't move live definitions of physical registers,
311 // so sinking their uses won't enable any opportunities.
312 if (TargetRegisterInfo::isPhysicalRegister(Reg))
313 continue;
314
315 // If this instruction is the only user of a virtual register,
316 // check if breaking the edge will enable sinking
317 // both this instruction and the defining instruction.
318 if (MRI->hasOneNonDBGUse(Reg)) {
319 // If the definition resides in same MBB,
320 // claim it's likely we can sink these together.
321 // If definition resides elsewhere, we aren't
322 // blocking it from being sunk so don't break the edge.
323 MachineInstr *DefMI = MRI->getVRegDef(Reg);
324 if (DefMI->getParent() == MI->getParent())
325 return true;
326 }
Evan Chenge53ab6d2010-09-17 22:28:18 +0000327 }
328
329 return false;
330}
331
332MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI,
333 MachineBasicBlock *FromBB,
334 MachineBasicBlock *ToBB,
Evan Cheng2031b762010-09-20 19:12:55 +0000335 bool BreakPHIEdge) {
Evan Chenge53ab6d2010-09-17 22:28:18 +0000336 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
Craig Topperc0196b12014-04-14 00:51:57 +0000337 return nullptr;
Evan Chenge53ab6d2010-09-17 22:28:18 +0000338
Evan Chengae9939c2010-08-19 17:33:11 +0000339 // Avoid breaking back edge. From == To means backedge for single BB loop.
Evan Chengf3e9a482010-09-20 22:52:00 +0000340 if (!SplitEdges || FromBB == ToBB)
Craig Topperc0196b12014-04-14 00:51:57 +0000341 return nullptr;
Evan Chengae9939c2010-08-19 17:33:11 +0000342
Evan Chenge53ab6d2010-09-17 22:28:18 +0000343 // Check for backedges of more "complex" loops.
344 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
345 LI->isLoopHeader(ToBB))
Craig Topperc0196b12014-04-14 00:51:57 +0000346 return nullptr;
Evan Chenge53ab6d2010-09-17 22:28:18 +0000347
348 // It's not always legal to break critical edges and sink the computation
349 // to the edge.
350 //
351 // BB#1:
352 // v1024
353 // Beq BB#3
354 // <fallthrough>
355 // BB#2:
356 // ... no uses of v1024
357 // <fallthrough>
358 // BB#3:
359 // ...
360 // = v1024
361 //
362 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
363 //
364 // BB#1:
365 // ...
366 // Bne BB#2
367 // BB#4:
368 // v1024 =
369 // B BB#3
370 // BB#2:
371 // ... no uses of v1024
372 // <fallthrough>
373 // BB#3:
374 // ...
375 // = v1024
376 //
377 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
378 // flow. We need to ensure the new basic block where the computation is
379 // sunk to dominates all the uses.
380 // It's only legal to break critical edge and sink the computation to the
381 // new block if all the predecessors of "To", except for "From", are
382 // not dominated by "From". Given SSA property, this means these
383 // predecessors are dominated by "To".
384 //
385 // There is no need to do this check if all the uses are PHI nodes. PHI
386 // sources are only defined on the specific predecessor edges.
Evan Cheng2031b762010-09-20 19:12:55 +0000387 if (!BreakPHIEdge) {
Evan Chengae9939c2010-08-19 17:33:11 +0000388 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
389 E = ToBB->pred_end(); PI != E; ++PI) {
390 if (*PI == FromBB)
391 continue;
392 if (!DT->dominates(ToBB, *PI))
Craig Topperc0196b12014-04-14 00:51:57 +0000393 return nullptr;
Evan Chengae9939c2010-08-19 17:33:11 +0000394 }
Evan Chengae9939c2010-08-19 17:33:11 +0000395 }
396
Evan Chenge53ab6d2010-09-17 22:28:18 +0000397 return FromBB->SplitCriticalEdge(ToBB, this);
Evan Chengae9939c2010-08-19 17:33:11 +0000398}
399
Evan Chengd4b31a72010-09-23 06:53:00 +0000400static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) {
401 return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence();
402}
403
Andrew Trick9e761992012-02-08 21:22:43 +0000404/// collectDebgValues - Scan instructions following MI and collect any
Devang Patel9de7a7d2011-09-07 00:07:58 +0000405/// matching DBG_VALUEs.
Andrew Trick9e761992012-02-08 21:22:43 +0000406static void collectDebugValues(MachineInstr *MI,
Craig Topperb94011f2013-07-14 04:42:23 +0000407 SmallVectorImpl<MachineInstr *> &DbgValues) {
Devang Patel9de7a7d2011-09-07 00:07:58 +0000408 DbgValues.clear();
409 if (!MI->getOperand(0).isReg())
410 return;
411
412 MachineBasicBlock::iterator DI = MI; ++DI;
413 for (MachineBasicBlock::iterator DE = MI->getParent()->end();
414 DI != DE; ++DI) {
415 if (!DI->isDebugValue())
416 return;
417 if (DI->getOperand(0).isReg() &&
418 DI->getOperand(0).getReg() == MI->getOperand(0).getReg())
419 DbgValues.push_back(DI);
420 }
421}
422
Devang Patelc2686882011-12-14 23:20:38 +0000423/// isPostDominatedBy - Return true if A is post dominated by B.
424static bool isPostDominatedBy(MachineBasicBlock *A, MachineBasicBlock *B) {
425
426 // FIXME - Use real post dominator.
427 if (A->succ_size() != 2)
428 return false;
429 MachineBasicBlock::succ_iterator I = A->succ_begin();
430 if (B == *I)
431 ++I;
432 MachineBasicBlock *OtherSuccBlock = *I;
433 if (OtherSuccBlock->succ_size() != 1 ||
434 *(OtherSuccBlock->succ_begin()) != B)
435 return false;
436
437 return true;
438}
439
440/// isProfitableToSinkTo - Return true if it is profitable to sink MI.
Andrew Trick9e761992012-02-08 21:22:43 +0000441bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
Devang Patelc2686882011-12-14 23:20:38 +0000442 MachineBasicBlock *MBB,
443 MachineBasicBlock *SuccToSinkTo) {
444 assert (MI && "Invalid MachineInstr!");
445 assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
446
447 if (MBB == SuccToSinkTo)
448 return false;
449
450 // It is profitable if SuccToSinkTo does not post dominate current block.
451 if (!isPostDominatedBy(MBB, SuccToSinkTo))
452 return true;
453
454 // Check if only use in post dominated block is PHI instruction.
455 bool NonPHIUse = false;
Owen Andersonb36376e2014-03-17 19:36:09 +0000456 for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
457 MachineBasicBlock *UseBlock = UseInst.getParent();
458 if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
Devang Patelc2686882011-12-14 23:20:38 +0000459 NonPHIUse = true;
460 }
461 if (!NonPHIUse)
462 return true;
463
464 // If SuccToSinkTo post dominates then also it may be profitable if MI
465 // can further profitably sinked into another block in next round.
466 bool BreakPHIEdge = false;
467 // FIXME - If finding successor is compile time expensive then catch results.
468 if (MachineBasicBlock *MBB2 = FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge))
469 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2);
470
471 // If SuccToSinkTo is final destination and it is a post dominator of current
472 // block then it is not profitable to sink MI into SuccToSinkTo block.
473 return false;
474}
475
Devang Patelb94c9a42011-12-08 21:48:01 +0000476/// FindSuccToSinkTo - Find a successor to sink this instruction to.
477MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI,
Devang Patelc2686882011-12-14 23:20:38 +0000478 MachineBasicBlock *MBB,
479 bool &BreakPHIEdge) {
480
481 assert (MI && "Invalid MachineInstr!");
482 assert (MBB && "Invalid MachineBasicBlock!");
Jim Grosbach01edd682010-06-03 23:49:57 +0000483
Chris Lattnerf3edc092008-01-04 07:36:53 +0000484 // Loop over all the operands of the specified instruction. If there is
485 // anything we can't handle, bail out.
Jim Grosbach01edd682010-06-03 23:49:57 +0000486
Chris Lattnerf3edc092008-01-04 07:36:53 +0000487 // SuccToSinkTo - This is the successor to sink this instruction to, once we
488 // decide.
Craig Topperc0196b12014-04-14 00:51:57 +0000489 MachineBasicBlock *SuccToSinkTo = nullptr;
Chris Lattnerf3edc092008-01-04 07:36:53 +0000490 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
491 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000492 if (!MO.isReg()) continue; // Ignore non-register operands.
Jim Grosbach01edd682010-06-03 23:49:57 +0000493
Chris Lattnerf3edc092008-01-04 07:36:53 +0000494 unsigned Reg = MO.getReg();
495 if (Reg == 0) continue;
Jim Grosbach01edd682010-06-03 23:49:57 +0000496
Dan Gohman3a4be0f2008-02-10 18:45:23 +0000497 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana3176872009-09-25 22:53:29 +0000498 if (MO.isUse()) {
499 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman2f5bdcb2009-09-26 02:34:00 +0000500 // and we can freely move its uses. Alternatively, if it's allocatable,
501 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesen86ae07f2012-01-16 22:34:08 +0000502 if (!MRI->isConstantPhysReg(Reg, *MBB->getParent()))
Craig Topperc0196b12014-04-14 00:51:57 +0000503 return nullptr;
Bill Wendlinge41e40f2010-06-25 20:48:10 +0000504 } else if (!MO.isDead()) {
505 // A def that isn't dead. We can't move it.
Craig Topperc0196b12014-04-14 00:51:57 +0000506 return nullptr;
Dan Gohmana3176872009-09-25 22:53:29 +0000507 }
Chris Lattnerf3edc092008-01-04 07:36:53 +0000508 } else {
509 // Virtual register uses are always safe to sink.
510 if (MO.isUse()) continue;
Evan Cheng47a65a12009-02-07 01:21:47 +0000511
512 // If it's not safe to move defs of the register class, then abort.
Evan Chenge53ab6d2010-09-17 22:28:18 +0000513 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
Craig Topperc0196b12014-04-14 00:51:57 +0000514 return nullptr;
Jim Grosbach01edd682010-06-03 23:49:57 +0000515
Chris Lattneree61d142008-01-05 06:47:58 +0000516 // FIXME: This picks a successor to sink into based on having one
517 // successor that dominates all the uses. However, there are cases where
518 // sinking can happen but where the sink point isn't a successor. For
519 // example:
Jim Grosbach01edd682010-06-03 23:49:57 +0000520 //
Chris Lattneree61d142008-01-05 06:47:58 +0000521 // x = computation
522 // if () {} else {}
523 // use x
Jim Grosbach01edd682010-06-03 23:49:57 +0000524 //
Bill Wendling7ee730e2010-06-02 23:04:26 +0000525 // the instruction could be sunk over the whole diamond for the
Chris Lattneree61d142008-01-05 06:47:58 +0000526 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
527 // after that.
Jim Grosbach01edd682010-06-03 23:49:57 +0000528
Chris Lattnerf3edc092008-01-04 07:36:53 +0000529 // Virtual register defs can only be sunk if all their uses are in blocks
530 // dominated by one of the successors.
531 if (SuccToSinkTo) {
532 // If a previous operand picked a block to sink to, then this operand
533 // must be sinkable to the same block.
Evan Cheng361b9be2010-08-19 18:33:29 +0000534 bool LocalUse = false;
Devang Patelc2686882011-12-14 23:20:38 +0000535 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
Evan Cheng2031b762010-09-20 19:12:55 +0000536 BreakPHIEdge, LocalUse))
Craig Topperc0196b12014-04-14 00:51:57 +0000537 return nullptr;
Bill Wendling7ee730e2010-06-02 23:04:26 +0000538
Chris Lattnerf3edc092008-01-04 07:36:53 +0000539 continue;
540 }
Jim Grosbach01edd682010-06-03 23:49:57 +0000541
Chris Lattnerf3edc092008-01-04 07:36:53 +0000542 // Otherwise, we should look at all the successors and decide which one
543 // we should sink to.
Manman Ren8c549b52012-07-31 18:10:39 +0000544 // We give successors with smaller loop depth higher priority.
545 SmallVector<MachineBasicBlock*, 4> Succs(MBB->succ_begin(), MBB->succ_end());
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000546 // Sort Successors according to their loop depth.
547 std::stable_sort(
548 Succs.begin(), Succs.end(),
549 [this](const MachineBasicBlock *LHS, const MachineBasicBlock *RHS) {
550 return LI->getLoopDepth(LHS) < LI->getLoopDepth(RHS);
551 });
Craig Toppere1c1d362013-07-03 05:11:49 +0000552 for (SmallVectorImpl<MachineBasicBlock *>::iterator SI = Succs.begin(),
553 E = Succs.end(); SI != E; ++SI) {
Devang Patelc2686882011-12-14 23:20:38 +0000554 MachineBasicBlock *SuccBlock = *SI;
Evan Cheng361b9be2010-08-19 18:33:29 +0000555 bool LocalUse = false;
Devang Patelc2686882011-12-14 23:20:38 +0000556 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
Evan Cheng2031b762010-09-20 19:12:55 +0000557 BreakPHIEdge, LocalUse)) {
Devang Patel1a3c1692011-12-08 21:33:23 +0000558 SuccToSinkTo = SuccBlock;
Chris Lattnerf3edc092008-01-04 07:36:53 +0000559 break;
560 }
Evan Cheng25b60682010-08-18 23:09:25 +0000561 if (LocalUse)
562 // Def is used locally, it's never safe to move this def.
Craig Topperc0196b12014-04-14 00:51:57 +0000563 return nullptr;
Chris Lattnerf3edc092008-01-04 07:36:53 +0000564 }
Jim Grosbach01edd682010-06-03 23:49:57 +0000565
Chris Lattnerf3edc092008-01-04 07:36:53 +0000566 // If we couldn't find a block to sink to, ignore this instruction.
Craig Topperc0196b12014-04-14 00:51:57 +0000567 if (!SuccToSinkTo)
568 return nullptr;
569 if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo))
570 return nullptr;
Chris Lattnerf3edc092008-01-04 07:36:53 +0000571 }
572 }
Devang Patel202cf2f2011-12-08 23:52:00 +0000573
574 // It is not possible to sink an instruction into its own block. This can
575 // happen with loops.
Devang Patelc2686882011-12-14 23:20:38 +0000576 if (MBB == SuccToSinkTo)
Craig Topperc0196b12014-04-14 00:51:57 +0000577 return nullptr;
Devang Patel202cf2f2011-12-08 23:52:00 +0000578
579 // It's not safe to sink instructions to EH landing pad. Control flow into
580 // landing pad is implicitly defined.
581 if (SuccToSinkTo && SuccToSinkTo->isLandingPad())
Craig Topperc0196b12014-04-14 00:51:57 +0000582 return nullptr;
Devang Patel202cf2f2011-12-08 23:52:00 +0000583
Devang Patelb94c9a42011-12-08 21:48:01 +0000584 return SuccToSinkTo;
585}
586
587/// SinkInstruction - Determine whether it is safe to sink the specified machine
588/// instruction out of its current block into a successor.
589bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
590 // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to
591 // be close to the source to make it easier to coalesce.
592 if (AvoidsSinking(MI, MRI))
593 return false;
594
595 // Check if it's safe to move the instruction.
596 if (!MI->isSafeToMove(TII, AA, SawStore))
597 return false;
598
599 // FIXME: This should include support for sinking instructions within the
600 // block they are currently in to shorten the live ranges. We often get
601 // instructions sunk into the top of a large block, but it would be better to
602 // also sink them down before their first use in the block. This xform has to
603 // be careful not to *increase* register pressure though, e.g. sinking
604 // "x = y + z" down if it kills y and z would increase the live ranges of y
605 // and z and only shrink the live range of x.
606
607 bool BreakPHIEdge = false;
Devang Patelc2686882011-12-14 23:20:38 +0000608 MachineBasicBlock *ParentBlock = MI->getParent();
609 MachineBasicBlock *SuccToSinkTo = FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge);
Jim Grosbach01edd682010-06-03 23:49:57 +0000610
Chris Lattner6ec78272008-01-05 01:39:17 +0000611 // If there are no outputs, it must have side-effects.
Craig Topperc0196b12014-04-14 00:51:57 +0000612 if (!SuccToSinkTo)
Chris Lattner6ec78272008-01-05 01:39:17 +0000613 return false;
Evan Cheng25104362009-02-15 08:36:12 +0000614
Bill Wendlingf82aea62010-06-03 07:54:20 +0000615
Daniel Dunbaref5a4382010-06-23 00:48:25 +0000616 // If the instruction to move defines a dead physical register which is live
617 // when leaving the basic block, don't move it because it could turn into a
618 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
Bill Wendlinge41e40f2010-06-25 20:48:10 +0000619 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
620 const MachineOperand &MO = MI->getOperand(I);
621 if (!MO.isReg()) continue;
622 unsigned Reg = MO.getReg();
623 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
624 if (SuccToSinkTo->isLiveIn(Reg))
Bill Wendlingf82aea62010-06-03 07:54:20 +0000625 return false;
Bill Wendlinge41e40f2010-06-25 20:48:10 +0000626 }
Bill Wendlingf82aea62010-06-03 07:54:20 +0000627
Bill Wendling7ee730e2010-06-02 23:04:26 +0000628 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
629
Will Dietz5cb7f4e2013-10-14 16:57:17 +0000630 // If the block has multiple predecessors, this is a critical edge.
631 // Decide if we can sink along it or need to break the edge.
Chris Lattnerf3edc092008-01-04 07:36:53 +0000632 if (SuccToSinkTo->pred_size() > 1) {
Jakob Stoklund Olesen20b71e22010-04-13 19:06:14 +0000633 // We cannot sink a load across a critical edge - there may be stores in
634 // other code paths.
Evan Chengae9939c2010-08-19 17:33:11 +0000635 bool TryBreak = false;
Jakob Stoklund Olesen20b71e22010-04-13 19:06:14 +0000636 bool store = true;
637 if (!MI->isSafeToMove(TII, AA, store)) {
Evan Chenge5af9302010-08-19 23:33:02 +0000638 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
Evan Chengae9939c2010-08-19 17:33:11 +0000639 TryBreak = true;
Jakob Stoklund Olesen20b71e22010-04-13 19:06:14 +0000640 }
641
642 // We don't want to sink across a critical edge if we don't dominate the
643 // successor. We could be introducing calculations to new code paths.
Evan Chengae9939c2010-08-19 17:33:11 +0000644 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
Evan Chenge5af9302010-08-19 23:33:02 +0000645 DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
Evan Chengae9939c2010-08-19 17:33:11 +0000646 TryBreak = true;
Jakob Stoklund Olesen20b71e22010-04-13 19:06:14 +0000647 }
648
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +0000649 // Don't sink instructions into a loop.
Evan Chengae9939c2010-08-19 17:33:11 +0000650 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
Evan Chenge5af9302010-08-19 23:33:02 +0000651 DEBUG(dbgs() << " *** NOTE: Loop header found\n");
Evan Chengae9939c2010-08-19 17:33:11 +0000652 TryBreak = true;
Jakob Stoklund Olesencdc3df42010-04-15 23:41:02 +0000653 }
654
Jakob Stoklund Olesen20b71e22010-04-13 19:06:14 +0000655 // Otherwise we are OK with sinking along a critical edge.
Evan Chengae9939c2010-08-19 17:33:11 +0000656 if (!TryBreak)
657 DEBUG(dbgs() << "Sinking along critical edge.\n");
658 else {
Evan Chenge53ab6d2010-09-17 22:28:18 +0000659 MachineBasicBlock *NewSucc =
Evan Cheng2031b762010-09-20 19:12:55 +0000660 SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
Evan Chengae9939c2010-08-19 17:33:11 +0000661 if (!NewSucc) {
Evan Chenge53ab6d2010-09-17 22:28:18 +0000662 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
663 "break critical edge\n");
Evan Chengae9939c2010-08-19 17:33:11 +0000664 return false;
665 } else {
Evan Chenge5af9302010-08-19 23:33:02 +0000666 DEBUG(dbgs() << " *** Splitting critical edge:"
Evan Chengae9939c2010-08-19 17:33:11 +0000667 " BB#" << ParentBlock->getNumber()
668 << " -- BB#" << NewSucc->getNumber()
669 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
Evan Chengae9939c2010-08-19 17:33:11 +0000670 SuccToSinkTo = NewSucc;
671 ++NumSplit;
Evan Cheng2031b762010-09-20 19:12:55 +0000672 BreakPHIEdge = false;
Evan Chengae9939c2010-08-19 17:33:11 +0000673 }
674 }
Chris Lattnerf3edc092008-01-04 07:36:53 +0000675 }
Jim Grosbach01edd682010-06-03 23:49:57 +0000676
Evan Cheng2031b762010-09-20 19:12:55 +0000677 if (BreakPHIEdge) {
678 // BreakPHIEdge is true if all the uses are in the successor MBB being
679 // sunken into and they are all PHI nodes. In this case, machine-sink must
680 // break the critical edge first.
Evan Chengb339f3d2010-09-18 06:42:17 +0000681 MachineBasicBlock *NewSucc = SplitCriticalEdge(MI, ParentBlock,
Evan Cheng2031b762010-09-20 19:12:55 +0000682 SuccToSinkTo, BreakPHIEdge);
Evan Chengb339f3d2010-09-18 06:42:17 +0000683 if (!NewSucc) {
684 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
685 "break critical edge\n");
686 return false;
687 }
688
689 DEBUG(dbgs() << " *** Splitting critical edge:"
690 " BB#" << ParentBlock->getNumber()
691 << " -- BB#" << NewSucc->getNumber()
692 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
693 SuccToSinkTo = NewSucc;
694 ++NumSplit;
695 }
696
Bill Wendling7ee730e2010-06-02 23:04:26 +0000697 // Determine where to insert into. Skip phi nodes.
Chris Lattnerf3edc092008-01-04 07:36:53 +0000698 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
Evan Chengb339f3d2010-09-18 06:42:17 +0000699 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
Chris Lattnerf3edc092008-01-04 07:36:53 +0000700 ++InsertPos;
Jim Grosbach01edd682010-06-03 23:49:57 +0000701
Devang Patel9de7a7d2011-09-07 00:07:58 +0000702 // collect matching debug values.
703 SmallVector<MachineInstr *, 2> DbgValuesToSink;
704 collectDebugValues(MI, DbgValuesToSink);
705
Chris Lattnerf3edc092008-01-04 07:36:53 +0000706 // Move the instruction.
707 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
708 ++MachineBasicBlock::iterator(MI));
Dan Gohmanc90f51c2010-05-13 20:34:42 +0000709
Devang Patel9de7a7d2011-09-07 00:07:58 +0000710 // Move debug values.
Craig Toppere1c1d362013-07-03 05:11:49 +0000711 for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
Devang Patel9de7a7d2011-09-07 00:07:58 +0000712 DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
713 MachineInstr *DbgMI = *DBI;
714 SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI,
715 ++MachineBasicBlock::iterator(DbgMI));
716 }
717
Bill Wendling7ee730e2010-06-02 23:04:26 +0000718 // Conservatively, clear any kill flags, since it's possible that they are no
719 // longer correct.
Dan Gohmanc90f51c2010-05-13 20:34:42 +0000720 MI->clearKillInfo();
721
Chris Lattnerf3edc092008-01-04 07:36:53 +0000722 return true;
723}