1//===- SpeculativeExecution.cpp ---------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass hoists instructions to enable speculative execution on
10// targets where branches are expensive. This is aimed at GPUs. It
11// currently works on simple if-then and if-then-else
12// patterns.
13//
14// Removing branches is not the only motivation for this
15// pass. E.g. consider this code and assume that there is no
16// addressing mode for multiplying by sizeof(*a):
17//
18// if (b > 0)
19// c = a[i + 1]
20// if (d > 0)
21// e = a[i + 2]
22//
23// turns into
24//
25// p = &a[i + 1];
26// if (b > 0)
27// c = *p;
28// q = &a[i + 2];
29// if (d > 0)
30// e = *q;
31//
32// which could later be optimized to
33//
34// r = &a[i];
35// if (b > 0)
36// c = r[1];
37// if (d > 0)
38// e = r[2];
39//
40// Later passes sink back much of the speculated code that did not enable
41// further optimization.
42//
43// This pass is more aggressive than the function SpeculativeyExecuteBB in
44// SimplifyCFG. SimplifyCFG will not speculate if no selects are introduced and
45// it will speculate at most one instruction. It also will not speculate if
46// there is a value defined in the if-block that is only used in the then-block.
47// These restrictions make sense since the speculation in SimplifyCFG seems
48// aimed at introducing cheap selects, while this pass is intended to do more
49// aggressive speculation while counting on later passes to either capitalize on
50// that or clean it up.
51//
52// If the pass was created by calling
53// createSpeculativeExecutionIfHasBranchDivergencePass or the
54// -spec-exec-only-if-divergent-target option is present, this pass only has an
55// effect on targets where TargetTransformInfo::hasBranchDivergence() is true;
56// on other targets, it is a nop.
57//
58// This lets you include this pass unconditionally in the IR pass pipeline, but
59// only enable it for relevant targets.
60//
61//===----------------------------------------------------------------------===//
62
63#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
64#include "llvm/ADT/SmallPtrSet.h"
65#include "llvm/Analysis/GlobalsModRef.h"
66#include "llvm/Analysis/TargetTransformInfo.h"
67#include "llvm/Analysis/ValueTracking.h"
68#include "llvm/IR/Instructions.h"
69#include "llvm/IR/Operator.h"
70#include "llvm/InitializePasses.h"
71#include "llvm/Support/CommandLine.h"
72#include "llvm/Support/Debug.h"
73#include "llvm/Transforms/Scalar.h"
74
75using namespace llvm;
76
77#define DEBUG_TYPE "speculative-execution"
78
79// The risk that speculation will not pay off increases with the
80// number of instructions speculated, so we put a limit on that.
81static cl::opt<unsigned> SpecExecMaxSpeculationCost(
82 "spec-exec-max-speculation-cost", cl::init(Val: 7), cl::Hidden,
83 cl::desc("Speculative execution is not applied to basic blocks where "
84 "the cost of the instructions to speculatively execute "
85 "exceeds this limit."));
86
87// Speculating just a few instructions from a larger block tends not
88// to be profitable and this limit prevents that. A reason for that is
89// that small basic blocks are more likely to be candidates for
90// further optimization.
91static cl::opt<unsigned> SpecExecMaxNotHoisted(
92 "spec-exec-max-not-hoisted", cl::init(Val: 5), cl::Hidden,
93 cl::desc("Speculative execution is not applied to basic blocks where the "
94 "number of instructions that would not be speculatively executed "
95 "exceeds this limit."));
96
97static cl::opt<bool> SpecExecOnlyIfDivergentTarget(
98 "spec-exec-only-if-divergent-target", cl::init(Val: false), cl::Hidden,
99 cl::desc("Speculative execution is applied only to targets with divergent "
100 "branches, even if the pass was configured to apply only to all "
101 "targets."));
102
103namespace {
104
105class SpeculativeExecutionLegacyPass : public FunctionPass {
106public:
107 static char ID;
108 explicit SpeculativeExecutionLegacyPass(bool OnlyIfDivergentTarget = false)
109 : FunctionPass(ID), OnlyIfDivergentTarget(OnlyIfDivergentTarget ||
110 SpecExecOnlyIfDivergentTarget),
111 Impl(OnlyIfDivergentTarget) {}
112
113 void getAnalysisUsage(AnalysisUsage &AU) const override;
114 bool runOnFunction(Function &F) override;
115
116 StringRef getPassName() const override {
117 if (OnlyIfDivergentTarget)
118 return "Speculatively execute instructions if target has divergent "
119 "branches";
120 return "Speculatively execute instructions";
121 }
122
123private:
124 // Variable preserved purely for correct name printing.
125 const bool OnlyIfDivergentTarget;
126
127 SpeculativeExecutionPass Impl;
128};
129} // namespace
130
131char SpeculativeExecutionLegacyPass::ID = 0;
132INITIALIZE_PASS_BEGIN(SpeculativeExecutionLegacyPass, "speculative-execution",
133 "Speculatively execute instructions", false, false)
134INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
135INITIALIZE_PASS_END(SpeculativeExecutionLegacyPass, "speculative-execution",
136 "Speculatively execute instructions", false, false)
137
138void SpeculativeExecutionLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
139 AU.addRequired<TargetTransformInfoWrapperPass>();
140 AU.addPreserved<GlobalsAAWrapperPass>();
141 AU.setPreservesCFG();
142}
143
144bool SpeculativeExecutionLegacyPass::runOnFunction(Function &F) {
145 if (skipFunction(F))
146 return false;
147
148 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
149 return Impl.runImpl(F, TTI);
150}
151
152bool SpeculativeExecutionPass::runImpl(Function &F, TargetTransformInfo *TTI) {
153 if (OnlyIfDivergentTarget && !TTI->hasBranchDivergence(F: &F)) {
154 LLVM_DEBUG(dbgs() << "Not running SpeculativeExecution because "
155 "TTI->hasBranchDivergence() is false.\n");
156 return false;
157 }
158
159 this->TTI = TTI;
160 bool Changed = false;
161 for (auto& B : F) {
162 Changed |= runOnBasicBlock(B);
163 }
164 return Changed;
165}
166
167bool SpeculativeExecutionPass::runOnBasicBlock(BasicBlock &B) {
168 CondBrInst *BI = dyn_cast<CondBrInst>(Val: B.getTerminator());
169 if (!BI)
170 return false;
171
172 BasicBlock &Succ0 = *BI->getSuccessor(i: 0);
173 BasicBlock &Succ1 = *BI->getSuccessor(i: 1);
174
175 if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
176 return false;
177 }
178
179 // Hoist from if-then (triangle).
180 if (Succ0.getSinglePredecessor() != nullptr &&
181 Succ0.getSingleSuccessor() == &Succ1) {
182 return considerHoistingFromTo(FromBlock&: Succ0, ToBlock&: B);
183 }
184
185 // Hoist from if-else (triangle).
186 if (Succ1.getSinglePredecessor() != nullptr &&
187 Succ1.getSingleSuccessor() == &Succ0) {
188 return considerHoistingFromTo(FromBlock&: Succ1, ToBlock&: B);
189 }
190
191 // Hoist from if-then-else (diamond), but only if it is equivalent to
192 // an if-else or if-then due to one of the branches doing nothing.
193 if (Succ0.getSinglePredecessor() != nullptr &&
194 Succ1.getSinglePredecessor() != nullptr &&
195 Succ1.getSingleSuccessor() != nullptr &&
196 Succ1.getSingleSuccessor() != &B &&
197 Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
198 // If a block has only one instruction, then that is a terminator
199 // instruction so that the block does nothing. This does happen.
200 if (Succ1.size() == 1) // equivalent to if-then
201 return considerHoistingFromTo(FromBlock&: Succ0, ToBlock&: B);
202 if (Succ0.size() == 1) // equivalent to if-else
203 return considerHoistingFromTo(FromBlock&: Succ1, ToBlock&: B);
204 }
205
206 return false;
207}
208
209static InstructionCost ComputeSpeculationCost(const Instruction *I,
210 const TargetTransformInfo &TTI) {
211 switch (Operator::getOpcode(V: I)) {
212 case Instruction::GetElementPtr:
213 case Instruction::Add:
214 case Instruction::Mul:
215 case Instruction::And:
216 case Instruction::Or:
217 case Instruction::Select:
218 case Instruction::Shl:
219 case Instruction::Sub:
220 case Instruction::LShr:
221 case Instruction::AShr:
222 case Instruction::Xor:
223 case Instruction::ZExt:
224 case Instruction::SExt:
225 case Instruction::Call:
226 case Instruction::BitCast:
227 case Instruction::PtrToInt:
228 case Instruction::PtrToAddr:
229 case Instruction::IntToPtr:
230 case Instruction::AddrSpaceCast:
231 case Instruction::FPToUI:
232 case Instruction::FPToSI:
233 case Instruction::UIToFP:
234 case Instruction::SIToFP:
235 case Instruction::FPExt:
236 case Instruction::FPTrunc:
237 case Instruction::FAdd:
238 case Instruction::FSub:
239 case Instruction::FMul:
240 case Instruction::FDiv:
241 case Instruction::FRem:
242 case Instruction::FNeg:
243 case Instruction::ICmp:
244 case Instruction::FCmp:
245 case Instruction::Trunc:
246 case Instruction::Freeze:
247 case Instruction::ExtractElement:
248 case Instruction::InsertElement:
249 case Instruction::ShuffleVector:
250 case Instruction::ExtractValue:
251 case Instruction::InsertValue:
252 return TTI.getInstructionCost(U: I, CostKind: TargetTransformInfo::TCK_SizeAndLatency);
253
254 default:
255 return InstructionCost::getInvalid(); // Disallow anything not explicitly
256 // listed.
257 }
258}
259
260// Do not hoist any debug info intrinsics.
261// ...
262// if (cond) {
263// x = y * z;
264// foo();
265// }
266// ...
267// -------- Which then becomes:
268// ...
269// if.then:
270// %x = mul i32 %y, %z
271// call void @llvm.dbg.value(%x, !"x", !DIExpression())
272// call void foo()
273//
274// SpeculativeExecution might decide to hoist the 'y * z' calculation
275// out of the 'if' block, because it is more efficient that way, so the
276// '%x = mul i32 %y, %z' moves to the block above. But it might also
277// decide to hoist the 'llvm.dbg.value' call.
278// This is incorrect, because even if we've moved the calculation of
279// 'y * z', we should not see the value of 'x' change unless we
280// actually go inside the 'if' block.
281
282bool SpeculativeExecutionPass::considerHoistingFromTo(
283 BasicBlock &FromBlock, BasicBlock &ToBlock) {
284 SmallPtrSet<const Instruction *, 8> NotHoisted;
285 auto HasNoUnhoistedInstr = [&NotHoisted](auto Values) {
286 for (const Value *V : Values) {
287 if (const auto *I = dyn_cast_or_null<Instruction>(Val: V))
288 if (NotHoisted.contains(Ptr: I))
289 return false;
290 }
291 return true;
292 };
293 auto AllPrecedingUsesFromBlockHoisted =
294 [&HasNoUnhoistedInstr](const User *U) {
295 return HasNoUnhoistedInstr(U->operand_values());
296 };
297
298 InstructionCost TotalSpeculationCost = 0;
299 unsigned NotHoistedInstCount = 0;
300 for (const auto &I : FromBlock) {
301 const InstructionCost Cost = ComputeSpeculationCost(I: &I, TTI: *TTI);
302 if (Cost.isValid() && isSafeToSpeculativelyExecute(I: &I) &&
303 AllPrecedingUsesFromBlockHoisted(&I)) {
304 TotalSpeculationCost += Cost;
305 if (TotalSpeculationCost > SpecExecMaxSpeculationCost)
306 return false; // too much to hoist
307 } else {
308 NotHoistedInstCount++;
309 if (NotHoistedInstCount > SpecExecMaxNotHoisted)
310 return false; // too much left behind
311 NotHoisted.insert(Ptr: &I);
312 }
313 }
314
315 for (auto I = FromBlock.begin(); I != FromBlock.end();) {
316 // We have to increment I before moving Current as moving Current
317 // changes the list that I is iterating through.
318 auto Current = I;
319 ++I;
320 if (!NotHoisted.count(Ptr: &*Current)) {
321 Current->moveBefore(InsertPos: ToBlock.getTerminator()->getIterator());
322 Current->dropLocation();
323 }
324 }
325 return true;
326}
327
328FunctionPass *llvm::createSpeculativeExecutionPass() {
329 return new SpeculativeExecutionLegacyPass();
330}
331
332FunctionPass *llvm::createSpeculativeExecutionIfHasBranchDivergencePass() {
333 return new SpeculativeExecutionLegacyPass(/* OnlyIfDivergentTarget = */ true);
334}
335
336SpeculativeExecutionPass::SpeculativeExecutionPass(bool OnlyIfDivergentTarget)
337 : OnlyIfDivergentTarget(OnlyIfDivergentTarget ||
338 SpecExecOnlyIfDivergentTarget) {}
339
340PreservedAnalyses SpeculativeExecutionPass::run(Function &F,
341 FunctionAnalysisManager &AM) {
342 auto *TTI = &AM.getResult<TargetIRAnalysis>(IR&: F);
343
344 bool Changed = runImpl(F, TTI);
345
346 if (!Changed)
347 return PreservedAnalyses::all();
348 PreservedAnalyses PA;
349 PA.preserveSet<CFGAnalyses>();
350 return PA;
351}
352
353void SpeculativeExecutionPass::printPipeline(
354 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
355 static_cast<PassInfoMixin<SpeculativeExecutionPass> *>(this)->printPipeline(
356 OS, MapClassName2PassName);
357 OS << '<';
358 if (OnlyIfDivergentTarget)
359 OS << "only-if-divergent-target";
360 OS << '>';
361}
362