xref: /llvm-project/llvm/lib/Transforms/Scalar/LowerGuardIntrinsic.cpp (revision a403d75be7add73f3e34032d73c81b8e1dcba3b9)
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/InitializePasses.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Transforms/Scalar.h"
26 #include "llvm/Transforms/Utils/GuardUtils.h"
27 
28 using namespace llvm;
29 
30 static bool lowerGuardIntrinsic(Function &F) {
31   // Check if we can cheaply rule out the possibility of not having any work to
32   // do.
33   auto *GuardDecl = F.getParent()->getFunction(
34       Intrinsic::getName(Intrinsic::experimental_guard));
35   if (!GuardDecl || GuardDecl->use_empty())
36     return false;
37 
38   SmallVector<CallInst *, 8> ToLower;
39   // Traverse through the users of GuardDecl.
40   // This is presumably cheaper than traversing all instructions in the
41   // function.
42   for (auto *U : GuardDecl->users())
43     if (auto *CI = dyn_cast<CallInst>(U))
44       if (CI->getFunction() == &F)
45         ToLower.push_back(CI);
46 
47   if (ToLower.empty())
48     return false;
49 
50   auto *DeoptIntrinsic = Intrinsic::getDeclaration(
51       F.getParent(), Intrinsic::experimental_deoptimize, {F.getReturnType()});
52   DeoptIntrinsic->setCallingConv(GuardDecl->getCallingConv());
53 
54   for (auto *CI : ToLower) {
55     makeGuardControlFlowExplicit(DeoptIntrinsic, CI, false);
56     CI->eraseFromParent();
57   }
58 
59   return true;
60 }
61 
62 PreservedAnalyses LowerGuardIntrinsicPass::run(Function &F,
63                                                FunctionAnalysisManager &AM) {
64   if (lowerGuardIntrinsic(F))
65     return PreservedAnalyses::none();
66 
67   return PreservedAnalyses::all();
68 }
69