blob: 0b035ba29d45eac36d766e78a4b0fdebea12630d [file] [log] [blame]
Jingyue Wu154eb5a2015-05-15 17:54:48 +00001//===- SpeculativeExecution.cpp ---------------------------------*- C++ -*-===//
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//
10// This pass hoists instructions to enable speculative execution on
11// targets where branches are expensive. This is aimed at GPUs. It
12// currently works on simple if-then and if-then-else
13// patterns.
14//
15// Removing branches is not the only motivation for this
16// pass. E.g. consider this code and assume that there is no
17// addressing mode for multiplying by sizeof(*a):
18//
19// if (b > 0)
20// c = a[i + 1]
21// if (d > 0)
22// e = a[i + 2]
23//
24// turns into
25//
26// p = &a[i + 1];
27// if (b > 0)
28// c = *p;
29// q = &a[i + 2];
30// if (d > 0)
31// e = *q;
32//
33// which could later be optimized to
34//
35// r = &a[i];
36// if (b > 0)
37// c = r[1];
38// if (d > 0)
39// e = r[2];
40//
41// Later passes sink back much of the speculated code that did not enable
42// further optimization.
43//
Jingyue Wu5db9cba2015-05-19 20:52:45 +000044// This pass is more aggressive than the function SpeculativeyExecuteBB in
45// SimplifyCFG. SimplifyCFG will not speculate if no selects are introduced and
46// it will speculate at most one instruction. It also will not speculate if
47// there is a value defined in the if-block that is only used in the then-block.
48// These restrictions make sense since the speculation in SimplifyCFG seems
49// aimed at introducing cheap selects, while this pass is intended to do more
50// aggressive speculation while counting on later passes to either capitalize on
51// that or clean it up.
52//
Justin Lebarcad81cf2016-04-15 00:32:09 +000053// If the pass was created by calling
54// createSpeculativeExecutionIfHasBranchDivergencePass or the
55// -spec-exec-only-if-divergent-target option is present, this pass only has an
56// effect on targets where TargetTransformInfo::hasBranchDivergence() is true;
57// on other targets, it is a nop.
58//
59// This lets you include this pass unconditionally in the IR pass pipeline, but
60// only enable it for relevant targets.
61//
Jingyue Wu154eb5a2015-05-15 17:54:48 +000062//===----------------------------------------------------------------------===//
63
Michael Kupersteinc4061862016-08-01 21:48:33 +000064#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Jingyue Wu154eb5a2015-05-15 17:54:48 +000065#include "llvm/ADT/SmallSet.h"
Kristof Beylsc08f7052016-05-03 08:33:26 +000066#include "llvm/Analysis/GlobalsModRef.h"
Jingyue Wu154eb5a2015-05-15 17:54:48 +000067#include "llvm/Analysis/ValueTracking.h"
68#include "llvm/IR/Instructions.h"
69#include "llvm/IR/Module.h"
70#include "llvm/IR/Operator.h"
71#include "llvm/Support/CommandLine.h"
72#include "llvm/Support/Debug.h"
73
74using namespace llvm;
75
76#define DEBUG_TYPE "speculative-execution"
77
78// The risk that speculation will not pay off increases with the
79// number of instructions speculated, so we put a limit on that.
80static cl::opt<unsigned> SpecExecMaxSpeculationCost(
81 "spec-exec-max-speculation-cost", cl::init(7), cl::Hidden,
82 cl::desc("Speculative execution is not applied to basic blocks where "
83 "the cost of the instructions to speculatively execute "
84 "exceeds this limit."));
85
86// Speculating just a few instructions from a larger block tends not
87// to be profitable and this limit prevents that. A reason for that is
88// that small basic blocks are more likely to be candidates for
89// further optimization.
90static cl::opt<unsigned> SpecExecMaxNotHoisted(
91 "spec-exec-max-not-hoisted", cl::init(5), cl::Hidden,
92 cl::desc("Speculative execution is not applied to basic blocks where the "
93 "number of instructions that would not be speculatively executed "
94 "exceeds this limit."));
95
Justin Lebarcad81cf2016-04-15 00:32:09 +000096static cl::opt<bool> SpecExecOnlyIfDivergentTarget(
Chad Rosier4466ff52016-05-02 19:06:02 +000097 "spec-exec-only-if-divergent-target", cl::init(false), cl::Hidden,
Justin Lebarcad81cf2016-04-15 00:32:09 +000098 cl::desc("Speculative execution is applied only to targets with divergent "
99 "branches, even if the pass was configured to apply only to all "
100 "targets."));
101
Benjamin Kramerd9f06c82015-05-16 16:16:35 +0000102namespace {
Justin Lebarcad81cf2016-04-15 00:32:09 +0000103
Michael Kupersteinc4061862016-08-01 21:48:33 +0000104class SpeculativeExecutionLegacyPass : public FunctionPass {
105public:
106 static char ID;
107 explicit SpeculativeExecutionLegacyPass(bool OnlyIfDivergentTarget = false)
108 : FunctionPass(ID), OnlyIfDivergentTarget(OnlyIfDivergentTarget ||
109 SpecExecOnlyIfDivergentTarget),
110 Impl(OnlyIfDivergentTarget) {}
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000111
Michael Kupersteinc4061862016-08-01 21:48:33 +0000112 void getAnalysisUsage(AnalysisUsage &AU) const override;
113 bool runOnFunction(Function &F) override;
Justin Lebarcad81cf2016-04-15 00:32:09 +0000114
Mehdi Amini117296c2016-10-01 02:56:57 +0000115 StringRef getPassName() const override {
Michael Kupersteinc4061862016-08-01 21:48:33 +0000116 if (OnlyIfDivergentTarget)
117 return "Speculatively execute instructions if target has divergent "
118 "branches";
119 return "Speculatively execute instructions";
120 }
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000121
Michael Kupersteinc4061862016-08-01 21:48:33 +0000122private:
123 // Variable preserved purely for correct name printing.
Justin Lebarcad81cf2016-04-15 00:32:09 +0000124 const bool OnlyIfDivergentTarget;
Michael Kupersteinc4061862016-08-01 21:48:33 +0000125
126 SpeculativeExecutionPass Impl;
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000127};
Benjamin Kramerd9f06c82015-05-16 16:16:35 +0000128} // namespace
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000129
Michael Kupersteinc4061862016-08-01 21:48:33 +0000130char SpeculativeExecutionLegacyPass::ID = 0;
131INITIALIZE_PASS_BEGIN(SpeculativeExecutionLegacyPass, "speculative-execution",
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000132 "Speculatively execute instructions", false, false)
133INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Michael Kupersteinc4061862016-08-01 21:48:33 +0000134INITIALIZE_PASS_END(SpeculativeExecutionLegacyPass, "speculative-execution",
Justin Lebarcad81cf2016-04-15 00:32:09 +0000135 "Speculatively execute instructions", false, false)
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000136
Michael Kupersteinc4061862016-08-01 21:48:33 +0000137void SpeculativeExecutionLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000138 AU.addRequired<TargetTransformInfoWrapperPass>();
Kristof Beylsc08f7052016-05-03 08:33:26 +0000139 AU.addPreserved<GlobalsAAWrapperPass>();
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000140}
141
Michael Kupersteinc4061862016-08-01 21:48:33 +0000142bool SpeculativeExecutionLegacyPass::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000143 if (skipFunction(F))
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000144 return false;
145
Michael Kupersteinc4061862016-08-01 21:48:33 +0000146 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
147 return Impl.runImpl(F, TTI);
148}
149
150namespace llvm {
151
152bool SpeculativeExecutionPass::runImpl(Function &F, TargetTransformInfo *TTI) {
Justin Lebarcad81cf2016-04-15 00:32:09 +0000153 if (OnlyIfDivergentTarget && !TTI->hasBranchDivergence()) {
154 DEBUG(dbgs() << "Not running SpeculativeExecution because "
155 "TTI->hasBranchDivergence() is false.\n");
156 return false;
157 }
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000158
Michael Kupersteinc4061862016-08-01 21:48:33 +0000159 this->TTI = TTI;
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000160 bool Changed = false;
161 for (auto& B : F) {
162 Changed |= runOnBasicBlock(B);
163 }
164 return Changed;
165}
166
Michael Kupersteinc4061862016-08-01 21:48:33 +0000167bool SpeculativeExecutionPass::runOnBasicBlock(BasicBlock &B) {
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000168 BranchInst *BI = dyn_cast<BranchInst>(B.getTerminator());
169 if (BI == nullptr)
170 return false;
171
172 if (BI->getNumSuccessors() != 2)
173 return false;
174 BasicBlock &Succ0 = *BI->getSuccessor(0);
175 BasicBlock &Succ1 = *BI->getSuccessor(1);
176
177 if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
178 return false;
179 }
180
181 // Hoist from if-then (triangle).
182 if (Succ0.getSinglePredecessor() != nullptr &&
183 Succ0.getSingleSuccessor() == &Succ1) {
184 return considerHoistingFromTo(Succ0, B);
185 }
186
187 // Hoist from if-else (triangle).
188 if (Succ1.getSinglePredecessor() != nullptr &&
189 Succ1.getSingleSuccessor() == &Succ0) {
190 return considerHoistingFromTo(Succ1, B);
191 }
192
193 // Hoist from if-then-else (diamond), but only if it is equivalent to
194 // an if-else or if-then due to one of the branches doing nothing.
195 if (Succ0.getSinglePredecessor() != nullptr &&
196 Succ1.getSinglePredecessor() != nullptr &&
197 Succ1.getSingleSuccessor() != nullptr &&
198 Succ1.getSingleSuccessor() != &B &&
199 Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
200 // If a block has only one instruction, then that is a terminator
201 // instruction so that the block does nothing. This does happen.
202 if (Succ1.size() == 1) // equivalent to if-then
203 return considerHoistingFromTo(Succ0, B);
204 if (Succ0.size() == 1) // equivalent to if-else
205 return considerHoistingFromTo(Succ1, B);
206 }
207
208 return false;
209}
210
211static unsigned ComputeSpeculationCost(const Instruction *I,
212 const TargetTransformInfo &TTI) {
213 switch (Operator::getOpcode(I)) {
214 case Instruction::GetElementPtr:
215 case Instruction::Add:
216 case Instruction::Mul:
217 case Instruction::And:
218 case Instruction::Or:
219 case Instruction::Select:
220 case Instruction::Shl:
221 case Instruction::Sub:
222 case Instruction::LShr:
223 case Instruction::AShr:
224 case Instruction::Xor:
225 case Instruction::ZExt:
226 case Instruction::SExt:
227 return TTI.getUserCost(I);
228
229 default:
230 return UINT_MAX; // Disallow anything not whitelisted.
231 }
232}
233
Michael Kupersteinc4061862016-08-01 21:48:33 +0000234bool SpeculativeExecutionPass::considerHoistingFromTo(
235 BasicBlock &FromBlock, BasicBlock &ToBlock) {
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000236 SmallSet<const Instruction *, 8> NotHoisted;
237 const auto AllPrecedingUsesFromBlockHoisted = [&NotHoisted](User *U) {
238 for (Value* V : U->operand_values()) {
239 if (Instruction *I = dyn_cast<Instruction>(V)) {
240 if (NotHoisted.count(I) > 0)
241 return false;
242 }
243 }
244 return true;
245 };
246
247 unsigned TotalSpeculationCost = 0;
248 for (auto& I : FromBlock) {
249 const unsigned Cost = ComputeSpeculationCost(&I, *TTI);
250 if (Cost != UINT_MAX && isSafeToSpeculativelyExecute(&I) &&
251 AllPrecedingUsesFromBlockHoisted(&I)) {
252 TotalSpeculationCost += Cost;
253 if (TotalSpeculationCost > SpecExecMaxSpeculationCost)
254 return false; // too much to hoist
255 } else {
256 NotHoisted.insert(&I);
257 if (NotHoisted.size() > SpecExecMaxNotHoisted)
258 return false; // too much left behind
259 }
260 }
261
262 if (TotalSpeculationCost == 0)
263 return false; // nothing to hoist
264
265 for (auto I = FromBlock.begin(); I != FromBlock.end();) {
266 // We have to increment I before moving Current as moving Current
267 // changes the list that I is iterating through.
268 auto Current = I;
269 ++I;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000270 if (!NotHoisted.count(&*Current)) {
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000271 Current->moveBefore(ToBlock.getTerminator());
272 }
273 }
274 return true;
275}
276
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000277FunctionPass *createSpeculativeExecutionPass() {
Michael Kupersteinc4061862016-08-01 21:48:33 +0000278 return new SpeculativeExecutionLegacyPass();
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000279}
280
Justin Lebarcad81cf2016-04-15 00:32:09 +0000281FunctionPass *createSpeculativeExecutionIfHasBranchDivergencePass() {
Michael Kupersteinc4061862016-08-01 21:48:33 +0000282 return new SpeculativeExecutionLegacyPass(/* OnlyIfDivergentTarget = */ true);
Justin Lebarcad81cf2016-04-15 00:32:09 +0000283}
284
Michael Kupersteinc4061862016-08-01 21:48:33 +0000285SpeculativeExecutionPass::SpeculativeExecutionPass(bool OnlyIfDivergentTarget)
286 : OnlyIfDivergentTarget(OnlyIfDivergentTarget ||
287 SpecExecOnlyIfDivergentTarget) {}
288
289PreservedAnalyses SpeculativeExecutionPass::run(Function &F,
290 FunctionAnalysisManager &AM) {
291 auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
292
293 bool Changed = runImpl(F, TTI);
294
295 if (!Changed)
296 return PreservedAnalyses::all();
297 PreservedAnalyses PA;
298 PA.preserve<GlobalsAA>();
299 return PA;
300}
Jingyue Wu154eb5a2015-05-15 17:54:48 +0000301} // namespace llvm