LLVM 24.0.0git
SanitizerCoverage.cpp
Go to the documentation of this file.
1//===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
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// Coverage instrumentation done on LLVM IR level, works with Sanitizers.
10//
11//===----------------------------------------------------------------------===//
12
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/ScopeExit.h"
20#include "llvm/IR/Constant.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Dominators.h"
25#include "llvm/IR/Function.h"
27#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/MDBuilder.h"
32#include "llvm/IR/Module.h"
33#include "llvm/IR/Type.h"
41
42using namespace llvm;
43
44#define DEBUG_TYPE "sancov"
45
46const char SanCovTracePCIndirName[] = "__sanitizer_cov_trace_pc_indir";
47const char SanCovTracePCName[] = "__sanitizer_cov_trace_pc";
48const char SanCovTracePCEntryName[] = "__sanitizer_cov_trace_pc_entry";
49const char SanCovTracePCExitName[] = "__sanitizer_cov_trace_pc_exit";
50const char SanCovTraceCmp1[] = "__sanitizer_cov_trace_cmp1";
51const char SanCovTraceCmp2[] = "__sanitizer_cov_trace_cmp2";
52const char SanCovTraceCmp4[] = "__sanitizer_cov_trace_cmp4";
53const char SanCovTraceCmp8[] = "__sanitizer_cov_trace_cmp8";
54const char SanCovTraceConstCmp1[] = "__sanitizer_cov_trace_const_cmp1";
55const char SanCovTraceConstCmp2[] = "__sanitizer_cov_trace_const_cmp2";
56const char SanCovTraceConstCmp4[] = "__sanitizer_cov_trace_const_cmp4";
57const char SanCovTraceConstCmp8[] = "__sanitizer_cov_trace_const_cmp8";
58const char SanCovLoad1[] = "__sanitizer_cov_load1";
59const char SanCovLoad2[] = "__sanitizer_cov_load2";
60const char SanCovLoad4[] = "__sanitizer_cov_load4";
61const char SanCovLoad8[] = "__sanitizer_cov_load8";
62const char SanCovLoad16[] = "__sanitizer_cov_load16";
63const char SanCovStore1[] = "__sanitizer_cov_store1";
64const char SanCovStore2[] = "__sanitizer_cov_store2";
65const char SanCovStore4[] = "__sanitizer_cov_store4";
66const char SanCovStore8[] = "__sanitizer_cov_store8";
67const char SanCovStore16[] = "__sanitizer_cov_store16";
68const char SanCovTraceDiv4[] = "__sanitizer_cov_trace_div4";
69const char SanCovTraceDiv8[] = "__sanitizer_cov_trace_div8";
70const char SanCovTraceGep[] = "__sanitizer_cov_trace_gep";
71const char SanCovTraceSwitchName[] = "__sanitizer_cov_trace_switch";
73 "sancov.module_ctor_trace_pc_guard";
75 "sancov.module_ctor_8bit_counters";
76const char SanCovModuleCtorBoolFlagName[] = "sancov.module_ctor_bool_flag";
78
79const char SanCovTracePCGuardName[] = "__sanitizer_cov_trace_pc_guard";
80const char SanCovTracePCGuardInitName[] = "__sanitizer_cov_trace_pc_guard_init";
81const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init";
82const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init";
83const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init";
84const char SanCovCFsInitName[] = "__sanitizer_cov_cfs_init";
85
86const char SanCovGuardsSectionName[] = "sancov_guards";
87const char SanCovCountersSectionName[] = "sancov_cntrs";
88const char SanCovBoolFlagSectionName[] = "sancov_bools";
89const char SanCovPCsSectionName[] = "sancov_pcs";
90const char SanCovCFsSectionName[] = "sancov_cfs";
91const char SanCovCallbackGateSectionName[] = "sancov_gate";
92
93const char SanCovStackDepthCallbackName[] = "__sanitizer_cov_stack_depth";
94const char SanCovLowestStackName[] = "__sancov_lowest_stack";
95const char SanCovCallbackGateName[] = "__sancov_should_track";
96
97namespace {
98
99SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
101 switch (LegacyCoverageLevel) {
102 case 0:
104 break;
105 case 1:
107 break;
108 case 2:
110 break;
111 case 3:
113 break;
114 case 4:
116 Res.IndirectCalls = true;
117 break;
118 }
119 return Res;
120}
121
122SanitizerCoverageOptions overrideFromCL(const InstrumentationOptions &Opts,
124 // Sets CoverageType and IndirectCalls.
125 SanitizerCoverageOptions CLOpts = getOptions(Opts.sanitizer_coverage_level);
126 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
127 Options.IndirectCalls |= CLOpts.IndirectCalls;
128 Options.TraceCmp |= Opts.sanitizer_coverage_trace_compares;
129 Options.TraceDiv |= Opts.sanitizer_coverage_trace_divs;
130 Options.TraceGep |= Opts.sanitizer_coverage_trace_geps;
131 Options.TracePC |= Opts.sanitizer_coverage_trace_pc;
132 Options.TracePCEntryExit |= Opts.sanitizer_coverage_trace_pc_entry_exit;
133 Options.TracePCGuard |= Opts.sanitizer_coverage_trace_pc_guard;
134 Options.Inline8bitCounters |= Opts.sanitizer_coverage_inline_8bit_counters;
135 Options.InlineBoolFlag |= Opts.sanitizer_coverage_inline_bool_flag;
136 Options.PCTable |= Opts.sanitizer_coverage_pc_table;
137 Options.NoPrune |= !Opts.sanitizer_coverage_prune_blocks;
138 Options.StackDepth |= Opts.sanitizer_coverage_stack_depth;
139 Options.StackDepthCallbackMin =
140 std::max(Options.StackDepthCallbackMin,
141 Opts.sanitizer_coverage_stack_depth_callback_min);
142 Options.TraceLoads |= Opts.sanitizer_coverage_trace_loads;
143 Options.TraceStores |= Opts.sanitizer_coverage_trace_stores;
144 Options.GatedCallbacks |= Opts.sanitizer_coverage_gated_trace_callbacks;
145 if (!Options.TracePCGuard && !Options.TracePC && !Options.TracePCEntryExit &&
146 !Options.Inline8bitCounters && !Options.StackDepth &&
147 !Options.InlineBoolFlag && !Options.TraceLoads && !Options.TraceStores)
148 Options.TracePCGuard = true; // TracePCGuard is default.
149 Options.CollectControlFlow |= Opts.sanitizer_coverage_control_flow;
150 return Options;
151}
152
153class ModuleSanitizerCoverage {
154public:
155 using DomTreeCallback = function_ref<const DominatorTree &(Function &F)>;
156 using PostDomTreeCallback =
158
159 ModuleSanitizerCoverage(const InstrumentationOptions &Opts, Module &M,
160 DomTreeCallback DTCallback,
161 PostDomTreeCallback PDTCallback,
163 const SpecialCaseList *Allowlist,
164 const SpecialCaseList *Blocklist)
165 : Opts(Opts), M(M), DTCallback(DTCallback), PDTCallback(PDTCallback),
166 Options(Options), Allowlist(Allowlist), Blocklist(Blocklist) {}
167
168 bool instrumentModule();
169
170private:
171 void createFunctionControlFlow(Function &F);
172 void instrumentFunction(Function &F);
173 void InjectCoverageForIndirectCalls(Function &F,
174 ArrayRef<Instruction *> IndirCalls);
175 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets,
176 Value *&FunctionGateCmp);
177 void InjectTraceForDiv(Function &F,
178 ArrayRef<BinaryOperator *> DivTraceTargets);
179 void InjectTraceForGep(Function &F,
180 ArrayRef<GetElementPtrInst *> GepTraceTargets);
181 void InjectTraceForLoadsAndStores(Function &F, ArrayRef<LoadInst *> Loads,
182 ArrayRef<StoreInst *> Stores);
183 void InjectTraceForExits(Function &F);
184 void InjectTraceForSwitch(Function &F,
185 ArrayRef<Instruction *> SwitchTraceTargets,
186 Value *&FunctionGateCmp);
187 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
188 Value *&FunctionGateCmp, bool IsLeafFunc);
189 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
190 Function &F, Type *Ty,
191 const char *Section);
192 void CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
193 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
194 void CreateGateBranch(Function &F, Value *&FunctionGateCmp, IRBuilder<> &IRB);
195 Value *CreateFunctionLocalGateCmp(IRBuilder<> &IRB);
196 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
197 Value *&FunctionGateCmp, bool IsLeafFunc);
198 CallInst *createRuntimeCall(IRBuilder<> &IRB, FunctionCallee Callee,
199 ArrayRef<Value *> Args = {});
200 void addFuncletBundles(Function &F);
201 Function *CreateInitCallsForSections(Module &M, const char *CtorName,
202 const char *InitFunctionName, Type *Ty,
203 const char *Section);
204 std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
205 Type *Ty);
206
207 std::string getSectionName(const std::string &Section) const;
208 std::string getSectionStart(const std::string &Section) const;
209 std::string getSectionEnd(const std::string &Section) const;
210
211 const InstrumentationOptions &Opts;
212 Module &M;
213 DomTreeCallback DTCallback;
214 PostDomTreeCallback PDTCallback;
215
216 FunctionCallee SanCovStackDepthCallback;
217 FunctionCallee SanCovTracePCIndir;
218 FunctionCallee SanCovTracePC, SanCovTracePCGuard;
219 FunctionCallee SanCovTracePCEntry, SanCovTracePCExit;
220 std::array<FunctionCallee, 4> SanCovTraceCmpFunction;
221 std::array<FunctionCallee, 4> SanCovTraceConstCmpFunction;
222 std::array<FunctionCallee, 5> SanCovLoadFunction;
223 std::array<FunctionCallee, 5> SanCovStoreFunction;
224 std::array<FunctionCallee, 2> SanCovTraceDivFunction;
225 FunctionCallee SanCovTraceGepFunction;
226 FunctionCallee SanCovTraceSwitchFunction;
227 GlobalVariable *SanCovLowestStack;
228 GlobalVariable *SanCovCallbackGate;
229 Type *PtrTy, *IntptrTy, *Int64Ty, *Int32Ty, *Int16Ty, *Int8Ty, *Int1Ty;
230 Module *CurModule;
231 Triple TargetTriple;
232 LLVMContext *C;
233 const DataLayout *DL;
234
235 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
236 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
237 GlobalVariable *FunctionBoolArray; // for inline-bool-flag.
238 GlobalVariable *FunctionCFsArray; // for control flow table
239 // Runtime calls inserted into the current function, for
240 // addFuncletBundles().
241 SmallVector<CallInst *, 16> RuntimeCalls;
242 SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
243 SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
244
246
247 const SpecialCaseList *Allowlist;
248 const SpecialCaseList *Blocklist;
249};
250} // namespace
251
254 const std::vector<std::string> &AllowlistFiles,
255 const std::vector<std::string> &BlocklistFiles)
256 : Options(std::move(Options)),
257 VFS(VFS ? std::move(VFS) : vfs::getRealFileSystem()) {
258 if (AllowlistFiles.size() > 0)
259 Allowlist = SpecialCaseList::createOrDie(AllowlistFiles, *this->VFS);
260 if (BlocklistFiles.size() > 0)
261 Blocklist = SpecialCaseList::createOrDie(BlocklistFiles, *this->VFS);
262}
263
266 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
267 auto DTCallback = [&FAM](Function &F) -> const DominatorTree & {
268 return FAM.getResult<DominatorTreeAnalysis>(F);
269 };
270 auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree & {
271 return FAM.getResult<PostDominatorTreeAnalysis>(F);
272 };
273 const InstrumentationOptions &Opts = getInstrumentationOptions(M);
274 ModuleSanitizerCoverage ModuleSancov(Opts, M, DTCallback, PDTCallback,
275 overrideFromCL(Opts, Options),
276 Allowlist.get(), Blocklist.get());
277 if (!ModuleSancov.instrumentModule())
278 return PreservedAnalyses::all();
279
281 // GlobalsAA is considered stateless and does not get invalidated unless
282 // explicitly invalidated; PreservedAnalyses::none() is not enough. Sanitizers
283 // make changes that require GlobalsAA to be invalidated.
284 PA.abandon<GlobalsAA>();
285 return PA;
286}
287
288std::pair<Value *, Value *>
289ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section,
290 Type *Ty) {
291 // Use ExternalWeak so that if all sections are discarded due to section
292 // garbage collection, the linker will not report undefined symbol errors.
293 // Windows defines the start/stop symbols in compiler-rt so no need for
294 // ExternalWeak.
295 GlobalValue::LinkageTypes Linkage = TargetTriple.isOSBinFormatCOFF()
298 GlobalVariable *SecStart = new GlobalVariable(M, Ty, false, Linkage, nullptr,
299 getSectionStart(Section));
301 GlobalVariable *SecEnd = new GlobalVariable(M, Ty, false, Linkage, nullptr,
302 getSectionEnd(Section));
304 if (!TargetTriple.isOSBinFormatCOFF())
305 return std::make_pair(SecStart, SecEnd);
306
307 // Account for the fact that on windows-msvc __start_* symbols actually
308 // point to a uint64_t before the start of the array.
310 SecStart, ConstantInt::get(IntptrTy, sizeof(uint64_t)));
311 return std::make_pair(GEP, SecEnd);
312}
313
314Function *ModuleSanitizerCoverage::CreateInitCallsForSections(
315 Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
316 const char *Section) {
317 if (Opts.sanitizer_coverage_drop_ctors)
318 return nullptr;
319 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
320 auto SecStart = SecStartEnd.first;
321 auto SecEnd = SecStartEnd.second;
322 Function *CtorFunc;
323 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
324 M, CtorName, InitFunctionName, {PtrTy, PtrTy}, {SecStart, SecEnd});
325 assert(CtorFunc->getName() == CtorName);
326
327 if (TargetTriple.supportsCOMDAT()) {
328 // Use comdat to dedup CtorFunc.
329 CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
330 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
331 } else {
333 }
334
335 if (TargetTriple.isOSBinFormatCOFF()) {
336 // In COFF files, if the contructors are set as COMDAT (they are because
337 // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
338 // functions and data) is used, the constructors get stripped. To prevent
339 // this, give the constructors weak ODR linkage and ensure the linker knows
340 // to include the sancov constructor. This way the linker can deduplicate
341 // the constructors but always leave one copy.
343 }
344 return CtorFunc;
345}
346
347bool ModuleSanitizerCoverage::instrumentModule() {
349 return false;
350 if (Allowlist &&
351 !Allowlist->inSection("coverage", "src", M.getSourceFileName()))
352 return false;
353 if (Blocklist &&
354 Blocklist->inSection("coverage", "src", M.getSourceFileName()))
355 return false;
356 C = &(M.getContext());
357 DL = &M.getDataLayout();
358 CurModule = &M;
359 TargetTriple = M.getTargetTriple();
360 FunctionGuardArray = nullptr;
361 Function8bitCounterArray = nullptr;
362 FunctionBoolArray = nullptr;
363 FunctionCFsArray = nullptr;
364 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
365 PtrTy = PointerType::getUnqual(*C);
366 Type *VoidTy = Type::getVoidTy(*C);
367 IRBuilder<> IRB(M);
368 Int64Ty = IRB.getInt64Ty();
369 Int32Ty = IRB.getInt32Ty();
370 Int16Ty = IRB.getInt16Ty();
371 Int8Ty = IRB.getInt8Ty();
372 Int1Ty = IRB.getInt1Ty();
373
374 SanCovTracePCIndir =
375 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
376 // Make sure smaller parameters are zero-extended to i64 if required by the
377 // target ABI.
378 AttributeList SanCovTraceCmpZeroExtAL;
379 SanCovTraceCmpZeroExtAL =
380 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
381 SanCovTraceCmpZeroExtAL =
382 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
383
384 SanCovTraceCmpFunction[0] =
385 M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
386 IRB.getInt8Ty(), IRB.getInt8Ty());
387 SanCovTraceCmpFunction[1] =
388 M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
389 IRB.getInt16Ty(), IRB.getInt16Ty());
390 SanCovTraceCmpFunction[2] =
391 M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
392 IRB.getInt32Ty(), IRB.getInt32Ty());
393 SanCovTraceCmpFunction[3] =
394 M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
395
396 SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
397 SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
398 SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
399 SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
400 SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
401 SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
402 SanCovTraceConstCmpFunction[3] =
403 M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
404
405 // Loads.
406 SanCovLoadFunction[0] = M.getOrInsertFunction(SanCovLoad1, VoidTy, PtrTy);
407 SanCovLoadFunction[1] = M.getOrInsertFunction(SanCovLoad2, VoidTy, PtrTy);
408 SanCovLoadFunction[2] = M.getOrInsertFunction(SanCovLoad4, VoidTy, PtrTy);
409 SanCovLoadFunction[3] = M.getOrInsertFunction(SanCovLoad8, VoidTy, PtrTy);
410 SanCovLoadFunction[4] = M.getOrInsertFunction(SanCovLoad16, VoidTy, PtrTy);
411 // Stores.
412 SanCovStoreFunction[0] = M.getOrInsertFunction(SanCovStore1, VoidTy, PtrTy);
413 SanCovStoreFunction[1] = M.getOrInsertFunction(SanCovStore2, VoidTy, PtrTy);
414 SanCovStoreFunction[2] = M.getOrInsertFunction(SanCovStore4, VoidTy, PtrTy);
415 SanCovStoreFunction[3] = M.getOrInsertFunction(SanCovStore8, VoidTy, PtrTy);
416 SanCovStoreFunction[4] = M.getOrInsertFunction(SanCovStore16, VoidTy, PtrTy);
417
418 {
419 AttributeList AL;
420 AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
421 SanCovTraceDivFunction[0] =
422 M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
423 }
424 SanCovTraceDivFunction[1] =
425 M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
426 SanCovTraceGepFunction =
427 M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
428 SanCovTraceSwitchFunction =
429 M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, PtrTy);
430
431 SanCovLowestStack = M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
432 if (SanCovLowestStack->getValueType() != IntptrTy) {
433 C->emitError(StringRef("'") + SanCovLowestStackName +
434 "' should not be declared by the user");
435 return true;
436 }
437 SanCovLowestStack->setThreadLocalMode(
439 if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
440 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
441
442 if (Options.GatedCallbacks) {
443 if (!Options.TracePCGuard && !Options.TraceCmp) {
444 C->emitError("'sanitizer-coverage-gated-trace-callbacks' is only "
445 "supported with trace-pc-guard or trace-cmp");
446 return true;
447 }
448
449 SanCovCallbackGate = cast<GlobalVariable>(
450 M.getOrInsertGlobal(SanCovCallbackGateName, Int64Ty));
451 SanCovCallbackGate->setSection(
453 SanCovCallbackGate->setInitializer(Constant::getNullValue(Int64Ty));
454 SanCovCallbackGate->setLinkage(GlobalVariable::LinkOnceAnyLinkage);
455 SanCovCallbackGate->setVisibility(GlobalVariable::HiddenVisibility);
456 appendToCompilerUsed(M, SanCovCallbackGate);
457 }
458
459 SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
460 SanCovTracePCEntry = M.getOrInsertFunction(SanCovTracePCEntryName, VoidTy);
461 SanCovTracePCExit = M.getOrInsertFunction(SanCovTracePCExitName, VoidTy);
462 SanCovTracePCGuard =
463 M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, PtrTy);
464
465 SanCovStackDepthCallback =
466 M.getOrInsertFunction(SanCovStackDepthCallbackName, VoidTy);
467
468 for (auto &F : M)
469 instrumentFunction(F);
470
471 Function *Ctor = nullptr;
472
473 if (FunctionGuardArray)
474 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
477 if (Function8bitCounterArray)
478 Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
481 if (FunctionBoolArray) {
482 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName,
485 }
486 if (Ctor && Options.PCTable) {
487 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrTy);
488 FunctionCallee InitFunction =
490 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
491 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
492 }
493
494 if (Ctor && Options.CollectControlFlow) {
495 auto SecStartEnd = CreateSecStartEnd(M, SanCovCFsSectionName, IntptrTy);
496 FunctionCallee InitFunction =
498 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
499 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
500 }
501
502 appendToUsed(M, GlobalsToAppendToUsed);
503 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
504 return true;
505}
506
507// True if block has successors and it dominates all of them.
508static bool isFullDominator(const BasicBlock *BB, const DominatorTree &DT) {
509 if (succ_empty(BB))
510 return false;
511
512 return llvm::all_of(successors(BB), [&](const BasicBlock *SUCC) {
513 return DT.dominates(BB, SUCC);
514 });
515}
516
517// True if block has predecessors and it postdominates all of them.
518static bool isFullPostDominator(const BasicBlock *BB,
519 const PostDominatorTree &PDT) {
520 if (pred_empty(BB))
521 return false;
522
523 return llvm::all_of(predecessors(BB), [&](const BasicBlock *PRED) {
524 return PDT.dominates(BB, PRED);
525 });
526}
527
528static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
529 const DominatorTree &DT,
530 const PostDominatorTree &PDT,
532 // Don't insert coverage for blocks containing nothing but unreachable: we
533 // will never call __sanitizer_cov() for them, so counting them in
534 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
535 // percentage. Also, unreachable instructions frequently have no debug
536 // locations.
538 return false;
539
540 // Don't insert coverage into blocks without a valid insertion point
541 // (catchswitch blocks).
542 if (BB->getFirstInsertionPt() == BB->end())
543 return false;
544
545 if (Options.NoPrune || &F.getEntryBlock() == BB)
546 return true;
547
549 &F.getEntryBlock() != BB)
550 return false;
551
552 // Do not instrument full dominators, or full post-dominators with multiple
553 // predecessors.
554 return !isFullDominator(BB, DT) &&
555 !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
556}
557
558// Returns true iff From->To is a backedge.
559// A twist here is that we treat From->To as a backedge if
560// * To dominates From or
561// * To->UniqueSuccessor dominates From
562static bool IsBackEdge(BasicBlock *From, BasicBlock *To,
563 const DominatorTree &DT) {
564 if (DT.dominates(To, From))
565 return true;
566 if (auto Next = To->getUniqueSuccessor())
567 if (DT.dominates(Next, From))
568 return true;
569 return false;
570}
571
572// Prunes uninteresting Cmp instrumentation:
573// * CMP instructions that feed into loop backedge branch.
574//
575// Note that Cmp pruning is controlled by the same flag as the
576// BB pruning.
577static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree &DT,
579 if (!Options.NoPrune)
580 if (CMP->hasOneUse())
581 if (auto BR = dyn_cast<CondBrInst>(CMP->user_back()))
582 for (BasicBlock *B : BR->successors())
583 if (IsBackEdge(BR->getParent(), B, DT))
584 return false;
585 return true;
586}
587
588void ModuleSanitizerCoverage::instrumentFunction(Function &F) {
589 if (F.empty())
590 return;
591 if (F.getName().contains(".module_ctor"))
592 return; // Should not instrument sanitizer init functions.
593 if (F.getName().starts_with("__sanitizer_"))
594 return; // Don't instrument __sanitizer_* callbacks.
595 // Don't touch available_externally functions, their actual body is elewhere.
596 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
597 return;
598 // Don't instrument MSVC CRT configuration helpers. They may run before normal
599 // initialization.
600 if (F.getName() == "__local_stdio_printf_options" ||
601 F.getName() == "__local_stdio_scanf_options")
602 return;
603 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
604 return;
605 // Don't instrument functions using SEH for now. Splitting basic blocks like
606 // we do for coverage breaks WinEHPrepare.
607 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
608 if (F.hasPersonalityFn() &&
610 return;
611 if (Allowlist && !Allowlist->inSection("coverage", "fun", F.getName()))
612 return;
613 if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName()))
614 return;
615 // Do not apply any instrumentation for naked functions.
616 if (F.hasFnAttribute(Attribute::Naked))
617 return;
618 if (F.hasFnAttribute(Attribute::NoSanitizeCoverage))
619 return;
620 if (F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation))
621 return;
622 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge) {
624 F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
625 }
627 SmallVector<BasicBlock *, 16> BlocksToInstrument;
628 SmallVector<Instruction *, 8> CmpTraceTargets;
629 SmallVector<Instruction *, 8> SwitchTraceTargets;
630 SmallVector<BinaryOperator *, 8> DivTraceTargets;
634
635 const DominatorTree &DT = DTCallback(F);
636 const PostDominatorTree &PDT = PDTCallback(F);
637 bool IsLeafFunc = true;
638
639 for (auto &BB : F) {
640 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
641 BlocksToInstrument.push_back(&BB);
642 for (auto &Inst : BB) {
643 if (Options.IndirectCalls) {
644 CallBase *CB = dyn_cast<CallBase>(&Inst);
645 if (CB && CB->isIndirectCall())
646 IndirCalls.push_back(&Inst);
647 }
648 if (Options.TraceCmp) {
649 if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
650 if (IsInterestingCmp(CMP, DT, Options))
651 CmpTraceTargets.push_back(&Inst);
652 if (isa<SwitchInst>(&Inst))
653 SwitchTraceTargets.push_back(&Inst);
654 }
655 if (Options.TraceDiv)
657 if (BO->getOpcode() == Instruction::SDiv ||
658 BO->getOpcode() == Instruction::UDiv)
659 DivTraceTargets.push_back(BO);
660 if (Options.TraceGep)
662 GepTraceTargets.push_back(GEP);
663 if (Options.TraceLoads)
664 if (LoadInst *LI = dyn_cast<LoadInst>(&Inst))
665 Loads.push_back(LI);
666 if (Options.TraceStores)
667 if (StoreInst *SI = dyn_cast<StoreInst>(&Inst))
668 Stores.push_back(SI);
669 if (Options.StackDepth)
670 if (isa<InvokeInst>(Inst) ||
671 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
672 IsLeafFunc = false;
673 }
674 }
675
676 if (Options.CollectControlFlow)
677 createFunctionControlFlow(F);
678
679 Value *FunctionGateCmp = nullptr;
680 InjectCoverage(F, BlocksToInstrument, FunctionGateCmp, IsLeafFunc);
681 InjectCoverageForIndirectCalls(F, IndirCalls);
682 InjectTraceForCmp(F, CmpTraceTargets, FunctionGateCmp);
683 InjectTraceForSwitch(F, SwitchTraceTargets, FunctionGateCmp);
684 InjectTraceForDiv(F, DivTraceTargets);
685 InjectTraceForGep(F, GepTraceTargets);
686 InjectTraceForLoadsAndStores(F, Loads, Stores);
687 // Before InjectTraceForExits(), whose EscapeEnumerator may turn the calls
688 // into invokes. The calls it inserts precede returns and resumes, which are
689 // never in a funclet.
690 addFuncletBundles(F);
691
692 if (Options.TracePCEntryExit)
693 InjectTraceForExits(F);
694}
695
696CallInst *ModuleSanitizerCoverage::createRuntimeCall(IRBuilder<> &IRB,
697 FunctionCallee Callee,
698 ArrayRef<Value *> Args) {
699 CallInst *CI = IRB.CreateCall(Callee, Args);
700 RuntimeCalls.push_back(CI);
701 return CI;
702}
703
704// With scoped EH (MSVC C++), a call inside a funclet must name the funclet's
705// pad in a "funclet" operand bundle. WinEHPrepare takes a call without one for
706// a call that does not belong to the funclet and replaces it, and all that
707// follows it in its block, with unreachable: a catch handler that compares an
708// integer or makes an indirect call would lose its body. Give each runtime
709// call the bundle of the funclet it is in.
710void ModuleSanitizerCoverage::addFuncletBundles(Function &F) {
711 if (RuntimeCalls.empty())
712 return;
713 llvm::scope_exit ClearCalls([&] { RuntimeCalls.clear(); });
714 if (!F.hasPersonalityFn() ||
715 !isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
716 return;
717
719 for (CallInst *CI : RuntimeCalls) {
720 const ColorVector &Colors = BlockColors[CI->getParent()];
721 // Unreachable blocks have no color; they are deleted later.
722 if (Colors.empty())
723 continue;
724 // A bundle names one pad.
725 if (Colors.size() != 1) {
726 F.getContext().emitError("Instruction's BasicBlock is not monochromatic");
727 continue;
728 }
729 BasicBlock *Color = Colors.front();
730 BasicBlock::iterator Pad = Color->getFirstNonPHIIt();
731 if (Pad == Color->end() || !isa<FuncletPadInst>(Pad))
732 continue;
733 OperandBundleDef OB("funclet", &*Pad);
735 OB, CI->getIterator());
736 NewCall->copyMetadata(*CI);
737 CI->replaceAllUsesWith(NewCall);
738 CI->eraseFromParent();
739 }
740}
741
742GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection(
743 size_t NumElements, Function &F, Type *Ty, const char *Section) {
744 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
745 auto Array = new GlobalVariable(
746 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
747 Constant::getNullValue(ArrayTy), "__sancov_gen_");
748
749 // sancov_pcs parallels the other arrays, so they must be retained or
750 // discarded together. Put them in F's comdat to tie them to F for linker GC
751 // benefit. Outside ELF (nodeduplicate), a new comdat for an interposable F
752 // could prevail over a strong definition (COFF: the weak external becomes a
753 // COMDAT definition; Wasm: comdats deduplicate first). noipa doesn't affect
754 // symbol resolution.
755 if (TargetTriple.supportsCOMDAT() &&
756 (F.hasComdat() || TargetTriple.isOSBinFormatELF() ||
757 !F.isInterposable(/*CheckNoIPA=*/false)))
758 if (auto Comdat = getOrCreateFunctionComdat(F, TargetTriple))
759 Array->setComdat(Comdat);
760 Array->setSection(getSectionName(Section));
761 Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedValue()));
762
763 // Optimizers (e.g. GlobalOpt/ConstantMerge) may not discard the arrays as a
764 // unit, so retain them in the compiler; without a comdat, in the linker too.
765 if (Array->hasComdat())
766 GlobalsToAppendToCompilerUsed.push_back(Array);
767 else
768 GlobalsToAppendToUsed.push_back(Array);
769
770 return Array;
771}
772
773void ModuleSanitizerCoverage::CreatePCArray(Function &F,
774 ArrayRef<BasicBlock *> AllBlocks) {
775 size_t N = AllBlocks.size();
776 assert(N);
778 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
779 for (size_t i = 0; i < N; i++) {
780 if (&F.getEntryBlock() == AllBlocks[i]) {
781 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, PtrTy));
782 PCs.push_back(
783 (Constant *)IRB.CreateIntToPtr(ConstantInt::get(IntptrTy, 1), PtrTy));
784 } else {
786 BlockAddress::get(AllBlocks[i]), PtrTy));
788 }
789 }
790 auto *PCArray =
791 CreateFunctionLocalArrayInSection(N * 2, F, PtrTy, SanCovPCsSectionName);
792 PCArray->setInitializer(
793 ConstantArray::get(ArrayType::get(PtrTy, N * 2), PCs));
794 PCArray->setConstant(true);
795}
796
797void ModuleSanitizerCoverage::CreateFunctionLocalArrays(
798 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
799 if (Options.TracePCGuard)
800 FunctionGuardArray = CreateFunctionLocalArrayInSection(
801 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
802
803 if (Options.Inline8bitCounters)
804 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
805 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
806 if (Options.InlineBoolFlag)
807 FunctionBoolArray = CreateFunctionLocalArrayInSection(
808 AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName);
809
810 if (Options.PCTable)
811 CreatePCArray(F, AllBlocks);
812}
813
814Value *ModuleSanitizerCoverage::CreateFunctionLocalGateCmp(IRBuilder<> &IRB) {
815 auto Load = IRB.CreateLoad(Int64Ty, SanCovCallbackGate);
816 Load->setNoSanitizeMetadata();
817 auto Cmp = IRB.CreateIsNotNull(Load);
818 Cmp->setName("sancov gate cmp");
819 return Cmp;
820}
821
822void ModuleSanitizerCoverage::CreateGateBranch(Function &F,
823 Value *&FunctionGateCmp,
824 IRBuilder<> &IRB) {
825 if (!FunctionGateCmp) {
826 // Create this in the entry block
827 BasicBlock &BB = F.getEntryBlock();
829 IP = PrepareToSplitEntryBlock(BB, IP);
830 IRBuilder<> EntryIRB(&*IP);
831 FunctionGateCmp = CreateFunctionLocalGateCmp(EntryIRB);
832 }
833 // Set the branch weights in order to minimize the price paid when the
834 // gate is turned off, allowing the default enablement of this
835 // instrumentation with as little of a performance cost as possible
836 auto Weights = MDBuilder(*C).createBranchWeights(1, 100000);
839 FunctionGateCmp, &*IRB.GetInsertPoint(), false, Weights));
841}
842
843bool ModuleSanitizerCoverage::InjectCoverage(Function &F,
844 ArrayRef<BasicBlock *> AllBlocks,
845 Value *&FunctionGateCmp,
846 bool IsLeafFunc) {
847 if (AllBlocks.empty())
848 return false;
849 CreateFunctionLocalArrays(F, AllBlocks);
850 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
851 InjectCoverageAtBlock(F, *AllBlocks[i], i, FunctionGateCmp, IsLeafFunc);
852
853 return true;
854}
855
856// On every indirect call we call a run-time function
857// __sanitizer_cov_indir_call* with two parameters:
858// - callee address,
859// - global cache array that contains CacheSize pointers (zero-initialized).
860// The cache is used to speed up recording the caller-callee pairs.
861// The address of the caller is passed implicitly via caller PC.
862// CacheSize is encoded in the name of the run-time function.
863void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls(
864 Function &F, ArrayRef<Instruction *> IndirCalls) {
865 if (IndirCalls.empty())
866 return;
867 assert(Options.TracePC || Options.TracePCEntryExit || Options.TracePCGuard ||
868 Options.Inline8bitCounters || Options.InlineBoolFlag);
869 for (auto *I : IndirCalls) {
871 CallBase &CB = cast<CallBase>(*I);
873 if (isa<InlineAsm>(Callee))
874 continue;
875 createRuntimeCall(IRB, SanCovTracePCIndir,
876 IRB.CreatePointerCast(Callee, IntptrTy));
877 }
878}
879
880// For every switch statement we insert a call:
881// __sanitizer_cov_trace_switch(CondValue,
882// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
883
884void ModuleSanitizerCoverage::InjectTraceForSwitch(
885 Function &F, ArrayRef<Instruction *> SwitchTraceTargets,
886 Value *&FunctionGateCmp) {
887 for (auto *I : SwitchTraceTargets) {
890 SmallVector<Constant *, 16> Initializers;
891 Value *Cond = SI->getCondition();
892 if (Cond->getType()->getScalarSizeInBits() >
893 Int64Ty->getScalarSizeInBits())
894 continue;
895 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
896 Initializers.push_back(
897 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
898 if (Cond->getType()->getScalarSizeInBits() <
899 Int64Ty->getScalarSizeInBits())
900 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
901 for (auto It : SI->cases()) {
902 ConstantInt *C = It.getCaseValue();
903 if (C->getType()->getScalarSizeInBits() < 64)
904 C = ConstantInt::get(C->getContext(), C->getValue().zext(64));
905 Initializers.push_back(C);
906 }
907 llvm::sort(drop_begin(Initializers, 2),
908 [](const Constant *A, const Constant *B) {
909 return cast<ConstantInt>(A)->getLimitedValue() <
910 cast<ConstantInt>(B)->getLimitedValue();
911 });
912 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
914 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
915 ConstantArray::get(ArrayOfInt64Ty, Initializers),
916 "__sancov_gen_cov_switch_values");
917 if (Options.GatedCallbacks)
918 CreateGateBranch(F, FunctionGateCmp, IRB);
919 createRuntimeCall(IRB, SanCovTraceSwitchFunction, {Cond, GV});
920 }
921 }
922}
923
924void ModuleSanitizerCoverage::InjectTraceForDiv(
925 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
926 for (auto *BO : DivTraceTargets) {
928 Value *A1 = BO->getOperand(1);
929 if (isa<ConstantInt>(A1))
930 continue;
931 if (!A1->getType()->isIntegerTy())
932 continue;
933 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
934 int CallbackIdx = TypeSize == 32 ? 0 : TypeSize == 64 ? 1 : -1;
935 if (CallbackIdx < 0)
936 continue;
937 auto Ty = Type::getIntNTy(*C, TypeSize);
938 createRuntimeCall(IRB, SanCovTraceDivFunction[CallbackIdx],
939 {IRB.CreateIntCast(A1, Ty, true)});
940 }
941}
942
943void ModuleSanitizerCoverage::InjectTraceForGep(
944 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
945 for (auto *GEP : GepTraceTargets) {
947 for (Use &Idx : GEP->indices())
948 if (!isa<ConstantInt>(Idx) && Idx->getType()->isIntegerTy())
949 createRuntimeCall(IRB, SanCovTraceGepFunction,
950 {IRB.CreateIntCast(Idx, IntptrTy, true)});
951 }
952}
953
954void ModuleSanitizerCoverage::InjectTraceForLoadsAndStores(
956 auto CallbackIdx = [&](Type *ElementTy) -> int {
957 uint64_t TypeSize = DL->getTypeStoreSizeInBits(ElementTy);
958 return TypeSize == 8 ? 0
959 : TypeSize == 16 ? 1
960 : TypeSize == 32 ? 2
961 : TypeSize == 64 ? 3
962 : TypeSize == 128 ? 4
963 : -1;
964 };
965 for (auto *LI : Loads) {
967 auto Ptr = LI->getPointerOperand();
968 int Idx = CallbackIdx(LI->getType());
969 if (Idx < 0)
970 continue;
971 createRuntimeCall(IRB, SanCovLoadFunction[Idx], Ptr);
972 }
973 for (auto *SI : Stores) {
975 auto Ptr = SI->getPointerOperand();
976 int Idx = CallbackIdx(SI->getValueOperand()->getType());
977 if (Idx < 0)
978 continue;
979 createRuntimeCall(IRB, SanCovStoreFunction[Idx], Ptr);
980 }
981}
982
983void ModuleSanitizerCoverage::InjectTraceForExits(Function &F) {
984 EscapeEnumerator EE(F, "sancov_exit");
985 while (IRBuilder<> *AtExit = EE.Next()) {
987 AtExit->CreateCall(SanCovTracePCExit, {})
988 ->setTailCallKind(CallInst::TCK_NoTail);
989 }
990}
991
992void ModuleSanitizerCoverage::InjectTraceForCmp(
993 Function &F, ArrayRef<Instruction *> CmpTraceTargets,
994 Value *&FunctionGateCmp) {
995 for (auto *I : CmpTraceTargets) {
996 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
997 InstrumentationIRBuilder IRB(ICMP);
998 Value *A0 = ICMP->getOperand(0);
999 Value *A1 = ICMP->getOperand(1);
1000 if (!A0->getType()->isIntegerTy())
1001 continue;
1002 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
1003 int CallbackIdx = TypeSize == 8 ? 0
1004 : TypeSize == 16 ? 1
1005 : TypeSize == 32 ? 2
1006 : TypeSize == 64 ? 3
1007 : -1;
1008 if (CallbackIdx < 0)
1009 continue;
1010 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
1011 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
1012 bool FirstIsConst = isa<ConstantInt>(A0);
1013 bool SecondIsConst = isa<ConstantInt>(A1);
1014 // If both are const, then we don't need such a comparison.
1015 if (FirstIsConst && SecondIsConst)
1016 continue;
1017 // If only one is const, then make it the first callback argument.
1018 if (FirstIsConst || SecondIsConst) {
1019 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
1020 if (SecondIsConst)
1021 std::swap(A0, A1);
1022 }
1023
1024 auto Ty = Type::getIntNTy(*C, TypeSize);
1025 if (Options.GatedCallbacks)
1026 CreateGateBranch(F, FunctionGateCmp, IRB);
1027 createRuntimeCall(
1028 IRB, CallbackFunc,
1029 {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
1030 }
1031 }
1032}
1033
1034void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
1035 size_t Idx,
1036 Value *&FunctionGateCmp,
1037 bool IsLeafFunc) {
1039 bool IsEntryBB = &BB == &F.getEntryBlock();
1040 DebugLoc EntryLoc;
1041 if (IsEntryBB) {
1042 if (auto SP = F.getSubprogram())
1043 EntryLoc = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
1044 // Keep static allocas and llvm.localescape calls in the entry block. Even
1045 // if we aren't splitting the block, it's nice for allocas to be before
1046 // calls.
1047 IP = PrepareToSplitEntryBlock(BB, IP);
1048 }
1049
1050 InstrumentationIRBuilder IRB(&*IP);
1051 if (EntryLoc)
1052 IRB.SetCurrentDebugLocation(EntryLoc);
1053 if (Options.TracePC || (IsEntryBB && Options.TracePCEntryExit)) {
1054 FunctionCallee Callee = IsEntryBB && Options.TracePCEntryExit
1055 ? SanCovTracePCEntry
1056 : SanCovTracePC;
1057 createRuntimeCall(IRB, Callee)
1058 ->setCannotMerge(); // gets the PC using GET_CALLER_PC.
1059 }
1060 if (Options.TracePCGuard) {
1061 auto GuardPtr = IRB.CreateConstInBoundsGEP2_64(
1062 FunctionGuardArray->getValueType(), FunctionGuardArray, 0, Idx);
1064 if (Options.GatedCallbacks)
1065 CreateGateBranch(F, FunctionGateCmp, IRB);
1066 createRuntimeCall(IRB, SanCovTracePCGuard, GuardPtr)->setCannotMerge();
1067 if (Options.GatedCallbacks) {
1068 IRB.SetInsertPoint(&*IP);
1070 }
1071 }
1072 if (Options.Inline8bitCounters) {
1073 auto CounterPtr = IRB.CreateGEP(
1074 Function8bitCounterArray->getValueType(), Function8bitCounterArray,
1075 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
1076 auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
1077 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
1078 auto Store = IRB.CreateStore(Inc, CounterPtr);
1079 Load->setNoSanitizeMetadata();
1080 Store->setNoSanitizeMetadata();
1081 }
1082 if (Options.InlineBoolFlag) {
1083 auto FlagPtr = IRB.CreateGEP(
1084 FunctionBoolArray->getValueType(), FunctionBoolArray,
1085 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
1086 auto Load = IRB.CreateLoad(Int1Ty, FlagPtr);
1087 auto ThenTerm = SplitBlockAndInsertIfThen(
1088 IRB.CreateIsNull(Load), &*IP, false,
1090 InstrumentationIRBuilder ThenIRB(ThenTerm);
1091 auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr);
1092 if (EntryLoc)
1093 Store->setDebugLoc(EntryLoc);
1094 Load->setNoSanitizeMetadata();
1095 Store->setNoSanitizeMetadata();
1096 }
1097 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
1098 Module *M = F.getParent();
1099 const DataLayout &DL = M->getDataLayout();
1100
1101 if (Options.StackDepthCallbackMin) {
1102 // In callback mode, only add call when stack depth reaches minimum.
1103 int EstimatedStackSize = 0;
1104 // If dynamic alloca found, always add call.
1105 bool HasDynamicAlloc = false;
1106 // Find an insertion point after last "alloca".
1107 llvm::Instruction *InsertBefore = nullptr;
1108
1109 // Examine all allocas in the basic block. since we're too early
1110 // to have results from Intrinsic::frameaddress, we have to manually
1111 // estimate the stack size.
1112 for (auto &I : BB) {
1113 if (auto *AI = dyn_cast<AllocaInst>(&I)) {
1114 // Move potential insertion point past the "alloca".
1115 InsertBefore = AI->getNextNode();
1116
1117 // Make an estimate on the stack usage.
1118 if (auto AllocaSize = AI->getAllocationSize(DL)) {
1119 if (AllocaSize->isFixed())
1120 EstimatedStackSize += AllocaSize->getFixedValue();
1121 else
1122 HasDynamicAlloc = true;
1123 } else {
1124 HasDynamicAlloc = true;
1125 }
1126 }
1127 }
1128
1129 if (HasDynamicAlloc ||
1130 EstimatedStackSize >= Options.StackDepthCallbackMin) {
1131 if (InsertBefore)
1132 IRB.SetInsertPoint(InsertBefore);
1133 auto Call = createRuntimeCall(IRB, SanCovStackDepthCallback);
1134 if (EntryLoc)
1135 Call->setDebugLoc(EntryLoc);
1137 }
1138 } else {
1139 // Check stack depth. If it's the deepest so far, record it.
1140 auto FrameAddrPtr = IRB.CreateIntrinsic(
1141 Intrinsic::frameaddress, IRB.getPtrTy(DL.getAllocaAddrSpace()),
1142 {Constant::getNullValue(Int32Ty)});
1143 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
1144 auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
1145 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
1146 auto ThenTerm = SplitBlockAndInsertIfThen(
1147 IsStackLower, &*IP, false,
1149 InstrumentationIRBuilder ThenIRB(ThenTerm);
1150 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
1151 if (EntryLoc)
1152 Store->setDebugLoc(EntryLoc);
1153 LowestStack->setNoSanitizeMetadata();
1154 Store->setNoSanitizeMetadata();
1155 }
1156 }
1157}
1158
1159std::string
1160ModuleSanitizerCoverage::getSectionName(const std::string &Section) const {
1161 if (TargetTriple.isOSBinFormatCOFF()) {
1162 if (Section == SanCovCountersSectionName)
1163 return ".SCOV$CM";
1164 if (Section == SanCovBoolFlagSectionName)
1165 return ".SCOV$BM";
1166 if (Section == SanCovPCsSectionName)
1167 return ".SCOVP$M";
1168 return ".SCOV$GM"; // For SanCovGuardsSectionName.
1169 }
1170 if (TargetTriple.isOSBinFormatMachO())
1171 return "__DATA,__" + Section;
1172 return "__" + Section;
1173}
1174
1175std::string
1176ModuleSanitizerCoverage::getSectionStart(const std::string &Section) const {
1177 if (TargetTriple.isOSBinFormatMachO())
1178 return "\1section$start$__DATA$__" + Section;
1179 return "__start___" + Section;
1180}
1181
1182std::string
1183ModuleSanitizerCoverage::getSectionEnd(const std::string &Section) const {
1184 if (TargetTriple.isOSBinFormatMachO())
1185 return "\1section$end$__DATA$__" + Section;
1186 return "__stop___" + Section;
1187}
1188
1189void ModuleSanitizerCoverage::createFunctionControlFlow(Function &F) {
1191 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
1192
1193 for (auto &BB : F) {
1194 // blockaddress can not be used on function's entry block.
1195 if (&BB == &F.getEntryBlock())
1196 CFs.push_back((Constant *)IRB.CreatePointerCast(&F, PtrTy));
1197 else
1198 CFs.push_back(
1199 (Constant *)IRB.CreatePointerCast(BlockAddress::get(&BB), PtrTy));
1200
1201 for (auto SuccBB : successors(&BB)) {
1202 assert(SuccBB != &F.getEntryBlock());
1203 CFs.push_back(
1204 (Constant *)IRB.CreatePointerCast(BlockAddress::get(SuccBB), PtrTy));
1205 }
1206
1208
1209 for (auto &Inst : BB) {
1210 if (CallBase *CB = dyn_cast<CallBase>(&Inst)) {
1211 if (CB->isIndirectCall()) {
1212 // TODO(navidem): handle indirect calls, for now mark its existence.
1214 ConstantInt::getAllOnesValue(IntptrTy), PtrTy));
1215 } else {
1216 auto CalledF = CB->getCalledFunction();
1217 if (CalledF && !CalledF->isIntrinsic())
1218 CFs.push_back((Constant *)IRB.CreatePointerCast(CalledF, PtrTy));
1219 }
1220 }
1221 }
1222
1224 }
1225
1226 FunctionCFsArray = CreateFunctionLocalArrayInSection(CFs.size(), F, PtrTy,
1228 FunctionCFsArray->setInitializer(
1229 ConstantArray::get(ArrayType::get(PtrTy, CFs.size()), CFs));
1230 FunctionCFsArray->setConstant(true);
1231}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const IROptions & getOptions(const Module *M)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
static LVOptions Options
Definition LVOptions.cpp:25
SmallVector< MachineOperand, 4 > Cond
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
if(PassOpts->AAPipeline)
const char SanCovCFsSectionName[]
static bool isFullPostDominator(const BasicBlock *BB, const PostDominatorTree &PDT)
const char SanCovTraceConstCmp4[]
const char SanCovBoolFlagSectionName[]
const char SanCov8bitCountersInitName[]
const char SanCovTracePCEntryName[]
const char SanCovLoad8[]
const char SanCovTraceSwitchName[]
const char SanCovTraceCmp1[]
const char SanCovModuleCtorTracePcGuardName[]
const char SanCovCountersSectionName[]
const char SanCovPCsInitName[]
const char SanCovTracePCGuardName[]
const char SanCovModuleCtor8bitCountersName[]
const char SanCovTracePCGuardInitName[]
const char SanCovTraceDiv4[]
static const uint64_t SanCtorAndDtorPriority
const char SanCovBoolFlagInitName[]
const char SanCovTraceGep[]
const char SanCovLoad16[]
const char SanCovTraceConstCmp8[]
const char SanCovGuardsSectionName[]
const char SanCovStore1[]
const char SanCovTraceConstCmp2[]
const char SanCovTraceConstCmp1[]
static bool IsBackEdge(BasicBlock *From, BasicBlock *To, const DominatorTree &DT)
const char SanCovCallbackGateName[]
const char SanCovTraceDiv8[]
const char SanCovLoad4[]
const char SanCovStackDepthCallbackName[]
const char SanCovCFsInitName[]
const char SanCovStore2[]
const char SanCovPCsSectionName[]
const char SanCovLoad1[]
const char SanCovTracePCExitName[]
static bool isFullDominator(const BasicBlock *BB, const DominatorTree &DT)
const char SanCovTraceCmp8[]
const char SanCovCallbackGateSectionName[]
const char SanCovStore16[]
static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree &DT, const SanitizerCoverageOptions &Options)
static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB, const DominatorTree &DT, const PostDominatorTree &PDT, const SanitizerCoverageOptions &Options)
const char SanCovModuleCtorBoolFlagName[]
const char SanCovTraceCmp2[]
const char SanCovStore8[]
const char SanCovTracePCName[]
const char SanCovStore4[]
const char SanCovLoad2[]
const char SanCovTraceCmp4[]
const char SanCovLowestStackName[]
const char SanCovTracePCIndirName[]
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallVector class.
Defines the virtual file system interface vfs::FileSystem.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator end()
Definition BasicBlock.h:452
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrLifetime() const
Returns an iterator to the first instruction in this block that is not a PHINode, a lifetime intrinsi...
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
void setCannotMerge()
static LLVM_ABI CallBase * addOperandBundle(CallBase *CB, uint32_t ID, OperandBundleDef OB, InsertPosition InsertPt=nullptr)
Create a clone of CB with operand bundle OB added.
Value * getCalledOperand() const
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h:1518
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
A debug info location.
Definition DebugLoc.h:126
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
EscapeEnumerator - This is a little algorithm to find all escape points from a function so that "fina...
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
const BasicBlock & getEntryBlock() const
Definition Function.h:803
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
void setLinkage(LinkageTypes LT)
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
void setVisibility(VisibilityTypes V)
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
Analysis pass providing a never-invalidated alias analysis result.
This instruction compares its operands according to the predicate given to the constructor.
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2474
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2373
BasicBlock::iterator GetInsertPoint() const
Definition IRBuilder.h:177
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2314
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:229
LLVM_ABI Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
LLVM_ABI DebugLoc getCurrentDebugLocation() const
Get location information used by debugging information.
Definition IRBuilder.cpp:67
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1913
LLVMContext & getContext() const
Definition IRBuilder.h:178
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
Value * CreateConstInBoundsGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0, uint64_t Idx1, const Twine &Name="")
Definition IRBuilder.h:2078
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1931
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1424
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2309
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition IRBuilder.h:2842
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2640
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:571
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition IRBuilder.h:2399
Value * CreateIsNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg == 0.
Definition IRBuilder.h:2837
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
LLVM_ABI MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
Definition MDBuilder.cpp:48
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
LLVM_ABI bool dominates(const Instruction *I1, const Instruction *I2) const
Return true if I1 dominates I2.
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 & abandon()
Mark an analysis as abandoned.
Definition Analysis.h:171
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI SanitizerCoveragePass(SanitizerCoverageOptions Options=SanitizerCoverageOptions(), IntrusiveRefCntPtr< vfs::FileSystem > VFS=nullptr, const std::vector< std::string > &AllowlistFiles={}, const std::vector< std::string > &BlocklistFiles={})
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This is a utility class used to parse user-provided text files with "special case lists" for code san...
static LLVM_ABI std::unique_ptr< SpecialCaseList > createOrDie(const std::vector< std::string > &Paths, llvm::vfs::FileSystem &FS)
Parses the special case list entries from files.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Multiway switch.
EltTy front() const
unsigned size() const
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
CallInst * Call
constexpr MCPhysReg SP
@ OB
OB - OneByte - Set if this instruction has a one byte opcode.
static constexpr const StringLiteral & getSectionName(DebugSectionKind SectionKind)
Return the name of the section.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
const InstrumentationOptions & getInstrumentationOptions(const LLVMContext &C)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
bool succ_empty(const Instruction *I)
Definition CFG.h:141
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
LLVM_ABI DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
LLVM_ABI FunctionCallee declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type * > InitArgTypes, bool Weak=false)
LLVM_ABI std::pair< Function *, FunctionCallee > createSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs, StringRef VersionCheckName=StringRef(), bool Weak=false)
Creates sanitizer constructor function, and calls sanitizer's init function from it.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
LLVM_ABI Comdat * getOrCreateFunctionComdat(Function &F, Triple &T)
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
OperandBundleDefT< Value * > OperandBundleDef
Definition AutoUpgrade.h:35
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
LLVM_ABI unsigned SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
Loop over all of the edges in the CFG, breaking critical edges as they are found.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
TinyPtrVector< BasicBlock * > ColorVector
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI BasicBlock::iterator PrepareToSplitEntryBlock(BasicBlock &BB, BasicBlock::iterator IP)
Instrumentation passes often insert conditional checks into entry blocks.
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
LLVM_ABI void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Option class for critical edge splitting.
static void ensureDebugInfo(IRBuilder<> &IRB, const Function &F)
enum llvm::SanitizerCoverageOptions::Type CoverageType