blob: 08de0a4c53e996de3897e6b6966f9920691e3a2b [file] [log] [blame]
Max Kazantsev8b4ffe62018-08-29 10:51:59 +00001//===-- GuardUtils.cpp - Utils for work with guards -------------*- C++ -*-===//
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// Utils that are used to perform transformations related to guards and their
10// conditions.
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Transforms/Utils/GuardUtils.h"
14#include "llvm/IR/Function.h"
15#include "llvm/IR/Instructions.h"
16#include "llvm/IR/IRBuilder.h"
17#include "llvm/IR/MDBuilder.h"
18#include "llvm/Transforms/Utils/BasicBlockUtils.h"
19
20using namespace llvm;
21
22static cl::opt<uint32_t> PredicatePassBranchWeight(
23 "guards-predicate-pass-branch-weight", cl::Hidden, cl::init(1 << 20),
24 cl::desc("The probability of a guard failing is assumed to be the "
25 "reciprocal of this value (default = 1 << 20)"));
26
27void llvm::makeGuardControlFlowExplicit(Function *DeoptIntrinsic,
28 CallInst *Guard) {
29 OperandBundleDef DeoptOB(*Guard->getOperandBundle(LLVMContext::OB_deopt));
30 SmallVector<Value *, 4> Args(std::next(Guard->arg_begin()), Guard->arg_end());
31
32 auto *CheckBB = Guard->getParent();
33 auto *DeoptBlockTerm =
34 SplitBlockAndInsertIfThen(Guard->getArgOperand(0), Guard, true);
35
36 auto *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
37
38 // SplitBlockAndInsertIfThen inserts control flow that branches to
39 // DeoptBlockTerm if the condition is true. We want the opposite.
40 CheckBI->swapSuccessors();
41
42 CheckBI->getSuccessor(0)->setName("guarded");
43 CheckBI->getSuccessor(1)->setName("deopt");
44
45 if (auto *MD = Guard->getMetadata(LLVMContext::MD_make_implicit))
46 CheckBI->setMetadata(LLVMContext::MD_make_implicit, MD);
47
48 MDBuilder MDB(Guard->getContext());
49 CheckBI->setMetadata(LLVMContext::MD_prof,
50 MDB.createBranchWeights(PredicatePassBranchWeight, 1));
51
52 IRBuilder<> B(DeoptBlockTerm);
53 auto *DeoptCall = B.CreateCall(DeoptIntrinsic, Args, {DeoptOB}, "");
54
55 if (DeoptIntrinsic->getReturnType()->isVoidTy()) {
56 B.CreateRetVoid();
57 } else {
58 DeoptCall->setName("deoptcall");
59 B.CreateRet(DeoptCall);
60 }
61
62 DeoptCall->setCallingConv(Guard->getCallingConv());
63 DeoptBlockTerm->eraseFromParent();
64}