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 
37*d2d2aa52SSanjay Patel // These default values are chosen to represent an extremely skewed outcome for
38*d2d2aa52SSanjay Patel // a condition, but they leave some room for interpretation by later passes.
39*d2d2aa52SSanjay Patel //
40*d2d2aa52SSanjay Patel // If the documentation for __builtin_expect() was made explicit that it should
41*d2d2aa52SSanjay Patel // only be used in extreme cases, we could make this ratio higher. As it stands,
42*d2d2aa52SSanjay Patel // programmers may be using __builtin_expect() / llvm.expect to annotate that a
43*d2d2aa52SSanjay Patel // branch is likely or unlikely to be taken.
44*d2d2aa52SSanjay Patel //
45*d2d2aa52SSanjay Patel // There is a known dependency on this ratio in CodeGenPrepare when transforming
46*d2d2aa52SSanjay Patel // 'select' instructions. It may be worthwhile to hoist these values to some
47*d2d2aa52SSanjay Patel // shared space, so they can be used directly by other passes.
48*d2d2aa52SSanjay Patel 
49*d2d2aa52SSanjay Patel static cl::opt<uint32_t> LikelyBranchWeight(
50*d2d2aa52SSanjay Patel     "likely-branch-weight", cl::Hidden, cl::init(2000),
51*d2d2aa52SSanjay Patel     cl::desc("Weight of the branch likely to be taken (default = 2000)"));
52*d2d2aa52SSanjay Patel static cl::opt<uint32_t> UnlikelyBranchWeight(
53*d2d2aa52SSanjay Patel     "unlikely-branch-weight", cl::Hidden, cl::init(1),
54*d2d2aa52SSanjay 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 
700012c778SChandler Carruth   SwitchInst::CaseIt 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 
743f5e7b1fSChandler 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 
860012c778SChandler Carruth static bool handleBranchExpect(BranchInst &BI) {
870012c778SChandler Carruth   if (BI.isUnconditional())
8872793727SChandler Carruth     return false;
8972793727SChandler Carruth 
9072793727SChandler Carruth   // Handle non-optimized IR code like:
9172793727SChandler Carruth   //   %expval = call i64 @llvm.expect.i64(i64 %conv1, i64 1)
9272793727SChandler Carruth   //   %tobool = icmp ne i64 %expval, 0
9372793727SChandler Carruth   //   br i1 %tobool, label %if.then, label %if.end
9472793727SChandler Carruth   //
9572793727SChandler Carruth   // Or the following simpler case:
9672793727SChandler Carruth   //   %expval = call i1 @llvm.expect.i1(i1 %cmp, i1 1)
9772793727SChandler Carruth   //   br i1 %expval, label %if.then, label %if.end
9872793727SChandler Carruth 
9972793727SChandler Carruth   CallInst *CI;
10072793727SChandler Carruth 
1010012c778SChandler Carruth   ICmpInst *CmpI = dyn_cast<ICmpInst>(BI.getCondition());
10272793727SChandler Carruth   if (!CmpI) {
1030012c778SChandler Carruth     CI = dyn_cast<CallInst>(BI.getCondition());
10472793727SChandler Carruth   } else {
10572793727SChandler Carruth     if (CmpI->getPredicate() != CmpInst::ICMP_NE)
10672793727SChandler Carruth       return false;
10772793727SChandler Carruth     CI = dyn_cast<CallInst>(CmpI->getOperand(0));
10872793727SChandler Carruth   }
10972793727SChandler Carruth 
11072793727SChandler Carruth   if (!CI)
11172793727SChandler Carruth     return false;
11272793727SChandler Carruth 
11372793727SChandler Carruth   Function *Fn = CI->getCalledFunction();
11472793727SChandler Carruth   if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
11572793727SChandler Carruth     return false;
11672793727SChandler Carruth 
11772793727SChandler Carruth   Value *ArgValue = CI->getArgOperand(0);
11872793727SChandler Carruth   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
11972793727SChandler Carruth   if (!ExpectedValue)
12072793727SChandler Carruth     return false;
12172793727SChandler Carruth 
12272793727SChandler Carruth   MDBuilder MDB(CI->getContext());
12372793727SChandler Carruth   MDNode *Node;
12472793727SChandler Carruth 
12572793727SChandler Carruth   // If expect value is equal to 1 it means that we are more likely to take
12672793727SChandler Carruth   // branch 0, in other case more likely is branch 1.
12772793727SChandler Carruth   if (ExpectedValue->isOne())
12872793727SChandler Carruth     Node = MDB.createBranchWeights(LikelyBranchWeight, UnlikelyBranchWeight);
12972793727SChandler Carruth   else
13072793727SChandler Carruth     Node = MDB.createBranchWeights(UnlikelyBranchWeight, LikelyBranchWeight);
13172793727SChandler Carruth 
1320012c778SChandler Carruth   BI.setMetadata(LLVMContext::MD_prof, Node);
13372793727SChandler Carruth 
13472793727SChandler Carruth   if (CmpI)
13572793727SChandler Carruth     CmpI->setOperand(0, ArgValue);
13672793727SChandler Carruth   else
1370012c778SChandler Carruth     BI.setCondition(ArgValue);
13872793727SChandler Carruth   return true;
13972793727SChandler Carruth }
14072793727SChandler Carruth 
14143e590e5SChandler Carruth static bool lowerExpectIntrinsic(Function &F) {
142c3bf5bd8SChandler Carruth   bool Changed = false;
143c3bf5bd8SChandler Carruth 
144d12741e0SChandler Carruth   for (BasicBlock &BB : F) {
14572793727SChandler Carruth     // Create "block_weights" metadata.
146d12741e0SChandler Carruth     if (BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
1470012c778SChandler Carruth       if (handleBranchExpect(*BI))
1486eb60eb5SChandler Carruth         ExpectIntrinsicsHandled++;
149d12741e0SChandler Carruth     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
1500012c778SChandler Carruth       if (handleSwitchExpect(*SI))
1516eb60eb5SChandler Carruth         ExpectIntrinsicsHandled++;
15272793727SChandler Carruth     }
15372793727SChandler Carruth 
1546b2765feSSanjay Patel     // Remove llvm.expect intrinsics.
155d12741e0SChandler Carruth     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
15672793727SChandler Carruth       CallInst *CI = dyn_cast<CallInst>(BI++);
15772793727SChandler Carruth       if (!CI)
15872793727SChandler Carruth         continue;
15972793727SChandler Carruth 
16072793727SChandler Carruth       Function *Fn = CI->getCalledFunction();
16172793727SChandler Carruth       if (Fn && Fn->getIntrinsicID() == Intrinsic::expect) {
16272793727SChandler Carruth         Value *Exp = CI->getArgOperand(0);
16372793727SChandler Carruth         CI->replaceAllUsesWith(Exp);
16472793727SChandler Carruth         CI->eraseFromParent();
165c3bf5bd8SChandler Carruth         Changed = true;
16672793727SChandler Carruth       }
16772793727SChandler Carruth     }
16872793727SChandler Carruth   }
16972793727SChandler Carruth 
170c3bf5bd8SChandler Carruth   return Changed;
17172793727SChandler Carruth }
17272793727SChandler Carruth 
17343e590e5SChandler Carruth PreservedAnalyses LowerExpectIntrinsicPass::run(Function &F) {
17443e590e5SChandler Carruth   if (lowerExpectIntrinsic(F))
17543e590e5SChandler Carruth     return PreservedAnalyses::none();
17643e590e5SChandler Carruth 
17743e590e5SChandler Carruth   return PreservedAnalyses::all();
17843e590e5SChandler Carruth }
17943e590e5SChandler Carruth 
18043e590e5SChandler Carruth namespace {
18143e590e5SChandler Carruth /// \brief Legacy pass for lowering expect intrinsics out of the IR.
18243e590e5SChandler Carruth ///
18343e590e5SChandler Carruth /// When this pass is run over a function it uses expect intrinsics which feed
18443e590e5SChandler Carruth /// branches and switches to provide branch weight metadata for those
18543e590e5SChandler Carruth /// terminators. It then removes the expect intrinsics from the IR so the rest
18643e590e5SChandler Carruth /// of the optimizer can ignore them.
18743e590e5SChandler Carruth class LowerExpectIntrinsic : public FunctionPass {
18843e590e5SChandler Carruth public:
18943e590e5SChandler Carruth   static char ID;
19043e590e5SChandler Carruth   LowerExpectIntrinsic() : FunctionPass(ID) {
19143e590e5SChandler Carruth     initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
19243e590e5SChandler Carruth   }
19343e590e5SChandler Carruth 
19443e590e5SChandler Carruth   bool runOnFunction(Function &F) override { return lowerExpectIntrinsic(F); }
19543e590e5SChandler Carruth };
196f00654e3SAlexander Kornienko }
19743e590e5SChandler Carruth 
19872793727SChandler Carruth char LowerExpectIntrinsic::ID = 0;
1990ea746bfSChandler Carruth INITIALIZE_PASS(LowerExpectIntrinsic, "lower-expect",
2000ea746bfSChandler Carruth                 "Lower 'expect' Intrinsics", false, false)
20172793727SChandler Carruth 
20272793727SChandler Carruth FunctionPass *llvm::createLowerExpectIntrinsicPass() {
20372793727SChandler Carruth   return new LowerExpectIntrinsic();
20472793727SChandler Carruth }
205