172793727SChandler Carruth //===- LowerExpectIntrinsic.cpp - Lower expect intrinsic ------------------===//
272793727SChandler Carruth //
372793727SChandler Carruth //                     The LLVM Compiler Infrastructure
472793727SChandler Carruth //
572793727SChandler Carruth // This file is distributed under the University of Illinois Open Source
672793727SChandler Carruth // License. See LICENSE.TXT for details.
772793727SChandler Carruth //
872793727SChandler Carruth //===----------------------------------------------------------------------===//
972793727SChandler Carruth //
1072793727SChandler Carruth // This pass lowers the 'expect' intrinsic to LLVM metadata.
1172793727SChandler Carruth //
1272793727SChandler Carruth //===----------------------------------------------------------------------===//
1372793727SChandler Carruth 
1443e590e5SChandler Carruth #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
153f5e7b1fSChandler Carruth #include "llvm/ADT/SmallVector.h"
1672793727SChandler Carruth #include "llvm/ADT/Statistic.h"
1772793727SChandler Carruth #include "llvm/IR/BasicBlock.h"
1872793727SChandler Carruth #include "llvm/IR/Constants.h"
1972793727SChandler Carruth #include "llvm/IR/Function.h"
2072793727SChandler Carruth #include "llvm/IR/Instructions.h"
2172793727SChandler Carruth #include "llvm/IR/Intrinsics.h"
2272793727SChandler Carruth #include "llvm/IR/LLVMContext.h"
2372793727SChandler Carruth #include "llvm/IR/MDBuilder.h"
2472793727SChandler Carruth #include "llvm/IR/Metadata.h"
2572793727SChandler Carruth #include "llvm/Pass.h"
2672793727SChandler Carruth #include "llvm/Support/CommandLine.h"
2772793727SChandler Carruth #include "llvm/Support/Debug.h"
2843e590e5SChandler Carruth #include "llvm/Transforms/Scalar.h"
2972793727SChandler Carruth 
3072793727SChandler Carruth using namespace llvm;
3172793727SChandler Carruth 
3272793727SChandler Carruth #define DEBUG_TYPE "lower-expect-intrinsic"
3372793727SChandler Carruth 
346eb60eb5SChandler Carruth STATISTIC(ExpectIntrinsicsHandled,
356eb60eb5SChandler Carruth           "Number of 'expect' intrinsic instructions handled");
3672793727SChandler Carruth 
37d2d2aa52SSanjay Patel // These default values are chosen to represent an extremely skewed outcome for
38d2d2aa52SSanjay Patel // a condition, but they leave some room for interpretation by later passes.
39d2d2aa52SSanjay Patel //
40d2d2aa52SSanjay Patel // If the documentation for __builtin_expect() was made explicit that it should
41d2d2aa52SSanjay Patel // only be used in extreme cases, we could make this ratio higher. As it stands,
42d2d2aa52SSanjay Patel // programmers may be using __builtin_expect() / llvm.expect to annotate that a
43d2d2aa52SSanjay Patel // branch is likely or unlikely to be taken.
44d2d2aa52SSanjay Patel //
45d2d2aa52SSanjay Patel // There is a known dependency on this ratio in CodeGenPrepare when transforming
46d2d2aa52SSanjay Patel // 'select' instructions. It may be worthwhile to hoist these values to some
47d2d2aa52SSanjay Patel // shared space, so they can be used directly by other passes.
48d2d2aa52SSanjay Patel 
49d2d2aa52SSanjay Patel static cl::opt<uint32_t> LikelyBranchWeight(
50d2d2aa52SSanjay Patel     "likely-branch-weight", cl::Hidden, cl::init(2000),
51d2d2aa52SSanjay Patel     cl::desc("Weight of the branch likely to be taken (default = 2000)"));
52d2d2aa52SSanjay Patel static cl::opt<uint32_t> UnlikelyBranchWeight(
53d2d2aa52SSanjay Patel     "unlikely-branch-weight", cl::Hidden, cl::init(1),
54d2d2aa52SSanjay Patel     cl::desc("Weight of the branch unlikely to be taken (default = 1)"));
5572793727SChandler Carruth 
560012c778SChandler Carruth static bool handleSwitchExpect(SwitchInst &SI) {
570012c778SChandler Carruth   CallInst *CI = dyn_cast<CallInst>(SI.getCondition());
5872793727SChandler Carruth   if (!CI)
5972793727SChandler Carruth     return false;
6072793727SChandler Carruth 
6172793727SChandler Carruth   Function *Fn = CI->getCalledFunction();
6272793727SChandler Carruth   if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
6372793727SChandler Carruth     return false;
6472793727SChandler Carruth 
6572793727SChandler Carruth   Value *ArgValue = CI->getArgOperand(0);
6672793727SChandler Carruth   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
6772793727SChandler Carruth   if (!ExpectedValue)
6872793727SChandler Carruth     return false;
6972793727SChandler Carruth 
70927d8e61SChandler Carruth   SwitchInst::CaseHandle Case = *SI.findCaseValue(ExpectedValue);
710012c778SChandler Carruth   unsigned n = SI.getNumCases(); // +1 for default case.
723f5e7b1fSChandler Carruth   SmallVector<uint32_t, 16> Weights(n + 1, UnlikelyBranchWeight);
7372793727SChandler Carruth 
74927d8e61SChandler Carruth   if (Case == *SI.case_default())
753f5e7b1fSChandler Carruth     Weights[0] = LikelyBranchWeight;
763f5e7b1fSChandler Carruth   else
773f5e7b1fSChandler Carruth     Weights[Case.getCaseIndex() + 1] = LikelyBranchWeight;
7872793727SChandler Carruth 
790012c778SChandler Carruth   SI.setMetadata(LLVMContext::MD_prof,
8072793727SChandler Carruth                  MDBuilder(CI->getContext()).createBranchWeights(Weights));
8172793727SChandler Carruth 
820012c778SChandler Carruth   SI.setCondition(ArgValue);
8372793727SChandler Carruth   return true;
8472793727SChandler Carruth }
8572793727SChandler Carruth 
8640afd5c9SXinliang David Li // Handle both BranchInst and SelectInst.
8740afd5c9SXinliang David Li template <class BrSelInst> static bool handleBrSelExpect(BrSelInst &BSI) {
8872793727SChandler Carruth 
8972793727SChandler Carruth   // Handle non-optimized IR code like:
9072793727SChandler Carruth   //   %expval = call i64 @llvm.expect.i64(i64 %conv1, i64 1)
9172793727SChandler Carruth   //   %tobool = icmp ne i64 %expval, 0
9272793727SChandler Carruth   //   br i1 %tobool, label %if.then, label %if.end
9372793727SChandler Carruth   //
9472793727SChandler Carruth   // Or the following simpler case:
9572793727SChandler Carruth   //   %expval = call i1 @llvm.expect.i1(i1 %cmp, i1 1)
9672793727SChandler Carruth   //   br i1 %expval, label %if.then, label %if.end
9772793727SChandler Carruth 
9872793727SChandler Carruth   CallInst *CI;
9972793727SChandler Carruth 
10040afd5c9SXinliang David Li   ICmpInst *CmpI = dyn_cast<ICmpInst>(BSI.getCondition());
101ee8d6acbSXinliang David Li   CmpInst::Predicate Predicate;
102*d6cfba2aSXinliang David Li   ConstantInt *CmpConstOperand = nullptr;
10372793727SChandler Carruth   if (!CmpI) {
10440afd5c9SXinliang David Li     CI = dyn_cast<CallInst>(BSI.getCondition());
105ee8d6acbSXinliang David Li     Predicate = CmpInst::ICMP_NE;
10672793727SChandler Carruth   } else {
107ee8d6acbSXinliang David Li     Predicate = CmpI->getPredicate();
108ee8d6acbSXinliang David Li     if (Predicate != CmpInst::ICMP_NE && Predicate != CmpInst::ICMP_EQ)
10972793727SChandler Carruth       return false;
110*d6cfba2aSXinliang David Li 
111*d6cfba2aSXinliang David Li     CmpConstOperand = dyn_cast<ConstantInt>(CmpI->getOperand(1));
112ee8d6acbSXinliang David Li     if (!CmpConstOperand)
113ee8d6acbSXinliang David Li       return false;
11472793727SChandler Carruth     CI = dyn_cast<CallInst>(CmpI->getOperand(0));
11572793727SChandler Carruth   }
11672793727SChandler Carruth 
11772793727SChandler Carruth   if (!CI)
11872793727SChandler Carruth     return false;
11972793727SChandler Carruth 
120*d6cfba2aSXinliang David Li   uint64_t ValueComparedTo = 0;
121*d6cfba2aSXinliang David Li   if (CmpConstOperand) {
122*d6cfba2aSXinliang David Li     if (CmpConstOperand->getBitWidth() > 64)
123*d6cfba2aSXinliang David Li       return false;
124*d6cfba2aSXinliang David Li     ValueComparedTo = CmpConstOperand->getZExtValue();
125*d6cfba2aSXinliang David Li   }
126*d6cfba2aSXinliang David Li 
12772793727SChandler Carruth   Function *Fn = CI->getCalledFunction();
12872793727SChandler Carruth   if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
12972793727SChandler Carruth     return false;
13072793727SChandler Carruth 
13172793727SChandler Carruth   Value *ArgValue = CI->getArgOperand(0);
13272793727SChandler Carruth   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
13372793727SChandler Carruth   if (!ExpectedValue)
13472793727SChandler Carruth     return false;
13572793727SChandler Carruth 
13672793727SChandler Carruth   MDBuilder MDB(CI->getContext());
13772793727SChandler Carruth   MDNode *Node;
13872793727SChandler Carruth 
139ee8d6acbSXinliang David Li   if ((ExpectedValue->getZExtValue() == ValueComparedTo) ==
140ee8d6acbSXinliang David Li       (Predicate == CmpInst::ICMP_EQ))
14172793727SChandler Carruth     Node = MDB.createBranchWeights(LikelyBranchWeight, UnlikelyBranchWeight);
14272793727SChandler Carruth   else
14372793727SChandler Carruth     Node = MDB.createBranchWeights(UnlikelyBranchWeight, LikelyBranchWeight);
14472793727SChandler Carruth 
14540afd5c9SXinliang David Li   BSI.setMetadata(LLVMContext::MD_prof, Node);
14672793727SChandler Carruth 
14772793727SChandler Carruth   if (CmpI)
14872793727SChandler Carruth     CmpI->setOperand(0, ArgValue);
14972793727SChandler Carruth   else
15040afd5c9SXinliang David Li     BSI.setCondition(ArgValue);
15172793727SChandler Carruth   return true;
15272793727SChandler Carruth }
15372793727SChandler Carruth 
15440afd5c9SXinliang David Li static bool handleBranchExpect(BranchInst &BI) {
15540afd5c9SXinliang David Li   if (BI.isUnconditional())
15640afd5c9SXinliang David Li     return false;
15740afd5c9SXinliang David Li 
15840afd5c9SXinliang David Li   return handleBrSelExpect<BranchInst>(BI);
15940afd5c9SXinliang David Li }
16040afd5c9SXinliang David Li 
16143e590e5SChandler Carruth static bool lowerExpectIntrinsic(Function &F) {
162c3bf5bd8SChandler Carruth   bool Changed = false;
163c3bf5bd8SChandler Carruth 
164d12741e0SChandler Carruth   for (BasicBlock &BB : F) {
16572793727SChandler Carruth     // Create "block_weights" metadata.
166d12741e0SChandler Carruth     if (BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
1670012c778SChandler Carruth       if (handleBranchExpect(*BI))
1686eb60eb5SChandler Carruth         ExpectIntrinsicsHandled++;
169d12741e0SChandler Carruth     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
1700012c778SChandler Carruth       if (handleSwitchExpect(*SI))
1716eb60eb5SChandler Carruth         ExpectIntrinsicsHandled++;
17272793727SChandler Carruth     }
17372793727SChandler Carruth 
17440afd5c9SXinliang David Li     // Remove llvm.expect intrinsics. Iterate backwards in order
17540afd5c9SXinliang David Li     // to process select instructions before the intrinsic gets
17640afd5c9SXinliang David Li     // removed.
17740afd5c9SXinliang David Li     for (auto BI = BB.rbegin(), BE = BB.rend(); BI != BE;) {
17840afd5c9SXinliang David Li       Instruction *Inst = &*BI++;
17940afd5c9SXinliang David Li       CallInst *CI = dyn_cast<CallInst>(Inst);
18040afd5c9SXinliang David Li       if (!CI) {
18140afd5c9SXinliang David Li         if (SelectInst *SI = dyn_cast<SelectInst>(Inst)) {
18240afd5c9SXinliang David Li           if (handleBrSelExpect(*SI))
18340afd5c9SXinliang David Li             ExpectIntrinsicsHandled++;
18440afd5c9SXinliang David Li         }
18572793727SChandler Carruth         continue;
18640afd5c9SXinliang David Li       }
18772793727SChandler Carruth 
18872793727SChandler Carruth       Function *Fn = CI->getCalledFunction();
18972793727SChandler Carruth       if (Fn && Fn->getIntrinsicID() == Intrinsic::expect) {
19072793727SChandler Carruth         Value *Exp = CI->getArgOperand(0);
19172793727SChandler Carruth         CI->replaceAllUsesWith(Exp);
19272793727SChandler Carruth         CI->eraseFromParent();
193c3bf5bd8SChandler Carruth         Changed = true;
19472793727SChandler Carruth       }
19572793727SChandler Carruth     }
19672793727SChandler Carruth   }
19772793727SChandler Carruth 
198c3bf5bd8SChandler Carruth   return Changed;
19972793727SChandler Carruth }
20072793727SChandler Carruth 
201164a2aa6SChandler Carruth PreservedAnalyses LowerExpectIntrinsicPass::run(Function &F,
202164a2aa6SChandler Carruth                                                 FunctionAnalysisManager &) {
20343e590e5SChandler Carruth   if (lowerExpectIntrinsic(F))
20443e590e5SChandler Carruth     return PreservedAnalyses::none();
20543e590e5SChandler Carruth 
20643e590e5SChandler Carruth   return PreservedAnalyses::all();
20743e590e5SChandler Carruth }
20843e590e5SChandler Carruth 
20943e590e5SChandler Carruth namespace {
21043e590e5SChandler Carruth /// \brief Legacy pass for lowering expect intrinsics out of the IR.
21143e590e5SChandler Carruth ///
21243e590e5SChandler Carruth /// When this pass is run over a function it uses expect intrinsics which feed
21343e590e5SChandler Carruth /// branches and switches to provide branch weight metadata for those
21443e590e5SChandler Carruth /// terminators. It then removes the expect intrinsics from the IR so the rest
21543e590e5SChandler Carruth /// of the optimizer can ignore them.
21643e590e5SChandler Carruth class LowerExpectIntrinsic : public FunctionPass {
21743e590e5SChandler Carruth public:
21843e590e5SChandler Carruth   static char ID;
21943e590e5SChandler Carruth   LowerExpectIntrinsic() : FunctionPass(ID) {
22043e590e5SChandler Carruth     initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
22143e590e5SChandler Carruth   }
22243e590e5SChandler Carruth 
22343e590e5SChandler Carruth   bool runOnFunction(Function &F) override { return lowerExpectIntrinsic(F); }
22443e590e5SChandler Carruth };
225f00654e3SAlexander Kornienko }
22643e590e5SChandler Carruth 
22772793727SChandler Carruth char LowerExpectIntrinsic::ID = 0;
2280ea746bfSChandler Carruth INITIALIZE_PASS(LowerExpectIntrinsic, "lower-expect",
2290ea746bfSChandler Carruth                 "Lower 'expect' Intrinsics", false, false)
23072793727SChandler Carruth 
23172793727SChandler Carruth FunctionPass *llvm::createLowerExpectIntrinsicPass() {
23272793727SChandler Carruth   return new LowerExpectIntrinsic();
23372793727SChandler Carruth }
234