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/Analysis/GuardUtils.h"
14#include "llvm/IR/Function.h"
15#include "llvm/IR/IRBuilder.h"
16#include "llvm/IR/Instructions.h"
17#include "llvm/IR/MDBuilder.h"
18#include "llvm/IR/PatternMatch.h"
19#include "llvm/Support/CommandLine.h"
20#include "llvm/Transforms/Utils/BasicBlockUtils.h"
21
22using namespace llvm;
23using namespace llvm::PatternMatch;
24
25static cl::opt<uint32_t> PredicatePassBranchWeight(
26 "guards-predicate-pass-branch-weight", cl::Hidden, cl::init(Val: 1 << 20),
27 cl::desc("The probability of a guard failing is assumed to be the "
28 "reciprocal of this value (default = 1 << 20)"));
29
30void llvm::makeGuardControlFlowExplicit(Function *DeoptIntrinsic,
31 CallInst *Guard, bool UseWC) {
32 OperandBundleDef DeoptOB(*Guard->getOperandBundle(ID: LLVMContext::OB_deopt));
33 SmallVector<Value *, 4> Args(drop_begin(RangeOrContainer: Guard->args()));
34
35 auto *CheckBB = Guard->getParent();
36 auto *DeoptBlockTerm =
37 SplitBlockAndInsertIfThen(Cond: Guard->getArgOperand(i: 0), SplitBefore: Guard, Unreachable: true);
38
39 auto *CheckBI = cast<CondBrInst>(Val: CheckBB->getTerminator());
40
41 // SplitBlockAndInsertIfThen inserts control flow that branches to
42 // DeoptBlockTerm if the condition is true. We want the opposite.
43 CheckBI->swapSuccessors();
44
45 CheckBI->getSuccessor(i: 0)->setName("guarded");
46 CheckBI->getSuccessor(i: 1)->setName("deopt");
47
48 if (auto *MD = Guard->getMetadata(KindID: LLVMContext::MD_make_implicit))
49 CheckBI->setMetadata(KindID: LLVMContext::MD_make_implicit, Node: MD);
50
51 MDBuilder MDB(Guard->getContext());
52 CheckBI->setMetadata(KindID: LLVMContext::MD_prof,
53 Node: MDB.createBranchWeights(TrueWeight: PredicatePassBranchWeight, FalseWeight: 1));
54
55 IRBuilder<> B(DeoptBlockTerm);
56 auto *DeoptCall = B.CreateCall(Callee: DeoptIntrinsic, Args, OpBundles: {DeoptOB}, Name: "");
57
58 if (DeoptIntrinsic->getReturnType()->isVoidTy()) {
59 B.CreateRetVoid();
60 } else {
61 DeoptCall->setName("deoptcall");
62 B.CreateRet(V: DeoptCall);
63 }
64
65 DeoptCall->setCallingConv(Guard->getCallingConv());
66 DeoptBlockTerm->eraseFromParent();
67
68 if (UseWC) {
69 // We want the guard to be expressed as explicit control flow, but still be
70 // widenable. For that, we add Widenable Condition intrinsic call to the
71 // guard's condition.
72 IRBuilder<> B(CheckBI);
73 auto *WC = B.CreateIntrinsic(ID: Intrinsic::experimental_widenable_condition,
74 Args: {}, FMFSource: nullptr, Name: "widenable_cond");
75 CheckBI->setCondition(B.CreateAnd(LHS: CheckBI->getCondition(), RHS: WC,
76 Name: "exiplicit_guard_cond"));
77 assert(isWidenableBranch(CheckBI) && "Branch must be widenable.");
78 }
79}
80
81void llvm::widenWidenableBranch(CondBrInst *WidenableBR, Value *NewCond) {
82 assert(isWidenableBranch(WidenableBR) && "precondition");
83
84 // The tempting trivially option is to produce something like this:
85 // br (and oldcond, newcond) where oldcond is assumed to contain a widenable
86 // condition, but that doesn't match the pattern parseWidenableBranch expects
87 // so we have to be more sophisticated.
88
89 Use *C, *WC;
90 BasicBlock *IfTrueBB, *IfFalseBB;
91 parseWidenableBranch(U: WidenableBR, Cond&: C, WC, IfTrueBB, IfFalseBB);
92 if (!C) {
93 // br (wc()), ... form
94 IRBuilder<> B(WidenableBR);
95 WidenableBR->setCondition(B.CreateAnd(LHS: NewCond, RHS: WC->get()));
96 } else {
97 // br (wc & C), ... form
98 IRBuilder<> B(WidenableBR);
99 C->set(B.CreateAnd(LHS: NewCond, RHS: C->get()));
100 Instruction *WCAnd = cast<Instruction>(Val: WidenableBR->getCondition());
101 // Condition is only guaranteed to dominate branch
102 WCAnd->moveBefore(InsertPos: WidenableBR->getIterator());
103 }
104 assert(isWidenableBranch(WidenableBR) && "preserve widenabiliy");
105}
106
107void llvm::setWidenableBranchCond(CondBrInst *WidenableBR, Value *NewCond) {
108 assert(isWidenableBranch(WidenableBR) && "precondition");
109
110 Use *C, *WC;
111 BasicBlock *IfTrueBB, *IfFalseBB;
112 parseWidenableBranch(U: WidenableBR, Cond&: C, WC, IfTrueBB, IfFalseBB);
113 if (!C) {
114 // br (wc()), ... form
115 IRBuilder<> B(WidenableBR);
116 WidenableBR->setCondition(B.CreateAnd(LHS: NewCond, RHS: WC->get()));
117 } else {
118 // br (wc & C), ... form
119 Instruction *WCAnd = cast<Instruction>(Val: WidenableBR->getCondition());
120 // Condition is only guaranteed to dominate branch
121 WCAnd->moveBefore(InsertPos: WidenableBR->getIterator());
122 C->set(NewCond);
123 }
124 assert(isWidenableBranch(WidenableBR) && "preserve widenabiliy");
125}
126