1 //===-- GuardUtils.cpp - Utils for work with guards -------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // Utils that are used to perform transformations related to guards and their 9 // conditions. 10 //===----------------------------------------------------------------------===// 11 12 #include "llvm/Transforms/Utils/GuardUtils.h" 13 #include "llvm/IR/Function.h" 14 #include "llvm/IR/IRBuilder.h" 15 #include "llvm/IR/Instructions.h" 16 #include "llvm/IR/MDBuilder.h" 17 #include "llvm/Support/CommandLine.h" 18 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 19 20 using namespace llvm; 21 22 static 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 27 void 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 } 65