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 "ScalarOptions.h"
65#include "llvm/ADT/SmallPtrSet.h"
66#include "llvm/Analysis/GlobalsModRef.h"
67#include "llvm/Analysis/TargetTransformInfo.h"
68#include "llvm/Analysis/ValueTracking.h"
69#include "llvm/IR/Instructions.h"
70#include "llvm/IR/Operator.h"
71#include "llvm/InitializePasses.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
79namespace {
80
81class SpeculativeExecutionLegacyPass : public FunctionPass {
82public:
83 static char ID;
84 explicit SpeculativeExecutionLegacyPass(bool OnlyIfDivergentTarget = false)
85 : FunctionPass(ID), OnlyIfDivergentTarget(OnlyIfDivergentTarget),
86 Impl(OnlyIfDivergentTarget) {}
87
88 void getAnalysisUsage(AnalysisUsage &AU) const override;
89 bool runOnFunction(Function &F) override;
90
91 StringRef getPassName() const override {
92 if (OnlyIfDivergentTarget)
93 return "Speculatively execute instructions if target has divergent "
94 "branches";
95 return "Speculatively execute instructions";
96 }
97
98private:
99 // Variable preserved purely for correct name printing.
100 const bool OnlyIfDivergentTarget;
101
102 SpeculativeExecutionPass Impl;
103};
104} // namespace
105
106char SpeculativeExecutionLegacyPass::ID = 0;
107INITIALIZE_PASS_BEGIN(SpeculativeExecutionLegacyPass, "speculative-execution",
108 "Speculatively execute instructions", false, false)
109INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
110INITIALIZE_PASS_END(SpeculativeExecutionLegacyPass, "speculative-execution",
111 "Speculatively execute instructions", false, false)
112
113void SpeculativeExecutionLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
114 AU.addRequired<TargetTransformInfoWrapperPass>();
115 AU.addPreserved<GlobalsAAWrapperPass>();
116 AU.setPreservesCFG();
117}
118
119bool SpeculativeExecutionLegacyPass::runOnFunction(Function &F) {
120 if (skipFunction(F))
121 return false;
122
123 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
124 return Impl.runImpl(F, TTI);
125}
126
127bool SpeculativeExecutionPass::runImpl(Function &F, TargetTransformInfo *TTI) {
128 Opts = &F.getContext().getLibraryOptions().get<ScalarOptions>();
129 if ((OnlyIfDivergentTarget || Opts->spec_exec_only_if_divergent_target) &&
130 !TTI->hasBranchDivergence(F: &F)) {
131 LLVM_DEBUG(dbgs() << "Not running SpeculativeExecution because "
132 "TTI->hasBranchDivergence() is false.\n");
133 return false;
134 }
135
136 this->TTI = TTI;
137 bool Changed = false;
138 for (auto& B : F) {
139 Changed |= runOnBasicBlock(B);
140 }
141 return Changed;
142}
143
144bool SpeculativeExecutionPass::runOnBasicBlock(BasicBlock &B) {
145 CondBrInst *BI = dyn_cast<CondBrInst>(Val: B.getTerminator());
146 if (!BI)
147 return false;
148
149 BasicBlock &Succ0 = *BI->getSuccessor(i: 0);
150 BasicBlock &Succ1 = *BI->getSuccessor(i: 1);
151
152 if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
153 return false;
154 }
155
156 // Hoist from if-then (triangle).
157 if (Succ0.getSinglePredecessor() != nullptr &&
158 Succ0.getSingleSuccessor() == &Succ1) {
159 return considerHoistingFromTo(FromBlock&: Succ0, ToBlock&: B);
160 }
161
162 // Hoist from if-else (triangle).
163 if (Succ1.getSinglePredecessor() != nullptr &&
164 Succ1.getSingleSuccessor() == &Succ0) {
165 return considerHoistingFromTo(FromBlock&: Succ1, ToBlock&: B);
166 }
167
168 // Hoist from if-then-else (diamond), but only if it is equivalent to
169 // an if-else or if-then due to one of the branches doing nothing.
170 if (Succ0.getSinglePredecessor() != nullptr &&
171 Succ1.getSinglePredecessor() != nullptr &&
172 Succ1.getSingleSuccessor() != nullptr &&
173 Succ1.getSingleSuccessor() != &B &&
174 Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
175 // If a block has only one instruction, then that is a terminator
176 // instruction so that the block does nothing. This does happen.
177 if (Succ1.size() == 1) // equivalent to if-then
178 return considerHoistingFromTo(FromBlock&: Succ0, ToBlock&: B);
179 if (Succ0.size() == 1) // equivalent to if-else
180 return considerHoistingFromTo(FromBlock&: Succ1, ToBlock&: B);
181 }
182
183 return false;
184}
185
186static InstructionCost ComputeSpeculationCost(const Instruction *I,
187 const TargetTransformInfo &TTI) {
188 switch (Operator::getOpcode(V: I)) {
189 case Instruction::GetElementPtr:
190 case Instruction::Add:
191 case Instruction::Mul:
192 case Instruction::And:
193 case Instruction::Or:
194 case Instruction::Select:
195 case Instruction::Shl:
196 case Instruction::Sub:
197 case Instruction::LShr:
198 case Instruction::AShr:
199 case Instruction::Xor:
200 case Instruction::ZExt:
201 case Instruction::SExt:
202 case Instruction::Call:
203 case Instruction::BitCast:
204 case Instruction::PtrToInt:
205 case Instruction::PtrToAddr:
206 case Instruction::IntToPtr:
207 case Instruction::AddrSpaceCast:
208 case Instruction::FPToUI:
209 case Instruction::FPToSI:
210 case Instruction::UIToFP:
211 case Instruction::SIToFP:
212 case Instruction::FPExt:
213 case Instruction::FPTrunc:
214 case Instruction::FAdd:
215 case Instruction::FSub:
216 case Instruction::FMul:
217 case Instruction::FDiv:
218 case Instruction::FRem:
219 case Instruction::FNeg:
220 case Instruction::ICmp:
221 case Instruction::FCmp:
222 case Instruction::Trunc:
223 case Instruction::Freeze:
224 case Instruction::ExtractElement:
225 case Instruction::InsertElement:
226 case Instruction::ShuffleVector:
227 case Instruction::ExtractValue:
228 case Instruction::InsertValue:
229 return TTI.getInstructionCost(U: I, CostKind: TargetTransformInfo::TCK_SizeAndLatency);
230
231 default:
232 return InstructionCost::getInvalid(); // Disallow anything not explicitly
233 // listed.
234 }
235}
236
237// Do not hoist any debug info intrinsics.
238// ...
239// if (cond) {
240// x = y * z;
241// foo();
242// }
243// ...
244// -------- Which then becomes:
245// ...
246// if.then:
247// %x = mul i32 %y, %z
248// call void @llvm.dbg.value(%x, !"x", !DIExpression())
249// call void foo()
250//
251// SpeculativeExecution might decide to hoist the 'y * z' calculation
252// out of the 'if' block, because it is more efficient that way, so the
253// '%x = mul i32 %y, %z' moves to the block above. But it might also
254// decide to hoist the 'llvm.dbg.value' call.
255// This is incorrect, because even if we've moved the calculation of
256// 'y * z', we should not see the value of 'x' change unless we
257// actually go inside the 'if' block.
258
259bool SpeculativeExecutionPass::considerHoistingFromTo(
260 BasicBlock &FromBlock, BasicBlock &ToBlock) {
261 SmallPtrSet<const Instruction *, 8> NotHoisted;
262 auto HasNoUnhoistedInstr = [&NotHoisted](auto Values) {
263 for (const Value *V : Values) {
264 if (const auto *I = dyn_cast_or_null<Instruction>(Val: V))
265 if (NotHoisted.contains(Ptr: I))
266 return false;
267 }
268 return true;
269 };
270 auto AllPrecedingUsesFromBlockHoisted =
271 [&HasNoUnhoistedInstr](const User *U) {
272 return HasNoUnhoistedInstr(U->operand_values());
273 };
274
275 InstructionCost TotalSpeculationCost = 0;
276 unsigned NotHoistedInstCount = 0;
277 for (const auto &I : FromBlock) {
278 const InstructionCost Cost = ComputeSpeculationCost(I: &I, TTI: *TTI);
279 if (Cost.isValid() && isSafeToSpeculativelyExecute(I: &I) &&
280 AllPrecedingUsesFromBlockHoisted(&I)) {
281 TotalSpeculationCost += Cost;
282 if (TotalSpeculationCost > Opts->spec_exec_max_speculation_cost)
283 return false; // too much to hoist
284 } else {
285 NotHoistedInstCount++;
286 if (NotHoistedInstCount > Opts->spec_exec_max_not_hoisted)
287 return false; // too much left behind
288 NotHoisted.insert(Ptr: &I);
289 }
290 }
291
292 for (auto I = FromBlock.begin(); I != FromBlock.end();) {
293 // We have to increment I before moving Current as moving Current
294 // changes the list that I is iterating through.
295 auto Current = I;
296 ++I;
297 if (!NotHoisted.count(Ptr: &*Current)) {
298 Current->moveBefore(InsertPos: ToBlock.getTerminator()->getIterator());
299 Current->dropLocation();
300 }
301 }
302 return true;
303}
304
305FunctionPass *llvm::createSpeculativeExecutionPass() {
306 return new SpeculativeExecutionLegacyPass();
307}
308
309FunctionPass *llvm::createSpeculativeExecutionIfHasBranchDivergencePass() {
310 return new SpeculativeExecutionLegacyPass(/* OnlyIfDivergentTarget = */ true);
311}
312
313SpeculativeExecutionPass::SpeculativeExecutionPass(bool OnlyIfDivergentTarget)
314 : OnlyIfDivergentTarget(OnlyIfDivergentTarget) {}
315
316PreservedAnalyses SpeculativeExecutionPass::run(Function &F,
317 FunctionAnalysisManager &AM) {
318 auto *TTI = &AM.getResult<TargetIRAnalysis>(IR&: F);
319
320 bool Changed = runImpl(F, TTI);
321
322 if (!Changed)
323 return PreservedAnalyses::all();
324 PreservedAnalyses PA;
325 PA.preserveSet<CFGAnalyses>();
326 return PA;
327}
328
329void SpeculativeExecutionPass::printPipeline(
330 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
331 static_cast<PassInfoMixin<SpeculativeExecutionPass> *>(this)->printPipeline(
332 OS, MapClassName2PassName);
333 OS << '<';
334 if (OnlyIfDivergentTarget)
335 OS << "only-if-divergent-target";
336 OS << '>';
337}
338