1 //===- LowerExpectIntrinsic.cpp - Lower expect intrinsic ------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This pass lowers the 'expect' intrinsic to LLVM metadata.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/ADT/iterator_range.h"
17 #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"
25 #include "llvm/InitializePasses.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Transforms/Utils/MisExpect.h"
34 #define DEBUG_TYPE "lower-expect-intrinsic"
36 STATISTIC(ExpectIntrinsicsHandled,
37 "Number of 'expect' intrinsic instructions handled");
39 // These default values are chosen to represent an extremely skewed outcome for
40 // a condition, but they leave some room for interpretation by later passes.
42 // If the documentation for __builtin_expect() was made explicit that it should
43 // only be used in extreme cases, we could make this ratio higher. As it stands,
44 // programmers may be using __builtin_expect() / llvm.expect to annotate that a
45 // branch is likely or unlikely to be taken.
47 // There is a known dependency on this ratio in CodeGenPrepare when transforming
48 // 'select' instructions. It may be worthwhile to hoist these values to some
49 // shared space, so they can be used directly by other passes.
51 static cl::opt<uint32_t> LikelyBranchWeight(
52 "likely-branch-weight", cl::Hidden, cl::init(2000),
53 cl::desc("Weight of the branch likely to be taken (default = 2000)"));
54 static cl::opt<uint32_t> UnlikelyBranchWeight(
55 "unlikely-branch-weight", cl::Hidden, cl::init(1),
56 cl::desc("Weight of the branch unlikely to be taken (default = 1)"));
58 static std::tuple<uint32_t, uint32_t>
59 getBranchWeight(Intrinsic::ID IntrinsicID, CallInst *CI, int BranchCount) {
60 if (IntrinsicID == Intrinsic::expect) {
62 return std::make_tuple(LikelyBranchWeight.getValue(),
63 UnlikelyBranchWeight.getValue());
65 // __builtin_expect_with_probability
66 assert(CI->getNumOperands() >= 3 &&
67 "expect with probability must have 3 arguments");
68 ConstantFP *Confidence = dyn_cast<ConstantFP>(CI->getArgOperand(2));
69 double TrueProb = Confidence->getValueAPF().convertToDouble();
70 assert((TrueProb >= 0.0 && TrueProb <= 1.0) &&
71 "probability value must be in the range [0.0, 1.0]");
72 double FalseProb = (1.0 - TrueProb) / (BranchCount - 1);
73 uint32_t LikelyBW = ceil((TrueProb * (double)(INT32_MAX - 1)) + 1.0);
74 uint32_t UnlikelyBW = ceil((FalseProb * (double)(INT32_MAX - 1)) + 1.0);
75 return std::make_tuple(LikelyBW, UnlikelyBW);
79 static bool handleSwitchExpect(SwitchInst &SI) {
80 CallInst *CI = dyn_cast<CallInst>(SI.getCondition());
84 Function *Fn = CI->getCalledFunction();
85 if (!Fn || (Fn->getIntrinsicID() != Intrinsic::expect &&
86 Fn->getIntrinsicID() != Intrinsic::expect_with_probability))
89 Value *ArgValue = CI->getArgOperand(0);
90 ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
94 SwitchInst::CaseHandle Case = *SI.findCaseValue(ExpectedValue);
95 unsigned n = SI.getNumCases(); // +1 for default case.
96 uint32_t LikelyBranchWeightVal, UnlikelyBranchWeightVal;
97 std::tie(LikelyBranchWeightVal, UnlikelyBranchWeightVal) =
98 getBranchWeight(Fn->getIntrinsicID(), CI, n + 1);
100 SmallVector<uint32_t, 16> Weights(n + 1, UnlikelyBranchWeightVal);
102 uint64_t Index = (Case == *SI.case_default()) ? 0 : Case.getCaseIndex() + 1;
103 Weights[Index] = LikelyBranchWeightVal;
105 SI.setMetadata(LLVMContext::MD_misexpect,
106 MDBuilder(CI->getContext())
107 .createMisExpect(Index, LikelyBranchWeightVal,
108 UnlikelyBranchWeightVal));
110 SI.setCondition(ArgValue);
111 misexpect::checkFrontendInstrumentation(SI);
113 SI.setMetadata(LLVMContext::MD_prof,
114 MDBuilder(CI->getContext()).createBranchWeights(Weights));
119 /// Handler for PHINodes that define the value argument to an
120 /// @llvm.expect call.
122 /// If the operand of the phi has a constant value and it 'contradicts'
123 /// with the expected value of phi def, then the corresponding incoming
124 /// edge of the phi is unlikely to be taken. Using that information,
125 /// the branch probability info for the originating branch can be inferred.
126 static void handlePhiDef(CallInst *Expect) {
127 Value &Arg = *Expect->getArgOperand(0);
128 ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(Expect->getArgOperand(1));
131 const APInt &ExpectedPhiValue = ExpectedValue->getValue();
133 // Walk up in backward a list of instructions that
134 // have 'copy' semantics by 'stripping' the copies
135 // until a PHI node or an instruction of unknown kind
136 // is reached. Negation via xor is also handled.
141 // D = __builtin_expect(A, 0);
144 SmallVector<Instruction *, 4> Operations;
145 while (!isa<PHINode>(V)) {
146 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(V)) {
147 V = ZExt->getOperand(0);
148 Operations.push_back(ZExt);
152 if (SExtInst *SExt = dyn_cast<SExtInst>(V)) {
153 V = SExt->getOperand(0);
154 Operations.push_back(SExt);
158 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(V);
159 if (!BinOp || BinOp->getOpcode() != Instruction::Xor)
162 ConstantInt *CInt = dyn_cast<ConstantInt>(BinOp->getOperand(1));
166 V = BinOp->getOperand(0);
167 Operations.push_back(BinOp);
170 // Executes the recorded operations on input 'Value'.
171 auto ApplyOperations = [&](const APInt &Value) {
172 APInt Result = Value;
173 for (auto Op : llvm::reverse(Operations)) {
174 switch (Op->getOpcode()) {
175 case Instruction::Xor:
176 Result ^= cast<ConstantInt>(Op->getOperand(1))->getValue();
178 case Instruction::ZExt:
179 Result = Result.zext(Op->getType()->getIntegerBitWidth());
181 case Instruction::SExt:
182 Result = Result.sext(Op->getType()->getIntegerBitWidth());
185 llvm_unreachable("Unexpected operation");
191 auto *PhiDef = cast<PHINode>(V);
193 // Get the first dominating conditional branch of the operand
194 // i's incoming block.
195 auto GetDomConditional = [&](unsigned i) -> BranchInst * {
196 BasicBlock *BB = PhiDef->getIncomingBlock(i);
197 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
198 if (BI && BI->isConditional())
200 BB = BB->getSinglePredecessor();
203 BI = dyn_cast<BranchInst>(BB->getTerminator());
204 if (!BI || BI->isUnconditional())
209 // Now walk through all Phi operands to find phi oprerands with values
210 // conflicting with the expected phi output value. Any such operand
211 // indicates the incoming edge to that operand is unlikely.
212 for (unsigned i = 0, e = PhiDef->getNumIncomingValues(); i != e; ++i) {
214 Value *PhiOpnd = PhiDef->getIncomingValue(i);
215 ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd);
219 // Not an interesting case when IsUnlikely is false -- we can not infer
220 // anything useful when the operand value matches the expected phi
222 if (ExpectedPhiValue == ApplyOperations(CI->getValue()))
225 BranchInst *BI = GetDomConditional(i);
229 MDBuilder MDB(PhiDef->getContext());
231 // There are two situations in which an operand of the PhiDef comes
232 // from a given successor of a branch instruction BI.
233 // 1) When the incoming block of the operand is the successor block;
234 // 2) When the incoming block is BI's enclosing block and the
235 // successor is the PhiDef's enclosing block.
237 // Returns true if the operand which comes from OpndIncomingBB
238 // comes from outgoing edge of BI that leads to Succ block.
239 auto *OpndIncomingBB = PhiDef->getIncomingBlock(i);
240 auto IsOpndComingFromSuccessor = [&](BasicBlock *Succ) {
241 if (OpndIncomingBB == Succ)
242 // If this successor is the incoming block for this
243 // Phi operand, then this successor does lead to the Phi.
245 if (OpndIncomingBB == BI->getParent() && Succ == PhiDef->getParent())
246 // Otherwise, if the edge is directly from the branch
247 // to the Phi, this successor is the one feeding this
252 uint32_t LikelyBranchWeightVal, UnlikelyBranchWeightVal;
253 std::tie(LikelyBranchWeightVal, UnlikelyBranchWeightVal) = getBranchWeight(
254 Expect->getCalledFunction()->getIntrinsicID(), Expect, 2);
256 if (IsOpndComingFromSuccessor(BI->getSuccessor(1)))
257 BI->setMetadata(LLVMContext::MD_prof,
258 MDB.createBranchWeights(LikelyBranchWeightVal,
259 UnlikelyBranchWeightVal));
260 else if (IsOpndComingFromSuccessor(BI->getSuccessor(0)))
261 BI->setMetadata(LLVMContext::MD_prof,
262 MDB.createBranchWeights(UnlikelyBranchWeightVal,
263 LikelyBranchWeightVal));
267 // Handle both BranchInst and SelectInst.
268 template <class BrSelInst> static bool handleBrSelExpect(BrSelInst &BSI) {
270 // Handle non-optimized IR code like:
271 // %expval = call i64 @llvm.expect.i64(i64 %conv1, i64 1)
272 // %tobool = icmp ne i64 %expval, 0
273 // br i1 %tobool, label %if.then, label %if.end
275 // Or the following simpler case:
276 // %expval = call i1 @llvm.expect.i1(i1 %cmp, i1 1)
277 // br i1 %expval, label %if.then, label %if.end
281 ICmpInst *CmpI = dyn_cast<ICmpInst>(BSI.getCondition());
282 CmpInst::Predicate Predicate;
283 ConstantInt *CmpConstOperand = nullptr;
285 CI = dyn_cast<CallInst>(BSI.getCondition());
286 Predicate = CmpInst::ICMP_NE;
288 Predicate = CmpI->getPredicate();
289 if (Predicate != CmpInst::ICMP_NE && Predicate != CmpInst::ICMP_EQ)
292 CmpConstOperand = dyn_cast<ConstantInt>(CmpI->getOperand(1));
293 if (!CmpConstOperand)
295 CI = dyn_cast<CallInst>(CmpI->getOperand(0));
301 uint64_t ValueComparedTo = 0;
302 if (CmpConstOperand) {
303 if (CmpConstOperand->getBitWidth() > 64)
305 ValueComparedTo = CmpConstOperand->getZExtValue();
308 Function *Fn = CI->getCalledFunction();
309 if (!Fn || (Fn->getIntrinsicID() != Intrinsic::expect &&
310 Fn->getIntrinsicID() != Intrinsic::expect_with_probability))
313 Value *ArgValue = CI->getArgOperand(0);
314 ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
318 MDBuilder MDB(CI->getContext());
322 uint32_t LikelyBranchWeightVal, UnlikelyBranchWeightVal;
323 std::tie(LikelyBranchWeightVal, UnlikelyBranchWeightVal) =
324 getBranchWeight(Fn->getIntrinsicID(), CI, 2);
326 if ((ExpectedValue->getZExtValue() == ValueComparedTo) ==
327 (Predicate == CmpInst::ICMP_EQ)) {
329 MDB.createBranchWeights(LikelyBranchWeightVal, UnlikelyBranchWeightVal);
331 MDB.createMisExpect(0, LikelyBranchWeightVal, UnlikelyBranchWeightVal);
334 MDB.createBranchWeights(UnlikelyBranchWeightVal, LikelyBranchWeightVal);
336 MDB.createMisExpect(1, LikelyBranchWeightVal, UnlikelyBranchWeightVal);
339 BSI.setMetadata(LLVMContext::MD_misexpect, ExpNode);
342 CmpI->setOperand(0, ArgValue);
344 BSI.setCondition(ArgValue);
346 misexpect::checkFrontendInstrumentation(BSI);
348 BSI.setMetadata(LLVMContext::MD_prof, Node);
353 static bool handleBranchExpect(BranchInst &BI) {
354 if (BI.isUnconditional())
357 return handleBrSelExpect<BranchInst>(BI);
360 static bool lowerExpectIntrinsic(Function &F) {
361 bool Changed = false;
363 for (BasicBlock &BB : F) {
364 // Create "block_weights" metadata.
365 if (BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
366 if (handleBranchExpect(*BI))
367 ExpectIntrinsicsHandled++;
368 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
369 if (handleSwitchExpect(*SI))
370 ExpectIntrinsicsHandled++;
373 // Remove llvm.expect intrinsics. Iterate backwards in order
374 // to process select instructions before the intrinsic gets
376 for (auto BI = BB.rbegin(), BE = BB.rend(); BI != BE;) {
377 Instruction *Inst = &*BI++;
378 CallInst *CI = dyn_cast<CallInst>(Inst);
380 if (SelectInst *SI = dyn_cast<SelectInst>(Inst)) {
381 if (handleBrSelExpect(*SI))
382 ExpectIntrinsicsHandled++;
387 Function *Fn = CI->getCalledFunction();
388 if (Fn && (Fn->getIntrinsicID() == Intrinsic::expect ||
389 Fn->getIntrinsicID() == Intrinsic::expect_with_probability)) {
390 // Before erasing the llvm.expect, walk backward to find
391 // phi that define llvm.expect's first arg, and
392 // infer branch probability:
394 Value *Exp = CI->getArgOperand(0);
395 CI->replaceAllUsesWith(Exp);
396 CI->eraseFromParent();
405 PreservedAnalyses LowerExpectIntrinsicPass::run(Function &F,
406 FunctionAnalysisManager &) {
407 if (lowerExpectIntrinsic(F))
408 return PreservedAnalyses::none();
410 return PreservedAnalyses::all();
414 /// Legacy pass for lowering expect intrinsics out of the IR.
416 /// When this pass is run over a function it uses expect intrinsics which feed
417 /// branches and switches to provide branch weight metadata for those
418 /// terminators. It then removes the expect intrinsics from the IR so the rest
419 /// of the optimizer can ignore them.
420 class LowerExpectIntrinsic : public FunctionPass {
423 LowerExpectIntrinsic() : FunctionPass(ID) {
424 initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
427 bool runOnFunction(Function &F) override { return lowerExpectIntrinsic(F); }
431 char LowerExpectIntrinsic::ID = 0;
432 INITIALIZE_PASS(LowerExpectIntrinsic, "lower-expect",
433 "Lower 'expect' Intrinsics", false, false)
435 FunctionPass *llvm::createLowerExpectIntrinsicPass() {
436 return new LowerExpectIntrinsic();