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/Pass.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/Transforms/Utils/MisExpect.h"
33 #define DEBUG_TYPE "lower-expect-intrinsic"
35 STATISTIC(ExpectIntrinsicsHandled
,
36 "Number of 'expect' intrinsic instructions handled");
38 // 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.
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.
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.
50 static 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)"));
53 static 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)"));
57 static bool handleSwitchExpect(SwitchInst
&SI
) {
58 CallInst
*CI
= dyn_cast
<CallInst
>(SI
.getCondition());
62 Function
*Fn
= CI
->getCalledFunction();
63 if (!Fn
|| Fn
->getIntrinsicID() != Intrinsic::expect
)
66 Value
*ArgValue
= CI
->getArgOperand(0);
67 ConstantInt
*ExpectedValue
= dyn_cast
<ConstantInt
>(CI
->getArgOperand(1));
71 SwitchInst::CaseHandle Case
= *SI
.findCaseValue(ExpectedValue
);
72 unsigned n
= SI
.getNumCases(); // +1 for default case.
73 SmallVector
<uint32_t, 16> Weights(n
+ 1, UnlikelyBranchWeight
);
75 uint64_t Index
= (Case
== *SI
.case_default()) ? 0 : Case
.getCaseIndex() + 1;
76 Weights
[Index
] = LikelyBranchWeight
;
79 LLVMContext::MD_misexpect
,
80 MDBuilder(CI
->getContext())
81 .createMisExpect(Index
, LikelyBranchWeight
, UnlikelyBranchWeight
));
83 SI
.setCondition(ArgValue
);
84 misexpect::checkFrontendInstrumentation(SI
);
86 SI
.setMetadata(LLVMContext::MD_prof
,
87 MDBuilder(CI
->getContext()).createBranchWeights(Weights
));
92 /// Handler for PHINodes that define the value argument to an
93 /// @llvm.expect call.
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.
99 static void handlePhiDef(CallInst
*Expect
) {
100 Value
&Arg
= *Expect
->getArgOperand(0);
101 ConstantInt
*ExpectedValue
= dyn_cast
<ConstantInt
>(Expect
->getArgOperand(1));
104 const APInt
&ExpectedPhiValue
= ExpectedValue
->getValue();
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.
114 // D = __builtin_expect(A, 0);
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
);
125 if (SExtInst
*SExt
= dyn_cast
<SExtInst
>(V
)) {
126 V
= SExt
->getOperand(0);
127 Operations
.push_back(SExt
);
131 BinaryOperator
*BinOp
= dyn_cast
<BinaryOperator
>(V
);
132 if (!BinOp
|| BinOp
->getOpcode() != Instruction::Xor
)
135 ConstantInt
*CInt
= dyn_cast
<ConstantInt
>(BinOp
->getOperand(1));
139 V
= BinOp
->getOperand(0);
140 Operations
.push_back(BinOp
);
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();
151 case Instruction::ZExt
:
152 Result
= Result
.zext(Op
->getType()->getIntegerBitWidth());
154 case Instruction::SExt
:
155 Result
= Result
.sext(Op
->getType()->getIntegerBitWidth());
158 llvm_unreachable("Unexpected operation");
164 auto *PhiDef
= cast
<PHINode
>(V
);
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())
173 BB
= BB
->getSinglePredecessor();
176 BI
= dyn_cast
<BranchInst
>(BB
->getTerminator());
177 if (!BI
|| BI
->isUnconditional())
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
) {
187 Value
*PhiOpnd
= PhiDef
->getIncomingValue(i
);
188 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(PhiOpnd
);
192 // Not an interesting case when IsUnlikely is false -- we can not infer
193 // anything useful when the operand value matches the expected phi
195 if (ExpectedPhiValue
== ApplyOperations(CI
->getValue()))
198 BranchInst
*BI
= GetDomConditional(i
);
202 MDBuilder
MDB(PhiDef
->getContext());
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.
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.
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
226 if (IsOpndComingFromSuccessor(BI
->getSuccessor(1)))
228 LLVMContext::MD_prof
,
229 MDB
.createBranchWeights(LikelyBranchWeight
, UnlikelyBranchWeight
));
230 else if (IsOpndComingFromSuccessor(BI
->getSuccessor(0)))
232 LLVMContext::MD_prof
,
233 MDB
.createBranchWeights(UnlikelyBranchWeight
, LikelyBranchWeight
));
237 // Handle both BranchInst and SelectInst.
238 template <class BrSelInst
> static bool handleBrSelExpect(BrSelInst
&BSI
) {
240 // Handle non-optimized IR code like:
241 // %expval = call i64 @llvm.expect.i64(i64 %conv1, i64 1)
242 // %tobool = icmp ne i64 %expval, 0
243 // br i1 %tobool, label %if.then, label %if.end
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
251 ICmpInst
*CmpI
= dyn_cast
<ICmpInst
>(BSI
.getCondition());
252 CmpInst::Predicate Predicate
;
253 ConstantInt
*CmpConstOperand
= nullptr;
255 CI
= dyn_cast
<CallInst
>(BSI
.getCondition());
256 Predicate
= CmpInst::ICMP_NE
;
258 Predicate
= CmpI
->getPredicate();
259 if (Predicate
!= CmpInst::ICMP_NE
&& Predicate
!= CmpInst::ICMP_EQ
)
262 CmpConstOperand
= dyn_cast
<ConstantInt
>(CmpI
->getOperand(1));
263 if (!CmpConstOperand
)
265 CI
= dyn_cast
<CallInst
>(CmpI
->getOperand(0));
271 uint64_t ValueComparedTo
= 0;
272 if (CmpConstOperand
) {
273 if (CmpConstOperand
->getBitWidth() > 64)
275 ValueComparedTo
= CmpConstOperand
->getZExtValue();
278 Function
*Fn
= CI
->getCalledFunction();
279 if (!Fn
|| Fn
->getIntrinsicID() != Intrinsic::expect
)
282 Value
*ArgValue
= CI
->getArgOperand(0);
283 ConstantInt
*ExpectedValue
= dyn_cast
<ConstantInt
>(CI
->getArgOperand(1));
287 MDBuilder
MDB(CI
->getContext());
291 if ((ExpectedValue
->getZExtValue() == ValueComparedTo
) ==
292 (Predicate
== CmpInst::ICMP_EQ
)) {
293 Node
= MDB
.createBranchWeights(LikelyBranchWeight
, UnlikelyBranchWeight
);
294 ExpNode
= MDB
.createMisExpect(0, LikelyBranchWeight
, UnlikelyBranchWeight
);
296 Node
= MDB
.createBranchWeights(UnlikelyBranchWeight
, LikelyBranchWeight
);
297 ExpNode
= MDB
.createMisExpect(1, LikelyBranchWeight
, UnlikelyBranchWeight
);
300 BSI
.setMetadata(LLVMContext::MD_misexpect
, ExpNode
);
303 CmpI
->setOperand(0, ArgValue
);
305 BSI
.setCondition(ArgValue
);
307 misexpect::checkFrontendInstrumentation(BSI
);
309 BSI
.setMetadata(LLVMContext::MD_prof
, Node
);
314 static bool handleBranchExpect(BranchInst
&BI
) {
315 if (BI
.isUnconditional())
318 return handleBrSelExpect
<BranchInst
>(BI
);
321 static bool lowerExpectIntrinsic(Function
&F
) {
322 bool Changed
= false;
324 for (BasicBlock
&BB
: F
) {
325 // Create "block_weights" metadata.
326 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(BB
.getTerminator())) {
327 if (handleBranchExpect(*BI
))
328 ExpectIntrinsicsHandled
++;
329 } else if (SwitchInst
*SI
= dyn_cast
<SwitchInst
>(BB
.getTerminator())) {
330 if (handleSwitchExpect(*SI
))
331 ExpectIntrinsicsHandled
++;
334 // Remove llvm.expect intrinsics. Iterate backwards in order
335 // to process select instructions before the intrinsic gets
337 for (auto BI
= BB
.rbegin(), BE
= BB
.rend(); BI
!= BE
;) {
338 Instruction
*Inst
= &*BI
++;
339 CallInst
*CI
= dyn_cast
<CallInst
>(Inst
);
341 if (SelectInst
*SI
= dyn_cast
<SelectInst
>(Inst
)) {
342 if (handleBrSelExpect(*SI
))
343 ExpectIntrinsicsHandled
++;
348 Function
*Fn
= CI
->getCalledFunction();
349 if (Fn
&& Fn
->getIntrinsicID() == Intrinsic::expect
) {
350 // Before erasing the llvm.expect, walk backward to find
351 // phi that define llvm.expect's first arg, and
352 // infer branch probability:
354 Value
*Exp
= CI
->getArgOperand(0);
355 CI
->replaceAllUsesWith(Exp
);
356 CI
->eraseFromParent();
365 PreservedAnalyses
LowerExpectIntrinsicPass::run(Function
&F
,
366 FunctionAnalysisManager
&) {
367 if (lowerExpectIntrinsic(F
))
368 return PreservedAnalyses::none();
370 return PreservedAnalyses::all();
374 /// Legacy pass for lowering expect intrinsics out of the IR.
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.
380 class LowerExpectIntrinsic
: public FunctionPass
{
383 LowerExpectIntrinsic() : FunctionPass(ID
) {
384 initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
387 bool runOnFunction(Function
&F
) override
{ return lowerExpectIntrinsic(F
); }
391 char LowerExpectIntrinsic::ID
= 0;
392 INITIALIZE_PASS(LowerExpectIntrinsic
, "lower-expect",
393 "Lower 'expect' Intrinsics", false, false)
395 FunctionPass
*llvm::createLowerExpectIntrinsicPass() {
396 return new LowerExpectIntrinsic();