blob: d85f20b3f80c101bdb8ce3192a60d5203a989ae0 [file] [log] [blame]
Chandler Carruth47e1db12011-10-16 22:15:07 +00001//===- LowerExpectIntrinsic.cpp - Lower expect intrinsic ------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chandler Carruth47e1db12011-10-16 22:15:07 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass lowers the 'expect' intrinsic to LLVM metadata.
10//
11//===----------------------------------------------------------------------===//
12
Chandler Carruth43e590e2015-01-24 11:13:02 +000013#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Chandler Carruth3f5e7b12015-01-24 10:47:13 +000014#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/Statistic.h"
Xinliang David Li621e8dc2017-06-02 02:09:31 +000016#include "llvm/ADT/iterator_range.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/BasicBlock.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/Function.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/LLVMContext.h"
23#include "llvm/IR/MDBuilder.h"
24#include "llvm/IR/Metadata.h"
Jakub Staszak3f158fd2011-07-06 18:22:43 +000025#include "llvm/Pass.h"
Jakub Staszak3f158fd2011-07-06 18:22:43 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +000028#include "llvm/Transforms/Scalar.h"
Petr Hosek7bdad082019-09-11 16:19:50 +000029#include "llvm/Transforms/Utils/MisExpect.h"
Jakub Staszak3f158fd2011-07-06 18:22:43 +000030
31using namespace llvm;
32
Chandler Carruth964daaa2014-04-22 02:55:47 +000033#define DEBUG_TYPE "lower-expect-intrinsic"
34
Chandler Carruth6eb60eb2015-01-24 10:57:25 +000035STATISTIC(ExpectIntrinsicsHandled,
36 "Number of 'expect' intrinsic instructions handled");
Jakub Staszak3f158fd2011-07-06 18:22:43 +000037
Sanjay Pateld2d2aa52016-04-26 22:23:38 +000038// These default values are chosen to represent an extremely skewed outcome for
39// a condition, but they leave some room for interpretation by later passes.
40//
41// If the documentation for __builtin_expect() was made explicit that it should
42// only be used in extreme cases, we could make this ratio higher. As it stands,
43// programmers may be using __builtin_expect() / llvm.expect to annotate that a
44// branch is likely or unlikely to be taken.
45//
46// There is a known dependency on this ratio in CodeGenPrepare when transforming
47// 'select' instructions. It may be worthwhile to hoist these values to some
48// shared space, so they can be used directly by other passes.
49
50static cl::opt<uint32_t> LikelyBranchWeight(
51 "likely-branch-weight", cl::Hidden, cl::init(2000),
52 cl::desc("Weight of the branch likely to be taken (default = 2000)"));
53static cl::opt<uint32_t> UnlikelyBranchWeight(
54 "unlikely-branch-weight", cl::Hidden, cl::init(1),
55 cl::desc("Weight of the branch unlikely to be taken (default = 1)"));
Jakub Staszak3f158fd2011-07-06 18:22:43 +000056
Chandler Carruth0012c772015-01-24 10:39:24 +000057static bool handleSwitchExpect(SwitchInst &SI) {
58 CallInst *CI = dyn_cast<CallInst>(SI.getCondition());
Jakub Staszak3f158fd2011-07-06 18:22:43 +000059 if (!CI)
60 return false;
61
62 Function *Fn = CI->getCalledFunction();
63 if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
64 return false;
65
66 Value *ArgValue = CI->getArgOperand(0);
67 ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
68 if (!ExpectedValue)
69 return false;
70
Chandler Carruth927d8e62017-04-12 07:27:28 +000071 SwitchInst::CaseHandle Case = *SI.findCaseValue(ExpectedValue);
Chandler Carruth0012c772015-01-24 10:39:24 +000072 unsigned n = SI.getNumCases(); // +1 for default case.
Chandler Carruth3f5e7b12015-01-24 10:47:13 +000073 SmallVector<uint32_t, 16> Weights(n + 1, UnlikelyBranchWeight);
Jakub Staszak3f158fd2011-07-06 18:22:43 +000074
Petr Hosek7bdad082019-09-11 16:19:50 +000075 uint64_t Index = (Case == *SI.case_default()) ? 0 : Case.getCaseIndex() + 1;
76 Weights[Index] = LikelyBranchWeight;
77
78 SI.setMetadata(
79 LLVMContext::MD_misexpect,
80 MDBuilder(CI->getContext())
81 .createMisExpect(Index, LikelyBranchWeight, UnlikelyBranchWeight));
82
83 SI.setCondition(ArgValue);
84 misexpect::checkFrontendInstrumentation(SI);
Jakub Staszak3f158fd2011-07-06 18:22:43 +000085
Chandler Carruth0012c772015-01-24 10:39:24 +000086 SI.setMetadata(LLVMContext::MD_prof,
87 MDBuilder(CI->getContext()).createBranchWeights(Weights));
Jakub Staszak3f158fd2011-07-06 18:22:43 +000088
Jakub Staszak3f158fd2011-07-06 18:22:43 +000089 return true;
90}
91
Xinliang David Li621e8dc2017-06-02 02:09:31 +000092/// Handler for PHINodes that define the value argument to an
93/// @llvm.expect call.
94///
95/// If the operand of the phi has a constant value and it 'contradicts'
96/// with the expected value of phi def, then the corresponding incoming
97/// edge of the phi is unlikely to be taken. Using that information,
98/// the branch probability info for the originating branch can be inferred.
99static void handlePhiDef(CallInst *Expect) {
100 Value &Arg = *Expect->getArgOperand(0);
Xinliang David Li4f49bee2017-06-07 18:32:24 +0000101 ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(Expect->getArgOperand(1));
102 if (!ExpectedValue)
103 return;
Xinliang David Li621e8dc2017-06-02 02:09:31 +0000104 const APInt &ExpectedPhiValue = ExpectedValue->getValue();
105
106 // Walk up in backward a list of instructions that
107 // have 'copy' semantics by 'stripping' the copies
108 // until a PHI node or an instruction of unknown kind
109 // is reached. Negation via xor is also handled.
110 //
111 // C = PHI(...);
112 // B = C;
113 // A = B;
114 // D = __builtin_expect(A, 0);
115 //
116 Value *V = &Arg;
117 SmallVector<Instruction *, 4> Operations;
118 while (!isa<PHINode>(V)) {
119 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(V)) {
120 V = ZExt->getOperand(0);
121 Operations.push_back(ZExt);
122 continue;
123 }
124
125 if (SExtInst *SExt = dyn_cast<SExtInst>(V)) {
126 V = SExt->getOperand(0);
127 Operations.push_back(SExt);
128 continue;
129 }
130
131 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(V);
132 if (!BinOp || BinOp->getOpcode() != Instruction::Xor)
133 return;
134
135 ConstantInt *CInt = dyn_cast<ConstantInt>(BinOp->getOperand(1));
136 if (!CInt)
137 return;
138
139 V = BinOp->getOperand(0);
140 Operations.push_back(BinOp);
141 }
142
143 // Executes the recorded operations on input 'Value'.
144 auto ApplyOperations = [&](const APInt &Value) {
145 APInt Result = Value;
146 for (auto Op : llvm::reverse(Operations)) {
147 switch (Op->getOpcode()) {
148 case Instruction::Xor:
149 Result ^= cast<ConstantInt>(Op->getOperand(1))->getValue();
150 break;
151 case Instruction::ZExt:
152 Result = Result.zext(Op->getType()->getIntegerBitWidth());
153 break;
154 case Instruction::SExt:
155 Result = Result.sext(Op->getType()->getIntegerBitWidth());
156 break;
157 default:
158 llvm_unreachable("Unexpected operation");
159 }
160 }
161 return Result;
162 };
163
Simon Pilgrim91b40852019-10-02 16:03:45 +0000164 auto *PhiDef = cast<PHINode>(V);
Xinliang David Li621e8dc2017-06-02 02:09:31 +0000165
166 // Get the first dominating conditional branch of the operand
167 // i's incoming block.
168 auto GetDomConditional = [&](unsigned i) -> BranchInst * {
169 BasicBlock *BB = PhiDef->getIncomingBlock(i);
170 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
171 if (BI && BI->isConditional())
172 return BI;
173 BB = BB->getSinglePredecessor();
174 if (!BB)
175 return nullptr;
176 BI = dyn_cast<BranchInst>(BB->getTerminator());
177 if (!BI || BI->isUnconditional())
178 return nullptr;
179 return BI;
180 };
181
182 // Now walk through all Phi operands to find phi oprerands with values
183 // conflicting with the expected phi output value. Any such operand
184 // indicates the incoming edge to that operand is unlikely.
185 for (unsigned i = 0, e = PhiDef->getNumIncomingValues(); i != e; ++i) {
186
187 Value *PhiOpnd = PhiDef->getIncomingValue(i);
188 ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd);
189 if (!CI)
190 continue;
191
192 // Not an interesting case when IsUnlikely is false -- we can not infer
193 // anything useful when the operand value matches the expected phi
194 // output.
195 if (ExpectedPhiValue == ApplyOperations(CI->getValue()))
196 continue;
197
198 BranchInst *BI = GetDomConditional(i);
199 if (!BI)
200 continue;
201
202 MDBuilder MDB(PhiDef->getContext());
203
204 // There are two situations in which an operand of the PhiDef comes
205 // from a given successor of a branch instruction BI.
206 // 1) When the incoming block of the operand is the successor block;
207 // 2) When the incoming block is BI's enclosing block and the
208 // successor is the PhiDef's enclosing block.
209 //
210 // Returns true if the operand which comes from OpndIncomingBB
211 // comes from outgoing edge of BI that leads to Succ block.
212 auto *OpndIncomingBB = PhiDef->getIncomingBlock(i);
213 auto IsOpndComingFromSuccessor = [&](BasicBlock *Succ) {
214 if (OpndIncomingBB == Succ)
215 // If this successor is the incoming block for this
216 // Phi operand, then this successor does lead to the Phi.
217 return true;
218 if (OpndIncomingBB == BI->getParent() && Succ == PhiDef->getParent())
219 // Otherwise, if the edge is directly from the branch
220 // to the Phi, this successor is the one feeding this
221 // Phi operand.
222 return true;
223 return false;
224 };
225
226 if (IsOpndComingFromSuccessor(BI->getSuccessor(1)))
227 BI->setMetadata(
228 LLVMContext::MD_prof,
229 MDB.createBranchWeights(LikelyBranchWeight, UnlikelyBranchWeight));
230 else if (IsOpndComingFromSuccessor(BI->getSuccessor(0)))
231 BI->setMetadata(
232 LLVMContext::MD_prof,
233 MDB.createBranchWeights(UnlikelyBranchWeight, LikelyBranchWeight));
234 }
235}
236
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000237// Handle both BranchInst and SelectInst.
238template <class BrSelInst> static bool handleBrSelExpect(BrSelInst &BSI) {
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000239
240 // Handle non-optimized IR code like:
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000241 // %expval = call i64 @llvm.expect.i64(i64 %conv1, i64 1)
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000242 // %tobool = icmp ne i64 %expval, 0
243 // br i1 %tobool, label %if.then, label %if.end
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000244 //
245 // Or the following simpler case:
246 // %expval = call i1 @llvm.expect.i1(i1 %cmp, i1 1)
247 // br i1 %expval, label %if.then, label %if.end
248
249 CallInst *CI;
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000250
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000251 ICmpInst *CmpI = dyn_cast<ICmpInst>(BSI.getCondition());
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000252 CmpInst::Predicate Predicate;
Xinliang David Lid6cfba22017-06-01 23:05:11 +0000253 ConstantInt *CmpConstOperand = nullptr;
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000254 if (!CmpI) {
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000255 CI = dyn_cast<CallInst>(BSI.getCondition());
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000256 Predicate = CmpInst::ICMP_NE;
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000257 } else {
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000258 Predicate = CmpI->getPredicate();
259 if (Predicate != CmpInst::ICMP_NE && Predicate != CmpInst::ICMP_EQ)
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000260 return false;
Xinliang David Lid6cfba22017-06-01 23:05:11 +0000261
262 CmpConstOperand = dyn_cast<ConstantInt>(CmpI->getOperand(1));
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000263 if (!CmpConstOperand)
264 return false;
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000265 CI = dyn_cast<CallInst>(CmpI->getOperand(0));
266 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000267
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000268 if (!CI)
269 return false;
270
Xinliang David Lid6cfba22017-06-01 23:05:11 +0000271 uint64_t ValueComparedTo = 0;
272 if (CmpConstOperand) {
273 if (CmpConstOperand->getBitWidth() > 64)
274 return false;
275 ValueComparedTo = CmpConstOperand->getZExtValue();
276 }
277
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000278 Function *Fn = CI->getCalledFunction();
279 if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
280 return false;
281
282 Value *ArgValue = CI->getArgOperand(0);
283 ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
284 if (!ExpectedValue)
285 return false;
286
Benjamin Kramer65e75662012-05-26 13:59:43 +0000287 MDBuilder MDB(CI->getContext());
288 MDNode *Node;
Petr Hosek7bdad082019-09-11 16:19:50 +0000289 MDNode *ExpNode;
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000290
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000291 if ((ExpectedValue->getZExtValue() == ValueComparedTo) ==
Petr Hosek7bdad082019-09-11 16:19:50 +0000292 (Predicate == CmpInst::ICMP_EQ)) {
Benjamin Kramer65e75662012-05-26 13:59:43 +0000293 Node = MDB.createBranchWeights(LikelyBranchWeight, UnlikelyBranchWeight);
Petr Hosek7bdad082019-09-11 16:19:50 +0000294 ExpNode = MDB.createMisExpect(0, LikelyBranchWeight, UnlikelyBranchWeight);
295 } else {
Benjamin Kramer65e75662012-05-26 13:59:43 +0000296 Node = MDB.createBranchWeights(UnlikelyBranchWeight, LikelyBranchWeight);
Petr Hosek7bdad082019-09-11 16:19:50 +0000297 ExpNode = MDB.createMisExpect(1, LikelyBranchWeight, UnlikelyBranchWeight);
298 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000299
Petr Hosek7bdad082019-09-11 16:19:50 +0000300 BSI.setMetadata(LLVMContext::MD_misexpect, ExpNode);
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000301
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000302 if (CmpI)
303 CmpI->setOperand(0, ArgValue);
304 else
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000305 BSI.setCondition(ArgValue);
Petr Hosek7bdad082019-09-11 16:19:50 +0000306
307 misexpect::checkFrontendInstrumentation(BSI);
308
309 BSI.setMetadata(LLVMContext::MD_prof, Node);
310
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000311 return true;
312}
313
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000314static bool handleBranchExpect(BranchInst &BI) {
315 if (BI.isUnconditional())
316 return false;
317
318 return handleBrSelExpect<BranchInst>(BI);
319}
320
Chandler Carruth43e590e2015-01-24 11:13:02 +0000321static bool lowerExpectIntrinsic(Function &F) {
Chandler Carruthc3bf5bd2015-01-24 11:12:57 +0000322 bool Changed = false;
323
Chandler Carruthd12741e2015-01-24 10:57:19 +0000324 for (BasicBlock &BB : F) {
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000325 // Create "block_weights" metadata.
Chandler Carruthd12741e2015-01-24 10:57:19 +0000326 if (BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
Chandler Carruth0012c772015-01-24 10:39:24 +0000327 if (handleBranchExpect(*BI))
Chandler Carruth6eb60eb2015-01-24 10:57:25 +0000328 ExpectIntrinsicsHandled++;
Chandler Carruthd12741e2015-01-24 10:57:19 +0000329 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
Chandler Carruth0012c772015-01-24 10:39:24 +0000330 if (handleSwitchExpect(*SI))
Chandler Carruth6eb60eb2015-01-24 10:57:25 +0000331 ExpectIntrinsicsHandled++;
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000332 }
333
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000334 // Remove llvm.expect intrinsics. Iterate backwards in order
335 // to process select instructions before the intrinsic gets
336 // removed.
337 for (auto BI = BB.rbegin(), BE = BB.rend(); BI != BE;) {
338 Instruction *Inst = &*BI++;
339 CallInst *CI = dyn_cast<CallInst>(Inst);
340 if (!CI) {
341 if (SelectInst *SI = dyn_cast<SelectInst>(Inst)) {
342 if (handleBrSelExpect(*SI))
343 ExpectIntrinsicsHandled++;
344 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000345 continue;
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000346 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000347
348 Function *Fn = CI->getCalledFunction();
Jakub Staszaka11f7ec2011-07-06 23:50:16 +0000349 if (Fn && Fn->getIntrinsicID() == Intrinsic::expect) {
Xinliang David Li621e8dc2017-06-02 02:09:31 +0000350 // Before erasing the llvm.expect, walk backward to find
351 // phi that define llvm.expect's first arg, and
352 // infer branch probability:
353 handlePhiDef(CI);
Jakub Staszaka11f7ec2011-07-06 23:50:16 +0000354 Value *Exp = CI->getArgOperand(0);
355 CI->replaceAllUsesWith(Exp);
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000356 CI->eraseFromParent();
Chandler Carruthc3bf5bd2015-01-24 11:12:57 +0000357 Changed = true;
Jakub Staszaka11f7ec2011-07-06 23:50:16 +0000358 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000359 }
360 }
361
Chandler Carruthc3bf5bd2015-01-24 11:12:57 +0000362 return Changed;
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000363}
364
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000365PreservedAnalyses LowerExpectIntrinsicPass::run(Function &F,
366 FunctionAnalysisManager &) {
Chandler Carruth43e590e2015-01-24 11:13:02 +0000367 if (lowerExpectIntrinsic(F))
368 return PreservedAnalyses::none();
369
370 return PreservedAnalyses::all();
371}
372
373namespace {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000374/// Legacy pass for lowering expect intrinsics out of the IR.
Chandler Carruth43e590e2015-01-24 11:13:02 +0000375///
376/// When this pass is run over a function it uses expect intrinsics which feed
377/// branches and switches to provide branch weight metadata for those
378/// terminators. It then removes the expect intrinsics from the IR so the rest
379/// of the optimizer can ignore them.
380class LowerExpectIntrinsic : public FunctionPass {
381public:
382 static char ID;
383 LowerExpectIntrinsic() : FunctionPass(ID) {
384 initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
385 }
386
387 bool runOnFunction(Function &F) override { return lowerExpectIntrinsic(F); }
388};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000389}
Chandler Carruth43e590e2015-01-24 11:13:02 +0000390
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000391char LowerExpectIntrinsic::ID = 0;
Chandler Carruth0ea746b2015-01-24 10:30:14 +0000392INITIALIZE_PASS(LowerExpectIntrinsic, "lower-expect",
393 "Lower 'expect' Intrinsics", false, false)
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000394
395FunctionPass *llvm::createLowerExpectIntrinsicPass() {
396 return new LowerExpectIntrinsic();
397}