Taken into account Duncan's comments for r149481 dated by 2nd Feb 2012:
[oota-llvm.git] / lib / Transforms / Utils / LowerExpectIntrinsic.cpp
1 //===- LowerExpectIntrinsic.cpp - Lower expect intrinsic ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass lowers the 'expect' intrinsic to LLVM metadata.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "lower-expect-intrinsic"
15 #include "llvm/Constants.h"
16 #include "llvm/Function.h"
17 #include "llvm/BasicBlock.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/Metadata.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/ADT/Statistic.h"
27 #include <vector>
28
29 using namespace llvm;
30
31 STATISTIC(IfHandled, "Number of 'expect' intrinsic intructions handled");
32
33 static cl::opt<uint32_t>
34 LikelyBranchWeight("likely-branch-weight", cl::Hidden, cl::init(64),
35                    cl::desc("Weight of the branch likely to be taken (default = 64)"));
36 static cl::opt<uint32_t>
37 UnlikelyBranchWeight("unlikely-branch-weight", cl::Hidden, cl::init(4),
38                    cl::desc("Weight of the branch unlikely to be taken (default = 4)"));
39
40 namespace {
41
42   class LowerExpectIntrinsic : public FunctionPass {
43
44     bool HandleSwitchExpect(SwitchInst *SI);
45
46     bool HandleIfExpect(BranchInst *BI);
47
48   public:
49     static char ID;
50     LowerExpectIntrinsic() : FunctionPass(ID) {
51       initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
52     }
53
54     bool runOnFunction(Function &F);
55   };
56 }
57
58
59 bool LowerExpectIntrinsic::HandleSwitchExpect(SwitchInst *SI) {
60   CallInst *CI = dyn_cast<CallInst>(SI->getCondition());
61   if (!CI)
62     return false;
63
64   Function *Fn = CI->getCalledFunction();
65   if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
66     return false;
67
68   Value *ArgValue = CI->getArgOperand(0);
69   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
70   if (!ExpectedValue)
71     return false;
72
73   LLVMContext &Context = CI->getContext();
74   Type *Int32Ty = Type::getInt32Ty(Context);
75
76   SwitchInst::CaseIt Case = SI->findCaseValue(ExpectedValue);
77   std::vector<Value *> Vec;
78   unsigned n = SI->getNumCases();
79   Vec.resize(n + 1 + 1); // +1 for MDString and +1 for default case
80
81   Vec[0] = MDString::get(Context, "branch_weights");
82   Vec[1] = ConstantInt::get(Int32Ty, Case == SI->caseDefault() ?
83                             LikelyBranchWeight : UnlikelyBranchWeight);
84   for (unsigned i = 0; i < n; ++i) {
85     Vec[i + 1 + 1] = ConstantInt::get(Int32Ty, i == Case.getCaseIndex() ?
86         LikelyBranchWeight : UnlikelyBranchWeight);
87   }
88
89   MDNode *WeightsNode = llvm::MDNode::get(Context, Vec);
90   SI->setMetadata(LLVMContext::MD_prof, WeightsNode);
91
92   SI->setCondition(ArgValue);
93   return true;
94 }
95
96
97 bool LowerExpectIntrinsic::HandleIfExpect(BranchInst *BI) {
98   if (BI->isUnconditional())
99     return false;
100
101   // Handle non-optimized IR code like:
102   //   %expval = call i64 @llvm.expect.i64.i64(i64 %conv1, i64 1)
103   //   %tobool = icmp ne i64 %expval, 0
104   //   br i1 %tobool, label %if.then, label %if.end
105
106   ICmpInst *CmpI = dyn_cast<ICmpInst>(BI->getCondition());
107   if (!CmpI || CmpI->getPredicate() != CmpInst::ICMP_NE)
108     return false;
109
110   CallInst *CI = dyn_cast<CallInst>(CmpI->getOperand(0));
111   if (!CI)
112     return false;
113
114   Function *Fn = CI->getCalledFunction();
115   if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
116     return false;
117
118   Value *ArgValue = CI->getArgOperand(0);
119   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
120   if (!ExpectedValue)
121     return false;
122
123   LLVMContext &Context = CI->getContext();
124   Type *Int32Ty = Type::getInt32Ty(Context);
125   bool Likely = ExpectedValue->isOne();
126
127   // If expect value is equal to 1 it means that we are more likely to take
128   // branch 0, in other case more likely is branch 1.
129   Value *Ops[] = {
130     MDString::get(Context, "branch_weights"),
131     ConstantInt::get(Int32Ty, Likely ? LikelyBranchWeight : UnlikelyBranchWeight),
132     ConstantInt::get(Int32Ty, Likely ? UnlikelyBranchWeight : LikelyBranchWeight)
133   };
134
135   MDNode *WeightsNode = MDNode::get(Context, Ops);
136   BI->setMetadata(LLVMContext::MD_prof, WeightsNode);
137
138   CmpI->setOperand(0, ArgValue);
139   return true;
140 }
141
142
143 bool LowerExpectIntrinsic::runOnFunction(Function &F) {
144   for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
145     BasicBlock *BB = I++;
146
147     // Create "block_weights" metadata.
148     if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
149       if (HandleIfExpect(BI))
150         IfHandled++;
151     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
152       if (HandleSwitchExpect(SI))
153         IfHandled++;
154     }
155
156     // remove llvm.expect intrinsics.
157     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
158          BI != BE; ) {
159       CallInst *CI = dyn_cast<CallInst>(BI++);
160       if (!CI)
161         continue;
162
163       Function *Fn = CI->getCalledFunction();
164       if (Fn && Fn->getIntrinsicID() == Intrinsic::expect) {
165         Value *Exp = CI->getArgOperand(0);
166         CI->replaceAllUsesWith(Exp);
167         CI->eraseFromParent();
168       }
169     }
170   }
171
172   return false;
173 }
174
175
176 char LowerExpectIntrinsic::ID = 0;
177 INITIALIZE_PASS(LowerExpectIntrinsic, "lower-expect", "Lower 'expect' "
178                 "Intrinsics", false, false)
179
180 FunctionPass *llvm::createLowerExpectIntrinsicPass() {
181   return new LowerExpectIntrinsic();
182 }