1//===- LowerGuardIntrinsic.cpp - Lower the guard intrinsic ---------------===//
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//
9// This pass lowers the llvm.experimental.guard intrinsic to a conditional call
10// to @llvm.experimental.deoptimize. Once this happens, the guard can no longer
11// be widened.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/Analysis/GuardUtils.h"
18#include "llvm/IR/Function.h"
19#include "llvm/IR/InstIterator.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/Module.h"
23#include "llvm/Transforms/Utils/GuardUtils.h"
24
25using namespace llvm;
26
27static bool lowerGuardIntrinsic(Function &F) {
28 // Check if we can cheaply rule out the possibility of not having any work to
29 // do.
30 auto *GuardDecl = F.getParent()->getFunction(
31 Name: Intrinsic::getName(id: Intrinsic::experimental_guard));
32 if (!GuardDecl || GuardDecl->use_empty())
33 return false;
34
35 SmallVector<CallInst *, 8> ToLower;
36 // Traverse through the users of GuardDecl.
37 // This is presumably cheaper than traversing all instructions in the
38 // function.
39 for (auto *U : GuardDecl->users())
40 if (auto *CI = dyn_cast<CallInst>(Val: U))
41 if (CI->getFunction() == &F)
42 ToLower.push_back(Elt: CI);
43
44 if (ToLower.empty())
45 return false;
46
47 auto *DeoptIntrinsic = Intrinsic::getDeclaration(
48 M: F.getParent(), id: Intrinsic::experimental_deoptimize, Tys: {F.getReturnType()});
49 DeoptIntrinsic->setCallingConv(GuardDecl->getCallingConv());
50
51 for (auto *CI : ToLower) {
52 makeGuardControlFlowExplicit(DeoptIntrinsic, Guard: CI, UseWC: false);
53 CI->eraseFromParent();
54 }
55
56 return true;
57}
58
59PreservedAnalyses LowerGuardIntrinsicPass::run(Function &F,
60 FunctionAnalysisManager &AM) {
61 if (lowerGuardIntrinsic(F))
62 return PreservedAnalyses::none();
63
64 return PreservedAnalyses::all();
65}
66