LLVM 24.0.0git
LowerAllowCheckPass.cpp
Go to the documentation of this file.
1//===- LowerAllowCheckPass.cpp ----------------------------------*- 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
11
13#include "llvm/ADT/Statistic.h"
15#include "llvm/ADT/StringRef.h"
18#include "llvm/IR/Constants.h"
23#include "llvm/IR/Intrinsics.h"
24#include "llvm/IR/Metadata.h"
25#include "llvm/IR/Module.h"
26#include "llvm/Support/Debug.h"
28#include <memory>
29#include <optional>
30#include <random>
31
32using namespace llvm;
33
34#define DEBUG_TYPE "lower-allow-check"
35
36STATISTIC(NumChecksTotal, "Number of checks");
37STATISTIC(NumChecksRemoved, "Number of removed checks");
38
39struct RemarkInfo {
44 : Kind("Kind", II->getArgOperand(0)),
45 F("Function", II->getParent()->getParent()),
46 BB("Block", II->getParent()->getName()) {}
47};
48
50 bool Removed) {
51 if (Removed) {
52 ORE.emit([&]() {
53 RemarkInfo Info(II);
54 return OptimizationRemark(DEBUG_TYPE, "Removed", II)
55 << "Removed check: Kind=" << Info.Kind << " F=" << Info.F
56 << " BB=" << Info.BB;
57 });
58 } else {
59 ORE.emit([&]() {
60 RemarkInfo Info(II);
61 return OptimizationRemarkMissed(DEBUG_TYPE, "Allowed", II)
62 << "Allowed check: Kind=" << Info.Kind << " F=" << Info.F
63 << " BB=" << Info.BB;
64 });
65 }
66}
67
69 const LowerAllowCheckPass::Options &Opts) {
70 const InstrumentationOptions &CLOpts = InstrumentationOptions::Global;
71 // Lazy analysis getters.
72 auto GetBFI = [&AM, &F, BFI = (BlockFrequencyInfo *)nullptr]() mutable
73 -> const BlockFrequencyInfo & {
74 if (!BFI)
76 return *BFI;
77 };
78 auto GetPSI = [&AM, &F, PSI = std::optional<ProfileSummaryInfo *>()]() mutable
79 -> const ProfileSummaryInfo * {
80 if (!PSI.has_value()) {
82 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
83 }
84 return *PSI;
85 };
86 auto GetORE = [&AM, &F, ORE = (OptimizationRemarkEmitter *)nullptr]() mutable
88 if (!ORE)
90 return *ORE;
91 };
92
93 // List of intrinsics and the constant value they should be lowered to.
95 std::unique_ptr<RandomNumberGenerator> Rng;
96
97 auto GetRng = [&]() -> RandomNumberGenerator & {
98 if (!Rng)
99 Rng = F.getParent()->createRNG(F.getName());
100 return *Rng;
101 };
102
103 auto GetCutoff = [&](const IntrinsicInst *II) -> unsigned {
104 if (CLOpts.lower_allow_check_percentile_cutoff_hot)
105 return *CLOpts.lower_allow_check_percentile_cutoff_hot;
106 else if (II->getIntrinsicID() == Intrinsic::allow_ubsan_check) {
107 auto *Kind = cast<ConstantInt>(II->getArgOperand(0));
108 if (Kind->getZExtValue() < Opts.cutoffs.size())
109 return Opts.cutoffs[Kind->getZExtValue()];
110 } else if (II->getIntrinsicID() == Intrinsic::allow_runtime_check) {
111 return Opts.runtime_check;
112 }
113
114 return 0;
115 };
116
117 auto ShouldRemoveHot = [&](const BasicBlock &BB, unsigned int cutoff) {
118 if (cutoff == 1000000)
119 return true;
120 const ProfileSummaryInfo *PSI = GetPSI();
121 return PSI && PSI->isHotCountNthPercentile(
122 cutoff, GetBFI().getBlockProfileCount(&BB).value_or(0));
123 };
124
125 auto ShouldRemoveRandom = [&]() {
126 return CLOpts.lower_allow_check_random_rate &&
127 !std::bernoulli_distribution(*CLOpts.lower_allow_check_random_rate)(
128 GetRng());
129 };
130
131 auto ShouldRemove = [&](const IntrinsicInst *II) {
132 unsigned int cutoff = GetCutoff(II);
133 return ShouldRemoveRandom() || ShouldRemoveHot(*(II->getParent()), cutoff);
134 };
135
136 for (Instruction &I : instructions(F)) {
138 if (!II)
139 continue;
140 auto ID = II->getIntrinsicID();
141 switch (ID) {
142 case Intrinsic::allow_ubsan_check:
143 case Intrinsic::allow_runtime_check: {
144 bool ToRemove = ShouldRemove(II);
145
146 ReplaceWithValue.push_back({
147 II,
148 !ToRemove,
149 });
150 emitRemark(II, GetORE(), ToRemove);
151 break;
152 }
153 case Intrinsic::allow_sanitize_address:
154 ReplaceWithValue.push_back(
155 {II, F.hasFnAttribute(Attribute::SanitizeAddress)});
156 break;
157 case Intrinsic::allow_sanitize_thread:
158 ReplaceWithValue.push_back(
159 {II, F.hasFnAttribute(Attribute::SanitizeThread)});
160 break;
161 case Intrinsic::allow_sanitize_memory:
162 ReplaceWithValue.push_back(
163 {II, F.hasFnAttribute(Attribute::SanitizeMemory)});
164 break;
165 case Intrinsic::allow_sanitize_hwaddress:
166 ReplaceWithValue.push_back(
167 {II, F.hasFnAttribute(Attribute::SanitizeHWAddress)});
168 break;
169 default:
170 break;
171 }
172 }
173
174 for (auto [I, V] : ReplaceWithValue) {
175 ++NumChecksTotal;
176 if (!V) // If the final value is false, the check is considered removed.
177 ++NumChecksRemoved;
178 I->replaceAllUsesWith(ConstantInt::getBool(I->getType(), V));
179 I->eraseFromParent();
180 }
181
182 return !ReplaceWithValue.empty();
183}
184
187 if (F.isDeclaration())
188 return PreservedAnalyses::all();
189
190 return lowerAllowChecks(F, AM, Opts)
191 // We do not change the CFG, we only replace the intrinsics with
192 // true or false.
195}
196
198 const InstrumentationOptions &CLOpts = InstrumentationOptions::Global;
199 return CLOpts.lower_allow_check_random_rate ||
200 CLOpts.lower_allow_check_percentile_cutoff_hot;
201}
202
204 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
205 static_cast<PassInfoMixin<LowerAllowCheckPass> *>(this)->printPipeline(
206 OS, MapClassName2PassName);
207 OS << "<";
208
209 // Format is <cutoffs[0,1,2]=70000;cutoffs[5,6,8]=90000>
210 // but it's equally valid to specify
211 // cutoffs[0]=70000;cutoffs[1]=70000;cutoffs[2]=70000;cutoffs[5]=90000;...
212 // and that's what we do here. It is verbose but valid and easy to verify
213 // correctness.
214 // TODO: print shorter output by combining adjacent runs, etc.
215 int i = 0;
216 ListSeparator LS(";");
217 for (unsigned int cutoff : Opts.cutoffs) {
218 if (cutoff > 0)
219 OS << LS << "cutoffs[" << i << "]=" << cutoff;
220 i++;
221 }
222 if (Opts.runtime_check)
223 OS << LS << "runtime_check=" << Opts.runtime_check;
224
225 OS << '>';
226}
ReachingDefInfo InstSet & ToRemove
Expand Atomic instructions
static const Function * getParent(const Value *V)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
static void emitRemark(IntrinsicInst *II, OptimizationRemarkEmitter &ORE, bool Removed)
static bool lowerAllowChecks(Function &F, FunctionAnalysisManager &AM, const LowerAllowCheckPass::Options &Opts)
This file provides the interface for the pass responsible for removing expensive ubsan checks.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
uint64_t IntrinsicInst * II
static StringRef getName(Value *V)
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
A wrapper class for inspecting calls to intrinsic functions.
A helper class to return the specified delimiter string after the first invocation of operator String...
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
static LLVM_ABI bool IsRequested()
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
LLVM_ABI bool isHotCountNthPercentile(int PercentileCutoff, uint64_t C) const
Returns true if count C is considered hot with regard to a given hot percentile cutoff value.
A random number generator.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
RemarkInfo(IntrinsicInst *II)
std::vector< unsigned int > cutoffs