172793727SChandler Carruth //===- LowerExpectIntrinsic.cpp - Lower expect intrinsic ------------------===//
272793727SChandler Carruth //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
672793727SChandler Carruth //
772793727SChandler Carruth //===----------------------------------------------------------------------===//
872793727SChandler Carruth //
972793727SChandler Carruth // This pass lowers the 'expect' intrinsic to LLVM metadata.
1072793727SChandler Carruth //
1172793727SChandler Carruth //===----------------------------------------------------------------------===//
1272793727SChandler Carruth 
1343e590e5SChandler Carruth #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
143f5e7b1fSChandler Carruth #include "llvm/ADT/SmallVector.h"
1572793727SChandler Carruth #include "llvm/ADT/Statistic.h"
16621e8dcfSXinliang David Li #include "llvm/ADT/iterator_range.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"
297bdad084SPetr Hosek #include "llvm/Transforms/Utils/MisExpect.h"
3072793727SChandler Carruth 
3172793727SChandler Carruth using namespace llvm;
3272793727SChandler Carruth 
3372793727SChandler Carruth #define DEBUG_TYPE "lower-expect-intrinsic"
3472793727SChandler Carruth 
356eb60eb5SChandler Carruth STATISTIC(ExpectIntrinsicsHandled,
366eb60eb5SChandler Carruth           "Number of 'expect' intrinsic instructions handled");
3772793727SChandler Carruth 
38d2d2aa52SSanjay Patel // These default values are chosen to represent an extremely skewed outcome for
39d2d2aa52SSanjay Patel // a condition, but they leave some room for interpretation by later passes.
40d2d2aa52SSanjay Patel //
41d2d2aa52SSanjay Patel // If the documentation for __builtin_expect() was made explicit that it should
42d2d2aa52SSanjay Patel // only be used in extreme cases, we could make this ratio higher. As it stands,
43d2d2aa52SSanjay Patel // programmers may be using __builtin_expect() / llvm.expect to annotate that a
44d2d2aa52SSanjay Patel // branch is likely or unlikely to be taken.
45d2d2aa52SSanjay Patel //
46d2d2aa52SSanjay Patel // There is a known dependency on this ratio in CodeGenPrepare when transforming
47d2d2aa52SSanjay Patel // 'select' instructions. It may be worthwhile to hoist these values to some
48d2d2aa52SSanjay Patel // shared space, so they can be used directly by other passes.
49d2d2aa52SSanjay Patel 
50d2d2aa52SSanjay Patel static cl::opt<uint32_t> LikelyBranchWeight(
51d2d2aa52SSanjay Patel     "likely-branch-weight", cl::Hidden, cl::init(2000),
52d2d2aa52SSanjay Patel     cl::desc("Weight of the branch likely to be taken (default = 2000)"));
53d2d2aa52SSanjay Patel static cl::opt<uint32_t> UnlikelyBranchWeight(
54d2d2aa52SSanjay Patel     "unlikely-branch-weight", cl::Hidden, cl::init(1),
55d2d2aa52SSanjay Patel     cl::desc("Weight of the branch unlikely to be taken (default = 1)"));
5672793727SChandler Carruth 
570012c778SChandler Carruth static bool handleSwitchExpect(SwitchInst &SI) {
580012c778SChandler Carruth   CallInst *CI = dyn_cast<CallInst>(SI.getCondition());
5972793727SChandler Carruth   if (!CI)
6072793727SChandler Carruth     return false;
6172793727SChandler Carruth 
6272793727SChandler Carruth   Function *Fn = CI->getCalledFunction();
6372793727SChandler Carruth   if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
6472793727SChandler Carruth     return false;
6572793727SChandler Carruth 
6672793727SChandler Carruth   Value *ArgValue = CI->getArgOperand(0);
6772793727SChandler Carruth   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
6872793727SChandler Carruth   if (!ExpectedValue)
6972793727SChandler Carruth     return false;
7072793727SChandler Carruth 
71927d8e61SChandler Carruth   SwitchInst::CaseHandle Case = *SI.findCaseValue(ExpectedValue);
720012c778SChandler Carruth   unsigned n = SI.getNumCases(); // +1 for default case.
733f5e7b1fSChandler Carruth   SmallVector<uint32_t, 16> Weights(n + 1, UnlikelyBranchWeight);
7472793727SChandler Carruth 
757bdad084SPetr Hosek   uint64_t Index = (Case == *SI.case_default()) ? 0 : Case.getCaseIndex() + 1;
767bdad084SPetr Hosek   Weights[Index] = LikelyBranchWeight;
777bdad084SPetr Hosek 
787bdad084SPetr Hosek   SI.setMetadata(
797bdad084SPetr Hosek       LLVMContext::MD_misexpect,
807bdad084SPetr Hosek       MDBuilder(CI->getContext())
817bdad084SPetr Hosek           .createMisExpect(Index, LikelyBranchWeight, UnlikelyBranchWeight));
827bdad084SPetr Hosek 
837bdad084SPetr Hosek   SI.setCondition(ArgValue);
847bdad084SPetr Hosek   misexpect::checkFrontendInstrumentation(SI);
8572793727SChandler Carruth 
860012c778SChandler Carruth   SI.setMetadata(LLVMContext::MD_prof,
8772793727SChandler Carruth                  MDBuilder(CI->getContext()).createBranchWeights(Weights));
8872793727SChandler Carruth 
8972793727SChandler Carruth   return true;
9072793727SChandler Carruth }
9172793727SChandler Carruth 
92621e8dcfSXinliang David Li /// Handler for PHINodes that define the value argument to an
93621e8dcfSXinliang David Li /// @llvm.expect call.
94621e8dcfSXinliang David Li ///
95621e8dcfSXinliang David Li /// If the operand of the phi has a constant value and it 'contradicts'
96621e8dcfSXinliang David Li /// with the expected value of phi def, then the corresponding incoming
97621e8dcfSXinliang David Li /// edge of the phi is unlikely to be taken. Using that information,
98621e8dcfSXinliang David Li /// the branch probability info for the originating branch can be inferred.
99621e8dcfSXinliang David Li static void handlePhiDef(CallInst *Expect) {
100621e8dcfSXinliang David Li   Value &Arg = *Expect->getArgOperand(0);
1014f49bee7SXinliang David Li   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(Expect->getArgOperand(1));
1024f49bee7SXinliang David Li   if (!ExpectedValue)
1034f49bee7SXinliang David Li     return;
104621e8dcfSXinliang David Li   const APInt &ExpectedPhiValue = ExpectedValue->getValue();
105621e8dcfSXinliang David Li 
106621e8dcfSXinliang David Li   // Walk up in backward a list of instructions that
107621e8dcfSXinliang David Li   // have 'copy' semantics by 'stripping' the copies
108621e8dcfSXinliang David Li   // until a PHI node or an instruction of unknown kind
109621e8dcfSXinliang David Li   // is reached. Negation via xor is also handled.
110621e8dcfSXinliang David Li   //
111621e8dcfSXinliang David Li   //       C = PHI(...);
112621e8dcfSXinliang David Li   //       B = C;
113621e8dcfSXinliang David Li   //       A = B;
114621e8dcfSXinliang David Li   //       D = __builtin_expect(A, 0);
115621e8dcfSXinliang David Li   //
116621e8dcfSXinliang David Li   Value *V = &Arg;
117621e8dcfSXinliang David Li   SmallVector<Instruction *, 4> Operations;
118621e8dcfSXinliang David Li   while (!isa<PHINode>(V)) {
119621e8dcfSXinliang David Li     if (ZExtInst *ZExt = dyn_cast<ZExtInst>(V)) {
120621e8dcfSXinliang David Li       V = ZExt->getOperand(0);
121621e8dcfSXinliang David Li       Operations.push_back(ZExt);
122621e8dcfSXinliang David Li       continue;
123621e8dcfSXinliang David Li     }
124621e8dcfSXinliang David Li 
125621e8dcfSXinliang David Li     if (SExtInst *SExt = dyn_cast<SExtInst>(V)) {
126621e8dcfSXinliang David Li       V = SExt->getOperand(0);
127621e8dcfSXinliang David Li       Operations.push_back(SExt);
128621e8dcfSXinliang David Li       continue;
129621e8dcfSXinliang David Li     }
130621e8dcfSXinliang David Li 
131621e8dcfSXinliang David Li     BinaryOperator *BinOp = dyn_cast<BinaryOperator>(V);
132621e8dcfSXinliang David Li     if (!BinOp || BinOp->getOpcode() != Instruction::Xor)
133621e8dcfSXinliang David Li       return;
134621e8dcfSXinliang David Li 
135621e8dcfSXinliang David Li     ConstantInt *CInt = dyn_cast<ConstantInt>(BinOp->getOperand(1));
136621e8dcfSXinliang David Li     if (!CInt)
137621e8dcfSXinliang David Li       return;
138621e8dcfSXinliang David Li 
139621e8dcfSXinliang David Li     V = BinOp->getOperand(0);
140621e8dcfSXinliang David Li     Operations.push_back(BinOp);
141621e8dcfSXinliang David Li   }
142621e8dcfSXinliang David Li 
143621e8dcfSXinliang David Li   // Executes the recorded operations on input 'Value'.
144621e8dcfSXinliang David Li   auto ApplyOperations = [&](const APInt &Value) {
145621e8dcfSXinliang David Li     APInt Result = Value;
146621e8dcfSXinliang David Li     for (auto Op : llvm::reverse(Operations)) {
147621e8dcfSXinliang David Li       switch (Op->getOpcode()) {
148621e8dcfSXinliang David Li       case Instruction::Xor:
149621e8dcfSXinliang David Li         Result ^= cast<ConstantInt>(Op->getOperand(1))->getValue();
150621e8dcfSXinliang David Li         break;
151621e8dcfSXinliang David Li       case Instruction::ZExt:
152621e8dcfSXinliang David Li         Result = Result.zext(Op->getType()->getIntegerBitWidth());
153621e8dcfSXinliang David Li         break;
154621e8dcfSXinliang David Li       case Instruction::SExt:
155621e8dcfSXinliang David Li         Result = Result.sext(Op->getType()->getIntegerBitWidth());
156621e8dcfSXinliang David Li         break;
157621e8dcfSXinliang David Li       default:
158621e8dcfSXinliang David Li         llvm_unreachable("Unexpected operation");
159621e8dcfSXinliang David Li       }
160621e8dcfSXinliang David Li     }
161621e8dcfSXinliang David Li     return Result;
162621e8dcfSXinliang David Li   };
163621e8dcfSXinliang David Li 
164*91b4085bSSimon Pilgrim   auto *PhiDef = cast<PHINode>(V);
165621e8dcfSXinliang David Li 
166621e8dcfSXinliang David Li   // Get the first dominating conditional branch of the operand
167621e8dcfSXinliang David Li   // i's incoming block.
168621e8dcfSXinliang David Li   auto GetDomConditional = [&](unsigned i) -> BranchInst * {
169621e8dcfSXinliang David Li     BasicBlock *BB = PhiDef->getIncomingBlock(i);
170621e8dcfSXinliang David Li     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
171621e8dcfSXinliang David Li     if (BI && BI->isConditional())
172621e8dcfSXinliang David Li       return BI;
173621e8dcfSXinliang David Li     BB = BB->getSinglePredecessor();
174621e8dcfSXinliang David Li     if (!BB)
175621e8dcfSXinliang David Li       return nullptr;
176621e8dcfSXinliang David Li     BI = dyn_cast<BranchInst>(BB->getTerminator());
177621e8dcfSXinliang David Li     if (!BI || BI->isUnconditional())
178621e8dcfSXinliang David Li       return nullptr;
179621e8dcfSXinliang David Li     return BI;
180621e8dcfSXinliang David Li   };
181621e8dcfSXinliang David Li 
182621e8dcfSXinliang David Li   // Now walk through all Phi operands to find phi oprerands with values
183621e8dcfSXinliang David Li   // conflicting with the expected phi output value. Any such operand
184621e8dcfSXinliang David Li   // indicates the incoming edge to that operand is unlikely.
185621e8dcfSXinliang David Li   for (unsigned i = 0, e = PhiDef->getNumIncomingValues(); i != e; ++i) {
186621e8dcfSXinliang David Li 
187621e8dcfSXinliang David Li     Value *PhiOpnd = PhiDef->getIncomingValue(i);
188621e8dcfSXinliang David Li     ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd);
189621e8dcfSXinliang David Li     if (!CI)
190621e8dcfSXinliang David Li       continue;
191621e8dcfSXinliang David Li 
192621e8dcfSXinliang David Li     // Not an interesting case when IsUnlikely is false -- we can not infer
193621e8dcfSXinliang David Li     // anything useful when the operand value matches the expected phi
194621e8dcfSXinliang David Li     // output.
195621e8dcfSXinliang David Li     if (ExpectedPhiValue == ApplyOperations(CI->getValue()))
196621e8dcfSXinliang David Li       continue;
197621e8dcfSXinliang David Li 
198621e8dcfSXinliang David Li     BranchInst *BI = GetDomConditional(i);
199621e8dcfSXinliang David Li     if (!BI)
200621e8dcfSXinliang David Li       continue;
201621e8dcfSXinliang David Li 
202621e8dcfSXinliang David Li     MDBuilder MDB(PhiDef->getContext());
203621e8dcfSXinliang David Li 
204621e8dcfSXinliang David Li     // There are two situations in which an operand of the PhiDef comes
205621e8dcfSXinliang David Li     // from a given successor of a branch instruction BI.
206621e8dcfSXinliang David Li     // 1) When the incoming block of the operand is the successor block;
207621e8dcfSXinliang David Li     // 2) When the incoming block is BI's enclosing block and the
208621e8dcfSXinliang David Li     // successor is the PhiDef's enclosing block.
209621e8dcfSXinliang David Li     //
210621e8dcfSXinliang David Li     // Returns true if the operand which comes from OpndIncomingBB
211621e8dcfSXinliang David Li     // comes from outgoing edge of BI that leads to Succ block.
212621e8dcfSXinliang David Li     auto *OpndIncomingBB = PhiDef->getIncomingBlock(i);
213621e8dcfSXinliang David Li     auto IsOpndComingFromSuccessor = [&](BasicBlock *Succ) {
214621e8dcfSXinliang David Li       if (OpndIncomingBB == Succ)
215621e8dcfSXinliang David Li         // If this successor is the incoming block for this
216621e8dcfSXinliang David Li         // Phi operand, then this successor does lead to the Phi.
217621e8dcfSXinliang David Li         return true;
218621e8dcfSXinliang David Li       if (OpndIncomingBB == BI->getParent() && Succ == PhiDef->getParent())
219621e8dcfSXinliang David Li         // Otherwise, if the edge is directly from the branch
220621e8dcfSXinliang David Li         // to the Phi, this successor is the one feeding this
221621e8dcfSXinliang David Li         // Phi operand.
222621e8dcfSXinliang David Li         return true;
223621e8dcfSXinliang David Li       return false;
224621e8dcfSXinliang David Li     };
225621e8dcfSXinliang David Li 
226621e8dcfSXinliang David Li     if (IsOpndComingFromSuccessor(BI->getSuccessor(1)))
227621e8dcfSXinliang David Li       BI->setMetadata(
228621e8dcfSXinliang David Li           LLVMContext::MD_prof,
229621e8dcfSXinliang David Li           MDB.createBranchWeights(LikelyBranchWeight, UnlikelyBranchWeight));
230621e8dcfSXinliang David Li     else if (IsOpndComingFromSuccessor(BI->getSuccessor(0)))
231621e8dcfSXinliang David Li       BI->setMetadata(
232621e8dcfSXinliang David Li           LLVMContext::MD_prof,
233621e8dcfSXinliang David Li           MDB.createBranchWeights(UnlikelyBranchWeight, LikelyBranchWeight));
234621e8dcfSXinliang David Li   }
235621e8dcfSXinliang David Li }
236621e8dcfSXinliang David Li 
23740afd5c9SXinliang David Li // Handle both BranchInst and SelectInst.
23840afd5c9SXinliang David Li template <class BrSelInst> static bool handleBrSelExpect(BrSelInst &BSI) {
23972793727SChandler Carruth 
24072793727SChandler Carruth   // Handle non-optimized IR code like:
24172793727SChandler Carruth   //   %expval = call i64 @llvm.expect.i64(i64 %conv1, i64 1)
24272793727SChandler Carruth   //   %tobool = icmp ne i64 %expval, 0
24372793727SChandler Carruth   //   br i1 %tobool, label %if.then, label %if.end
24472793727SChandler Carruth   //
24572793727SChandler Carruth   // Or the following simpler case:
24672793727SChandler Carruth   //   %expval = call i1 @llvm.expect.i1(i1 %cmp, i1 1)
24772793727SChandler Carruth   //   br i1 %expval, label %if.then, label %if.end
24872793727SChandler Carruth 
24972793727SChandler Carruth   CallInst *CI;
25072793727SChandler Carruth 
25140afd5c9SXinliang David Li   ICmpInst *CmpI = dyn_cast<ICmpInst>(BSI.getCondition());
252ee8d6acbSXinliang David Li   CmpInst::Predicate Predicate;
253d6cfba2aSXinliang David Li   ConstantInt *CmpConstOperand = nullptr;
25472793727SChandler Carruth   if (!CmpI) {
25540afd5c9SXinliang David Li     CI = dyn_cast<CallInst>(BSI.getCondition());
256ee8d6acbSXinliang David Li     Predicate = CmpInst::ICMP_NE;
25772793727SChandler Carruth   } else {
258ee8d6acbSXinliang David Li     Predicate = CmpI->getPredicate();
259ee8d6acbSXinliang David Li     if (Predicate != CmpInst::ICMP_NE && Predicate != CmpInst::ICMP_EQ)
26072793727SChandler Carruth       return false;
261d6cfba2aSXinliang David Li 
262d6cfba2aSXinliang David Li     CmpConstOperand = dyn_cast<ConstantInt>(CmpI->getOperand(1));
263ee8d6acbSXinliang David Li     if (!CmpConstOperand)
264ee8d6acbSXinliang David Li       return false;
26572793727SChandler Carruth     CI = dyn_cast<CallInst>(CmpI->getOperand(0));
26672793727SChandler Carruth   }
26772793727SChandler Carruth 
26872793727SChandler Carruth   if (!CI)
26972793727SChandler Carruth     return false;
27072793727SChandler Carruth 
271d6cfba2aSXinliang David Li   uint64_t ValueComparedTo = 0;
272d6cfba2aSXinliang David Li   if (CmpConstOperand) {
273d6cfba2aSXinliang David Li     if (CmpConstOperand->getBitWidth() > 64)
274d6cfba2aSXinliang David Li       return false;
275d6cfba2aSXinliang David Li     ValueComparedTo = CmpConstOperand->getZExtValue();
276d6cfba2aSXinliang David Li   }
277d6cfba2aSXinliang David Li 
27872793727SChandler Carruth   Function *Fn = CI->getCalledFunction();
27972793727SChandler Carruth   if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
28072793727SChandler Carruth     return false;
28172793727SChandler Carruth 
28272793727SChandler Carruth   Value *ArgValue = CI->getArgOperand(0);
28372793727SChandler Carruth   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
28472793727SChandler Carruth   if (!ExpectedValue)
28572793727SChandler Carruth     return false;
28672793727SChandler Carruth 
28772793727SChandler Carruth   MDBuilder MDB(CI->getContext());
28872793727SChandler Carruth   MDNode *Node;
2897bdad084SPetr Hosek   MDNode *ExpNode;
29072793727SChandler Carruth 
291ee8d6acbSXinliang David Li   if ((ExpectedValue->getZExtValue() == ValueComparedTo) ==
2927bdad084SPetr Hosek       (Predicate == CmpInst::ICMP_EQ)) {
29372793727SChandler Carruth     Node = MDB.createBranchWeights(LikelyBranchWeight, UnlikelyBranchWeight);
2947bdad084SPetr Hosek     ExpNode = MDB.createMisExpect(0, LikelyBranchWeight, UnlikelyBranchWeight);
2957bdad084SPetr Hosek   } else {
29672793727SChandler Carruth     Node = MDB.createBranchWeights(UnlikelyBranchWeight, LikelyBranchWeight);
2977bdad084SPetr Hosek     ExpNode = MDB.createMisExpect(1, LikelyBranchWeight, UnlikelyBranchWeight);
2987bdad084SPetr Hosek   }
29972793727SChandler Carruth 
3007bdad084SPetr Hosek   BSI.setMetadata(LLVMContext::MD_misexpect, ExpNode);
30172793727SChandler Carruth 
30272793727SChandler Carruth   if (CmpI)
30372793727SChandler Carruth     CmpI->setOperand(0, ArgValue);
30472793727SChandler Carruth   else
30540afd5c9SXinliang David Li     BSI.setCondition(ArgValue);
3067bdad084SPetr Hosek 
3077bdad084SPetr Hosek   misexpect::checkFrontendInstrumentation(BSI);
3087bdad084SPetr Hosek 
3097bdad084SPetr Hosek   BSI.setMetadata(LLVMContext::MD_prof, Node);
3107bdad084SPetr Hosek 
31172793727SChandler Carruth   return true;
31272793727SChandler Carruth }
31372793727SChandler Carruth 
31440afd5c9SXinliang David Li static bool handleBranchExpect(BranchInst &BI) {
31540afd5c9SXinliang David Li   if (BI.isUnconditional())
31640afd5c9SXinliang David Li     return false;
31740afd5c9SXinliang David Li 
31840afd5c9SXinliang David Li   return handleBrSelExpect<BranchInst>(BI);
31940afd5c9SXinliang David Li }
32040afd5c9SXinliang David Li 
32143e590e5SChandler Carruth static bool lowerExpectIntrinsic(Function &F) {
322c3bf5bd8SChandler Carruth   bool Changed = false;
323c3bf5bd8SChandler Carruth 
324d12741e0SChandler Carruth   for (BasicBlock &BB : F) {
32572793727SChandler Carruth     // Create "block_weights" metadata.
326d12741e0SChandler Carruth     if (BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
3270012c778SChandler Carruth       if (handleBranchExpect(*BI))
3286eb60eb5SChandler Carruth         ExpectIntrinsicsHandled++;
329d12741e0SChandler Carruth     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
3300012c778SChandler Carruth       if (handleSwitchExpect(*SI))
3316eb60eb5SChandler Carruth         ExpectIntrinsicsHandled++;
33272793727SChandler Carruth     }
33372793727SChandler Carruth 
33440afd5c9SXinliang David Li     // Remove llvm.expect intrinsics. Iterate backwards in order
33540afd5c9SXinliang David Li     // to process select instructions before the intrinsic gets
33640afd5c9SXinliang David Li     // removed.
33740afd5c9SXinliang David Li     for (auto BI = BB.rbegin(), BE = BB.rend(); BI != BE;) {
33840afd5c9SXinliang David Li       Instruction *Inst = &*BI++;
33940afd5c9SXinliang David Li       CallInst *CI = dyn_cast<CallInst>(Inst);
34040afd5c9SXinliang David Li       if (!CI) {
34140afd5c9SXinliang David Li         if (SelectInst *SI = dyn_cast<SelectInst>(Inst)) {
34240afd5c9SXinliang David Li           if (handleBrSelExpect(*SI))
34340afd5c9SXinliang David Li             ExpectIntrinsicsHandled++;
34440afd5c9SXinliang David Li         }
34572793727SChandler Carruth         continue;
34640afd5c9SXinliang David Li       }
34772793727SChandler Carruth 
34872793727SChandler Carruth       Function *Fn = CI->getCalledFunction();
34972793727SChandler Carruth       if (Fn && Fn->getIntrinsicID() == Intrinsic::expect) {
350621e8dcfSXinliang David Li         // Before erasing the llvm.expect, walk backward to find
351621e8dcfSXinliang David Li         // phi that define llvm.expect's first arg, and
352621e8dcfSXinliang David Li         // infer branch probability:
353621e8dcfSXinliang David Li         handlePhiDef(CI);
35472793727SChandler Carruth         Value *Exp = CI->getArgOperand(0);
35572793727SChandler Carruth         CI->replaceAllUsesWith(Exp);
35672793727SChandler Carruth         CI->eraseFromParent();
357c3bf5bd8SChandler Carruth         Changed = true;
35872793727SChandler Carruth       }
35972793727SChandler Carruth     }
36072793727SChandler Carruth   }
36172793727SChandler Carruth 
362c3bf5bd8SChandler Carruth   return Changed;
36372793727SChandler Carruth }
36472793727SChandler Carruth 
365164a2aa6SChandler Carruth PreservedAnalyses LowerExpectIntrinsicPass::run(Function &F,
366164a2aa6SChandler Carruth                                                 FunctionAnalysisManager &) {
36743e590e5SChandler Carruth   if (lowerExpectIntrinsic(F))
36843e590e5SChandler Carruth     return PreservedAnalyses::none();
36943e590e5SChandler Carruth 
37043e590e5SChandler Carruth   return PreservedAnalyses::all();
37143e590e5SChandler Carruth }
37243e590e5SChandler Carruth 
37343e590e5SChandler Carruth namespace {
3745f8f34e4SAdrian Prantl /// Legacy pass for lowering expect intrinsics out of the IR.
37543e590e5SChandler Carruth ///
37643e590e5SChandler Carruth /// When this pass is run over a function it uses expect intrinsics which feed
37743e590e5SChandler Carruth /// branches and switches to provide branch weight metadata for those
37843e590e5SChandler Carruth /// terminators. It then removes the expect intrinsics from the IR so the rest
37943e590e5SChandler Carruth /// of the optimizer can ignore them.
38043e590e5SChandler Carruth class LowerExpectIntrinsic : public FunctionPass {
38143e590e5SChandler Carruth public:
38243e590e5SChandler Carruth   static char ID;
38343e590e5SChandler Carruth   LowerExpectIntrinsic() : FunctionPass(ID) {
38443e590e5SChandler Carruth     initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
38543e590e5SChandler Carruth   }
38643e590e5SChandler Carruth 
38743e590e5SChandler Carruth   bool runOnFunction(Function &F) override { return lowerExpectIntrinsic(F); }
38843e590e5SChandler Carruth };
389f00654e3SAlexander Kornienko }
39043e590e5SChandler Carruth 
39172793727SChandler Carruth char LowerExpectIntrinsic::ID = 0;
3920ea746bfSChandler Carruth INITIALIZE_PASS(LowerExpectIntrinsic, "lower-expect",
3930ea746bfSChandler Carruth                 "Lower 'expect' Intrinsics", false, false)
39472793727SChandler Carruth 
39572793727SChandler Carruth FunctionPass *llvm::createLowerExpectIntrinsicPass() {
39672793727SChandler Carruth   return new LowerExpectIntrinsic();
39772793727SChandler Carruth }
398