LLVM 23.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
14#include "llvm/ADT/ArrayRef.h"
18#include "llvm/IR/Constant.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/DataLayout.h"
21#include "llvm/IR/Dominators.h"
23#include "llvm/IR/Function.h"
25#include "llvm/IR/IRBuilder.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/MDBuilder.h"
30#include "llvm/IR/Module.h"
31#include "llvm/IR/Type.h"
40
41using namespace llvm;
42
43#define DEBUG_TYPE "sancov"
44
45const char SanCovTracePCIndirName[] = "__sanitizer_cov_trace_pc_indir";
46const char SanCovTracePCName[] = "__sanitizer_cov_trace_pc";
47const char SanCovTracePCEntryName[] = "__sanitizer_cov_trace_pc_entry";
48const char SanCovTracePCExitName[] = "__sanitizer_cov_trace_pc_exit";
49const char SanCovTraceCmp1[] = "__sanitizer_cov_trace_cmp1";
50const char SanCovTraceCmp2[] = "__sanitizer_cov_trace_cmp2";
51const char SanCovTraceCmp4[] = "__sanitizer_cov_trace_cmp4";
52const char SanCovTraceCmp8[] = "__sanitizer_cov_trace_cmp8";
53const char SanCovTraceConstCmp1[] = "__sanitizer_cov_trace_const_cmp1";
54const char SanCovTraceConstCmp2[] = "__sanitizer_cov_trace_const_cmp2";
55const char SanCovTraceConstCmp4[] = "__sanitizer_cov_trace_const_cmp4";
56const char SanCovTraceConstCmp8[] = "__sanitizer_cov_trace_const_cmp8";
57const char SanCovLoad1[] = "__sanitizer_cov_load1";
58const char SanCovLoad2[] = "__sanitizer_cov_load2";
59const char SanCovLoad4[] = "__sanitizer_cov_load4";
60const char SanCovLoad8[] = "__sanitizer_cov_load8";
61const char SanCovLoad16[] = "__sanitizer_cov_load16";
62const char SanCovStore1[] = "__sanitizer_cov_store1";
63const char SanCovStore2[] = "__sanitizer_cov_store2";
64const char SanCovStore4[] = "__sanitizer_cov_store4";
65const char SanCovStore8[] = "__sanitizer_cov_store8";
66const char SanCovStore16[] = "__sanitizer_cov_store16";
67const char SanCovTraceDiv4[] = "__sanitizer_cov_trace_div4";
68const char SanCovTraceDiv8[] = "__sanitizer_cov_trace_div8";
69const char SanCovTraceGep[] = "__sanitizer_cov_trace_gep";
70const char SanCovTraceSwitchName[] = "__sanitizer_cov_trace_switch";
72 "sancov.module_ctor_trace_pc_guard";
74 "sancov.module_ctor_8bit_counters";
75const char SanCovModuleCtorBoolFlagName[] = "sancov.module_ctor_bool_flag";
77
78const char SanCovTracePCGuardName[] = "__sanitizer_cov_trace_pc_guard";
79const char SanCovTracePCGuardInitName[] = "__sanitizer_cov_trace_pc_guard_init";
80const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init";
81const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init";
82const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init";
83const char SanCovCFsInitName[] = "__sanitizer_cov_cfs_init";
84
85const char SanCovGuardsSectionName[] = "sancov_guards";
86const char SanCovCountersSectionName[] = "sancov_cntrs";
87const char SanCovBoolFlagSectionName[] = "sancov_bools";
88const char SanCovPCsSectionName[] = "sancov_pcs";
89const char SanCovCFsSectionName[] = "sancov_cfs";
90const char SanCovCallbackGateSectionName[] = "sancov_gate";
91
92const char SanCovStackDepthCallbackName[] = "__sanitizer_cov_stack_depth";
93const char SanCovLowestStackName[] = "__sancov_lowest_stack";
94const char SanCovCallbackGateName[] = "__sancov_should_track";
95
97 "sanitizer-coverage-level",
98 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
99 "3: all blocks and critical edges"),
100 cl::Hidden);
101
102static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
103 cl::desc("Experimental pc tracing"), cl::Hidden);
104
106 "sanitizer-coverage-trace-pc-entry-exit",
107 cl::desc("pc tracing with separate entry/exit callbacks"), cl::Hidden);
108
109static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
110 cl::desc("pc tracing with a guard"),
111 cl::Hidden);
112
113// If true, we create a global variable that contains PCs of all instrumented
114// BBs, put this global into a named section, and pass this section's bounds
115// to __sanitizer_cov_pcs_init.
116// This way the coverage instrumentation does not need to acquire the PCs
117// at run-time. Works with trace-pc-guard, inline-8bit-counters, and
118// inline-bool-flag.
119static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
120 cl::desc("create a static PC table"),
121 cl::Hidden);
122
123static cl::opt<bool>
124 ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
125 cl::desc("increments 8-bit counter for every edge"),
126 cl::Hidden);
127
128static cl::opt<bool>
129 ClSancovDropCtors("sanitizer-coverage-drop-ctors",
130 cl::desc("do not emit module ctors for global counters"),
131 cl::Hidden);
132
133static cl::opt<bool>
134 ClInlineBoolFlag("sanitizer-coverage-inline-bool-flag",
135 cl::desc("sets a boolean flag for every edge"),
136 cl::Hidden);
137
138static cl::opt<bool>
139 ClCMPTracing("sanitizer-coverage-trace-compares",
140 cl::desc("Tracing of CMP and similar instructions"),
141 cl::Hidden);
142
143static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
144 cl::desc("Tracing of DIV instructions"),
145 cl::Hidden);
146
147static cl::opt<bool> ClLoadTracing("sanitizer-coverage-trace-loads",
148 cl::desc("Tracing of load instructions"),
149 cl::Hidden);
150
151static cl::opt<bool> ClStoreTracing("sanitizer-coverage-trace-stores",
152 cl::desc("Tracing of store instructions"),
153 cl::Hidden);
154
155static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
156 cl::desc("Tracing of GEP instructions"),
157 cl::Hidden);
158
159static cl::opt<bool>
160 ClPruneBlocks("sanitizer-coverage-prune-blocks",
161 cl::desc("Reduce the number of instrumented blocks"),
162 cl::Hidden, cl::init(true));
163
164static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
165 cl::desc("max stack depth tracing"),
166 cl::Hidden);
167
169 "sanitizer-coverage-stack-depth-callback-min",
170 cl::desc("max stack depth tracing should use callback and only when "
171 "stack depth more than specified"),
172 cl::Hidden);
173
174static cl::opt<bool>
175 ClCollectCF("sanitizer-coverage-control-flow",
176 cl::desc("collect control flow for each function"), cl::Hidden);
177
179 "sanitizer-coverage-gated-trace-callbacks",
180 cl::desc("Gate the invocation of the tracing callbacks on a global variable"
181 ". Currently only supported for trace-pc-guard and trace-cmp."),
182 cl::Hidden, cl::init(false));
183
184namespace {
185
186SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
188 switch (LegacyCoverageLevel) {
189 case 0:
191 break;
192 case 1:
194 break;
195 case 2:
197 break;
198 case 3:
200 break;
201 case 4:
203 Res.IndirectCalls = true;
204 break;
205 }
206 return Res;
207}
208
210 // Sets CoverageType and IndirectCalls.
211 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
212 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
213 Options.IndirectCalls |= CLOpts.IndirectCalls;
214 Options.TraceCmp |= ClCMPTracing;
215 Options.TraceDiv |= ClDIVTracing;
216 Options.TraceGep |= ClGEPTracing;
217 Options.TracePC |= ClTracePC;
218 Options.TracePCEntryExit |= ClTracePCEntryExit;
219 Options.TracePCGuard |= ClTracePCGuard;
220 Options.Inline8bitCounters |= ClInline8bitCounters;
221 Options.InlineBoolFlag |= ClInlineBoolFlag;
222 Options.PCTable |= ClCreatePCTable;
223 Options.NoPrune |= !ClPruneBlocks;
224 Options.StackDepth |= ClStackDepth;
225 Options.StackDepthCallbackMin = std::max(Options.StackDepthCallbackMin,
226 ClStackDepthCallbackMin.getValue());
227 Options.TraceLoads |= ClLoadTracing;
228 Options.TraceStores |= ClStoreTracing;
229 Options.GatedCallbacks |= ClGatedCallbacks;
230 if (!Options.TracePCGuard && !Options.TracePC && !Options.TracePCEntryExit &&
231 !Options.Inline8bitCounters && !Options.StackDepth &&
232 !Options.InlineBoolFlag && !Options.TraceLoads && !Options.TraceStores)
233 Options.TracePCGuard = true; // TracePCGuard is default.
234 Options.CollectControlFlow |= ClCollectCF;
235 return Options;
236}
237
238class ModuleSanitizerCoverage {
239public:
240 using DomTreeCallback = function_ref<const DominatorTree &(Function &F)>;
241 using PostDomTreeCallback =
242 function_ref<const PostDominatorTree &(Function &F)>;
243
244 ModuleSanitizerCoverage(Module &M, DomTreeCallback DTCallback,
245 PostDomTreeCallback PDTCallback,
246 const SanitizerCoverageOptions &Options,
247 const SpecialCaseList *Allowlist,
248 const SpecialCaseList *Blocklist)
249 : M(M), DTCallback(DTCallback), PDTCallback(PDTCallback),
250 Options(Options), Allowlist(Allowlist), Blocklist(Blocklist) {}
251
252 bool instrumentModule();
253
254private:
255 void createFunctionControlFlow(Function &F);
256 void instrumentFunction(Function &F);
257 void InjectCoverageForIndirectCalls(Function &F,
258 ArrayRef<Instruction *> IndirCalls);
259 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets,
260 Value *&FunctionGateCmp);
261 void InjectTraceForDiv(Function &F,
262 ArrayRef<BinaryOperator *> DivTraceTargets);
263 void InjectTraceForGep(Function &F,
264 ArrayRef<GetElementPtrInst *> GepTraceTargets);
265 void InjectTraceForLoadsAndStores(Function &F, ArrayRef<LoadInst *> Loads,
266 ArrayRef<StoreInst *> Stores);
267 void InjectTraceForExits(Function &F);
268 void InjectTraceForSwitch(Function &F,
269 ArrayRef<Instruction *> SwitchTraceTargets,
270 Value *&FunctionGateCmp);
271 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
272 Value *&FunctionGateCmp, bool IsLeafFunc);
273 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
274 Function &F, Type *Ty,
275 const char *Section);
276 GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
277 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
278 Instruction *CreateGateBranch(Function &F, Value *&FunctionGateCmp,
279 Instruction *I);
280 Value *CreateFunctionLocalGateCmp(IRBuilder<> &IRB);
281 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
282 Value *&FunctionGateCmp, bool IsLeafFunc);
283 Function *CreateInitCallsForSections(Module &M, const char *CtorName,
284 const char *InitFunctionName, Type *Ty,
285 const char *Section);
286 std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
287 Type *Ty);
288
289 std::string getSectionName(const std::string &Section) const;
290 std::string getSectionStart(const std::string &Section) const;
291 std::string getSectionEnd(const std::string &Section) const;
292
293 Module &M;
294 DomTreeCallback DTCallback;
295 PostDomTreeCallback PDTCallback;
296
297 FunctionCallee SanCovStackDepthCallback;
298 FunctionCallee SanCovTracePCIndir;
299 FunctionCallee SanCovTracePC, SanCovTracePCGuard;
300 FunctionCallee SanCovTracePCEntry, SanCovTracePCExit;
301 std::array<FunctionCallee, 4> SanCovTraceCmpFunction;
302 std::array<FunctionCallee, 4> SanCovTraceConstCmpFunction;
303 std::array<FunctionCallee, 5> SanCovLoadFunction;
304 std::array<FunctionCallee, 5> SanCovStoreFunction;
305 std::array<FunctionCallee, 2> SanCovTraceDivFunction;
306 FunctionCallee SanCovTraceGepFunction;
307 FunctionCallee SanCovTraceSwitchFunction;
308 GlobalVariable *SanCovLowestStack;
309 GlobalVariable *SanCovCallbackGate;
310 Type *PtrTy, *IntptrTy, *Int64Ty, *Int32Ty, *Int16Ty, *Int8Ty, *Int1Ty;
311 Module *CurModule;
312 Triple TargetTriple;
313 LLVMContext *C;
314 const DataLayout *DL;
315
316 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
317 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
318 GlobalVariable *FunctionBoolArray; // for inline-bool-flag.
319 GlobalVariable *FunctionPCsArray; // for pc-table.
320 GlobalVariable *FunctionCFsArray; // for control flow table
321 SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
322 SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
323
324 SanitizerCoverageOptions Options;
325
326 const SpecialCaseList *Allowlist;
327 const SpecialCaseList *Blocklist;
328};
329} // namespace
330
333 const std::vector<std::string> &AllowlistFiles,
334 const std::vector<std::string> &BlocklistFiles)
335 : Options(std::move(Options)),
336 VFS(VFS ? std::move(VFS) : vfs::getRealFileSystem()) {
337 if (AllowlistFiles.size() > 0)
338 Allowlist = SpecialCaseList::createOrDie(AllowlistFiles, *this->VFS);
339 if (BlocklistFiles.size() > 0)
340 Blocklist = SpecialCaseList::createOrDie(BlocklistFiles, *this->VFS);
341}
342
345 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
346 auto DTCallback = [&FAM](Function &F) -> const DominatorTree & {
347 return FAM.getResult<DominatorTreeAnalysis>(F);
348 };
349 auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree & {
350 return FAM.getResult<PostDominatorTreeAnalysis>(F);
351 };
352 ModuleSanitizerCoverage ModuleSancov(M, DTCallback, PDTCallback,
353 OverrideFromCL(Options), Allowlist.get(),
354 Blocklist.get());
355 if (!ModuleSancov.instrumentModule())
356 return PreservedAnalyses::all();
357
359 // GlobalsAA is considered stateless and does not get invalidated unless
360 // explicitly invalidated; PreservedAnalyses::none() is not enough. Sanitizers
361 // make changes that require GlobalsAA to be invalidated.
362 PA.abandon<GlobalsAA>();
363 return PA;
364}
365
366std::pair<Value *, Value *>
367ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section,
368 Type *Ty) {
369 // Use ExternalWeak so that if all sections are discarded due to section
370 // garbage collection, the linker will not report undefined symbol errors.
371 // Windows defines the start/stop symbols in compiler-rt so no need for
372 // ExternalWeak.
373 GlobalValue::LinkageTypes Linkage = TargetTriple.isOSBinFormatCOFF()
376 GlobalVariable *SecStart = new GlobalVariable(M, Ty, false, Linkage, nullptr,
377 getSectionStart(Section));
379 GlobalVariable *SecEnd = new GlobalVariable(M, Ty, false, Linkage, nullptr,
380 getSectionEnd(Section));
382 IRBuilder<> IRB(M.getContext());
383 if (!TargetTriple.isOSBinFormatCOFF())
384 return std::make_pair(SecStart, SecEnd);
385
386 // Account for the fact that on windows-msvc __start_* symbols actually
387 // point to a uint64_t before the start of the array.
388 auto GEP =
389 IRB.CreatePtrAdd(SecStart, ConstantInt::get(IntptrTy, sizeof(uint64_t)));
390 return std::make_pair(GEP, SecEnd);
391}
392
393Function *ModuleSanitizerCoverage::CreateInitCallsForSections(
394 Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
395 const char *Section) {
397 return nullptr;
398 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
399 auto SecStart = SecStartEnd.first;
400 auto SecEnd = SecStartEnd.second;
401 Function *CtorFunc;
402 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
403 M, CtorName, InitFunctionName, {PtrTy, PtrTy}, {SecStart, SecEnd});
404 assert(CtorFunc->getName() == CtorName);
405
406 if (TargetTriple.supportsCOMDAT()) {
407 // Use comdat to dedup CtorFunc.
408 CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
409 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
410 } else {
412 }
413
414 if (TargetTriple.isOSBinFormatCOFF()) {
415 // In COFF files, if the contructors are set as COMDAT (they are because
416 // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
417 // functions and data) is used, the constructors get stripped. To prevent
418 // this, give the constructors weak ODR linkage and ensure the linker knows
419 // to include the sancov constructor. This way the linker can deduplicate
420 // the constructors but always leave one copy.
422 }
423 return CtorFunc;
424}
425
426bool ModuleSanitizerCoverage::instrumentModule() {
428 return false;
429 if (Allowlist &&
430 !Allowlist->inSection("coverage", "src", M.getSourceFileName()))
431 return false;
432 if (Blocklist &&
433 Blocklist->inSection("coverage", "src", M.getSourceFileName()))
434 return false;
435 C = &(M.getContext());
436 DL = &M.getDataLayout();
437 CurModule = &M;
438 TargetTriple = M.getTargetTriple();
439 FunctionGuardArray = nullptr;
440 Function8bitCounterArray = nullptr;
441 FunctionBoolArray = nullptr;
442 FunctionPCsArray = nullptr;
443 FunctionCFsArray = nullptr;
444 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
445 PtrTy = PointerType::getUnqual(*C);
446 Type *VoidTy = Type::getVoidTy(*C);
447 IRBuilder<> IRB(*C);
448 Int64Ty = IRB.getInt64Ty();
449 Int32Ty = IRB.getInt32Ty();
450 Int16Ty = IRB.getInt16Ty();
451 Int8Ty = IRB.getInt8Ty();
452 Int1Ty = IRB.getInt1Ty();
453
454 SanCovTracePCIndir =
455 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
456 // Make sure smaller parameters are zero-extended to i64 if required by the
457 // target ABI.
458 AttributeList SanCovTraceCmpZeroExtAL;
459 SanCovTraceCmpZeroExtAL =
460 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
461 SanCovTraceCmpZeroExtAL =
462 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
463
464 SanCovTraceCmpFunction[0] =
465 M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
466 IRB.getInt8Ty(), IRB.getInt8Ty());
467 SanCovTraceCmpFunction[1] =
468 M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
469 IRB.getInt16Ty(), IRB.getInt16Ty());
470 SanCovTraceCmpFunction[2] =
471 M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
472 IRB.getInt32Ty(), IRB.getInt32Ty());
473 SanCovTraceCmpFunction[3] =
474 M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
475
476 SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
477 SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
478 SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
479 SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
480 SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
481 SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
482 SanCovTraceConstCmpFunction[3] =
483 M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
484
485 // Loads.
486 SanCovLoadFunction[0] = M.getOrInsertFunction(SanCovLoad1, VoidTy, PtrTy);
487 SanCovLoadFunction[1] = M.getOrInsertFunction(SanCovLoad2, VoidTy, PtrTy);
488 SanCovLoadFunction[2] = M.getOrInsertFunction(SanCovLoad4, VoidTy, PtrTy);
489 SanCovLoadFunction[3] = M.getOrInsertFunction(SanCovLoad8, VoidTy, PtrTy);
490 SanCovLoadFunction[4] = M.getOrInsertFunction(SanCovLoad16, VoidTy, PtrTy);
491 // Stores.
492 SanCovStoreFunction[0] = M.getOrInsertFunction(SanCovStore1, VoidTy, PtrTy);
493 SanCovStoreFunction[1] = M.getOrInsertFunction(SanCovStore2, VoidTy, PtrTy);
494 SanCovStoreFunction[2] = M.getOrInsertFunction(SanCovStore4, VoidTy, PtrTy);
495 SanCovStoreFunction[3] = M.getOrInsertFunction(SanCovStore8, VoidTy, PtrTy);
496 SanCovStoreFunction[4] = M.getOrInsertFunction(SanCovStore16, VoidTy, PtrTy);
497
498 {
499 AttributeList AL;
500 AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
501 SanCovTraceDivFunction[0] =
502 M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
503 }
504 SanCovTraceDivFunction[1] =
505 M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
506 SanCovTraceGepFunction =
507 M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
508 SanCovTraceSwitchFunction =
509 M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, PtrTy);
510
511 SanCovLowestStack = M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
512 if (SanCovLowestStack->getValueType() != IntptrTy) {
513 C->emitError(StringRef("'") + SanCovLowestStackName +
514 "' should not be declared by the user");
515 return true;
516 }
517 SanCovLowestStack->setThreadLocalMode(
519 if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
520 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
521
522 if (Options.GatedCallbacks) {
523 if (!Options.TracePCGuard && !Options.TraceCmp) {
524 C->emitError(StringRef("'") + ClGatedCallbacks.ArgStr +
525 "' is only supported with trace-pc-guard or trace-cmp");
526 return true;
527 }
528
529 SanCovCallbackGate = cast<GlobalVariable>(
530 M.getOrInsertGlobal(SanCovCallbackGateName, Int64Ty));
531 SanCovCallbackGate->setSection(
533 SanCovCallbackGate->setInitializer(Constant::getNullValue(Int64Ty));
534 SanCovCallbackGate->setLinkage(GlobalVariable::LinkOnceAnyLinkage);
535 SanCovCallbackGate->setVisibility(GlobalVariable::HiddenVisibility);
536 appendToCompilerUsed(M, SanCovCallbackGate);
537 }
538
539 SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
540 SanCovTracePCEntry = M.getOrInsertFunction(SanCovTracePCEntryName, VoidTy);
541 SanCovTracePCExit = M.getOrInsertFunction(SanCovTracePCExitName, VoidTy);
542 SanCovTracePCGuard =
543 M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, PtrTy);
544
545 SanCovStackDepthCallback =
546 M.getOrInsertFunction(SanCovStackDepthCallbackName, VoidTy);
547
548 for (auto &F : M)
549 instrumentFunction(F);
550
551 Function *Ctor = nullptr;
552
553 if (FunctionGuardArray)
554 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
557 if (Function8bitCounterArray)
558 Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
561 if (FunctionBoolArray) {
562 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName,
565 }
566 if (Ctor && Options.PCTable) {
567 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrTy);
568 FunctionCallee InitFunction =
570 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
571 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
572 }
573
574 if (Ctor && Options.CollectControlFlow) {
575 auto SecStartEnd = CreateSecStartEnd(M, SanCovCFsSectionName, IntptrTy);
576 FunctionCallee InitFunction =
578 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
579 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
580 }
581
582 appendToUsed(M, GlobalsToAppendToUsed);
583 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
584 return true;
585}
586
587// True if block has successors and it dominates all of them.
588static bool isFullDominator(const BasicBlock *BB, const DominatorTree &DT) {
589 if (succ_empty(BB))
590 return false;
591
592 return llvm::all_of(successors(BB), [&](const BasicBlock *SUCC) {
593 return DT.dominates(BB, SUCC);
594 });
595}
596
597// True if block has predecessors and it postdominates all of them.
598static bool isFullPostDominator(const BasicBlock *BB,
599 const PostDominatorTree &PDT) {
600 if (pred_empty(BB))
601 return false;
602
603 return llvm::all_of(predecessors(BB), [&](const BasicBlock *PRED) {
604 return PDT.dominates(BB, PRED);
605 });
606}
607
608static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
609 const DominatorTree &DT,
610 const PostDominatorTree &PDT,
612 // Don't insert coverage for blocks containing nothing but unreachable: we
613 // will never call __sanitizer_cov() for them, so counting them in
614 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
615 // percentage. Also, unreachable instructions frequently have no debug
616 // locations.
618 return false;
619
620 // Don't insert coverage into blocks without a valid insertion point
621 // (catchswitch blocks).
622 if (BB->getFirstInsertionPt() == BB->end())
623 return false;
624
625 if (Options.NoPrune || &F.getEntryBlock() == BB)
626 return true;
627
629 &F.getEntryBlock() != BB)
630 return false;
631
632 // Do not instrument full dominators, or full post-dominators with multiple
633 // predecessors.
634 return !isFullDominator(BB, DT) &&
635 !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
636}
637
638// Returns true iff From->To is a backedge.
639// A twist here is that we treat From->To as a backedge if
640// * To dominates From or
641// * To->UniqueSuccessor dominates From
642static bool IsBackEdge(BasicBlock *From, BasicBlock *To,
643 const DominatorTree &DT) {
644 if (DT.dominates(To, From))
645 return true;
646 if (auto Next = To->getUniqueSuccessor())
647 if (DT.dominates(Next, From))
648 return true;
649 return false;
650}
651
652// Prunes uninteresting Cmp instrumentation:
653// * CMP instructions that feed into loop backedge branch.
654//
655// Note that Cmp pruning is controlled by the same flag as the
656// BB pruning.
657static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree &DT,
659 if (!Options.NoPrune)
660 if (CMP->hasOneUse())
661 if (auto BR = dyn_cast<CondBrInst>(CMP->user_back()))
662 for (BasicBlock *B : BR->successors())
663 if (IsBackEdge(BR->getParent(), B, DT))
664 return false;
665 return true;
666}
667
668void ModuleSanitizerCoverage::instrumentFunction(Function &F) {
669 if (F.empty())
670 return;
671 if (F.getName().contains(".module_ctor"))
672 return; // Should not instrument sanitizer init functions.
673 if (F.getName().starts_with("__sanitizer_"))
674 return; // Don't instrument __sanitizer_* callbacks.
675 // Don't touch available_externally functions, their actual body is elewhere.
676 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
677 return;
678 // Don't instrument MSVC CRT configuration helpers. They may run before normal
679 // initialization.
680 if (F.getName() == "__local_stdio_printf_options" ||
681 F.getName() == "__local_stdio_scanf_options")
682 return;
683 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
684 return;
685 // Don't instrument functions using SEH for now. Splitting basic blocks like
686 // we do for coverage breaks WinEHPrepare.
687 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
688 if (F.hasPersonalityFn() &&
690 return;
691 if (Allowlist && !Allowlist->inSection("coverage", "fun", F.getName()))
692 return;
693 if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName()))
694 return;
695 // Do not apply any instrumentation for naked functions.
696 if (F.hasFnAttribute(Attribute::Naked))
697 return;
698 if (F.hasFnAttribute(Attribute::NoSanitizeCoverage))
699 return;
700 if (F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation))
701 return;
702 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge) {
704 F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
705 }
707 SmallVector<BasicBlock *, 16> BlocksToInstrument;
708 SmallVector<Instruction *, 8> CmpTraceTargets;
709 SmallVector<Instruction *, 8> SwitchTraceTargets;
710 SmallVector<BinaryOperator *, 8> DivTraceTargets;
714
715 const DominatorTree &DT = DTCallback(F);
716 const PostDominatorTree &PDT = PDTCallback(F);
717 bool IsLeafFunc = true;
718
719 for (auto &BB : F) {
720 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
721 BlocksToInstrument.push_back(&BB);
722 for (auto &Inst : BB) {
723 if (Options.IndirectCalls) {
724 CallBase *CB = dyn_cast<CallBase>(&Inst);
725 if (CB && CB->isIndirectCall())
726 IndirCalls.push_back(&Inst);
727 }
728 if (Options.TraceCmp) {
729 if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
730 if (IsInterestingCmp(CMP, DT, Options))
731 CmpTraceTargets.push_back(&Inst);
732 if (isa<SwitchInst>(&Inst))
733 SwitchTraceTargets.push_back(&Inst);
734 }
735 if (Options.TraceDiv)
737 if (BO->getOpcode() == Instruction::SDiv ||
738 BO->getOpcode() == Instruction::UDiv)
739 DivTraceTargets.push_back(BO);
740 if (Options.TraceGep)
742 GepTraceTargets.push_back(GEP);
743 if (Options.TraceLoads)
744 if (LoadInst *LI = dyn_cast<LoadInst>(&Inst))
745 Loads.push_back(LI);
746 if (Options.TraceStores)
747 if (StoreInst *SI = dyn_cast<StoreInst>(&Inst))
748 Stores.push_back(SI);
749 if (Options.StackDepth)
750 if (isa<InvokeInst>(Inst) ||
751 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
752 IsLeafFunc = false;
753 }
754 }
755
756 if (Options.CollectControlFlow)
757 createFunctionControlFlow(F);
758
759 Value *FunctionGateCmp = nullptr;
760 InjectCoverage(F, BlocksToInstrument, FunctionGateCmp, IsLeafFunc);
761 InjectCoverageForIndirectCalls(F, IndirCalls);
762 InjectTraceForCmp(F, CmpTraceTargets, FunctionGateCmp);
763 InjectTraceForSwitch(F, SwitchTraceTargets, FunctionGateCmp);
764 InjectTraceForDiv(F, DivTraceTargets);
765 InjectTraceForGep(F, GepTraceTargets);
766 InjectTraceForLoadsAndStores(F, Loads, Stores);
767
768 if (Options.TracePCEntryExit)
769 InjectTraceForExits(F);
770}
771
772GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection(
773 size_t NumElements, Function &F, Type *Ty, const char *Section) {
774 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
775 auto Array = new GlobalVariable(
776 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
777 Constant::getNullValue(ArrayTy), "__sancov_gen_");
778
779 if (TargetTriple.supportsCOMDAT() &&
780 (F.hasComdat() || TargetTriple.isOSBinFormatELF() || !F.isInterposable()))
781 if (auto Comdat = getOrCreateFunctionComdat(F, TargetTriple))
782 Array->setComdat(Comdat);
783 Array->setSection(getSectionName(Section));
784 Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedValue()));
785
786 // sancov_pcs parallels the other metadata section(s). Optimizers (e.g.
787 // GlobalOpt/ConstantMerge) may not discard sancov_pcs and the other
788 // section(s) as a unit, so we conservatively retain all unconditionally in
789 // the compiler.
790 //
791 // With comdat (COFF/ELF), the linker can guarantee the associated sections
792 // will be retained or discarded as a unit, so llvm.compiler.used is
793 // sufficient. Otherwise, conservatively make all of them retained by the
794 // linker.
795 if (Array->hasComdat())
796 GlobalsToAppendToCompilerUsed.push_back(Array);
797 else
798 GlobalsToAppendToUsed.push_back(Array);
799
800 return Array;
801}
802
804ModuleSanitizerCoverage::CreatePCArray(Function &F,
805 ArrayRef<BasicBlock *> AllBlocks) {
806 size_t N = AllBlocks.size();
807 assert(N);
809 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
810 for (size_t i = 0; i < N; i++) {
811 if (&F.getEntryBlock() == AllBlocks[i]) {
812 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, PtrTy));
813 PCs.push_back(
814 (Constant *)IRB.CreateIntToPtr(ConstantInt::get(IntptrTy, 1), PtrTy));
815 } else {
816 PCs.push_back((Constant *)IRB.CreatePointerCast(
817 BlockAddress::get(AllBlocks[i]), PtrTy));
819 }
820 }
821 auto *PCArray =
822 CreateFunctionLocalArrayInSection(N * 2, F, PtrTy, SanCovPCsSectionName);
823 PCArray->setInitializer(
824 ConstantArray::get(ArrayType::get(PtrTy, N * 2), PCs));
825 PCArray->setConstant(true);
826
827 return PCArray;
828}
829
830void ModuleSanitizerCoverage::CreateFunctionLocalArrays(
831 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
832 if (Options.TracePCGuard)
833 FunctionGuardArray = CreateFunctionLocalArrayInSection(
834 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
835
836 if (Options.Inline8bitCounters)
837 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
838 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
839 if (Options.InlineBoolFlag)
840 FunctionBoolArray = CreateFunctionLocalArrayInSection(
841 AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName);
842
843 if (Options.PCTable)
844 FunctionPCsArray = CreatePCArray(F, AllBlocks);
845}
846
847Value *ModuleSanitizerCoverage::CreateFunctionLocalGateCmp(IRBuilder<> &IRB) {
848 auto Load = IRB.CreateLoad(Int64Ty, SanCovCallbackGate);
849 Load->setNoSanitizeMetadata();
850 auto Cmp = IRB.CreateIsNotNull(Load);
851 Cmp->setName("sancov gate cmp");
852 return Cmp;
853}
854
855Instruction *ModuleSanitizerCoverage::CreateGateBranch(Function &F,
856 Value *&FunctionGateCmp,
857 Instruction *IP) {
858 if (!FunctionGateCmp) {
859 // Create this in the entry block
860 BasicBlock &BB = F.getEntryBlock();
862 IP = PrepareToSplitEntryBlock(BB, IP);
863 IRBuilder<> EntryIRB(&*IP);
864 FunctionGateCmp = CreateFunctionLocalGateCmp(EntryIRB);
865 }
866 // Set the branch weights in order to minimize the price paid when the
867 // gate is turned off, allowing the default enablement of this
868 // instrumentation with as little of a performance cost as possible
869 auto Weights = MDBuilder(*C).createBranchWeights(1, 100000);
870 return SplitBlockAndInsertIfThen(FunctionGateCmp, IP, false, Weights);
871}
872
873bool ModuleSanitizerCoverage::InjectCoverage(Function &F,
874 ArrayRef<BasicBlock *> AllBlocks,
875 Value *&FunctionGateCmp,
876 bool IsLeafFunc) {
877 if (AllBlocks.empty())
878 return false;
879 CreateFunctionLocalArrays(F, AllBlocks);
880 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
881 InjectCoverageAtBlock(F, *AllBlocks[i], i, FunctionGateCmp, IsLeafFunc);
882
883 return true;
884}
885
886// On every indirect call we call a run-time function
887// __sanitizer_cov_indir_call* with two parameters:
888// - callee address,
889// - global cache array that contains CacheSize pointers (zero-initialized).
890// The cache is used to speed up recording the caller-callee pairs.
891// The address of the caller is passed implicitly via caller PC.
892// CacheSize is encoded in the name of the run-time function.
893void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls(
894 Function &F, ArrayRef<Instruction *> IndirCalls) {
895 if (IndirCalls.empty())
896 return;
897 assert(Options.TracePC || Options.TracePCEntryExit || Options.TracePCGuard ||
898 Options.Inline8bitCounters || Options.InlineBoolFlag);
899 for (auto *I : IndirCalls) {
901 CallBase &CB = cast<CallBase>(*I);
903 if (isa<InlineAsm>(Callee))
904 continue;
905 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
906 }
907}
908
909// For every switch statement we insert a call:
910// __sanitizer_cov_trace_switch(CondValue,
911// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
912
913void ModuleSanitizerCoverage::InjectTraceForSwitch(
914 Function &F, ArrayRef<Instruction *> SwitchTraceTargets,
915 Value *&FunctionGateCmp) {
916 for (auto *I : SwitchTraceTargets) {
919 SmallVector<Constant *, 16> Initializers;
920 Value *Cond = SI->getCondition();
921 if (Cond->getType()->getScalarSizeInBits() >
922 Int64Ty->getScalarSizeInBits())
923 continue;
924 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
925 Initializers.push_back(
926 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
927 if (Cond->getType()->getScalarSizeInBits() <
928 Int64Ty->getScalarSizeInBits())
929 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
930 for (auto It : SI->cases()) {
931 ConstantInt *C = It.getCaseValue();
932 if (C->getType()->getScalarSizeInBits() < 64)
933 C = ConstantInt::get(C->getContext(), C->getValue().zext(64));
934 Initializers.push_back(C);
935 }
936 llvm::sort(drop_begin(Initializers, 2),
937 [](const Constant *A, const Constant *B) {
938 return cast<ConstantInt>(A)->getLimitedValue() <
939 cast<ConstantInt>(B)->getLimitedValue();
940 });
941 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
943 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
944 ConstantArray::get(ArrayOfInt64Ty, Initializers),
945 "__sancov_gen_cov_switch_values");
946 if (Options.GatedCallbacks) {
947 auto GateBranch = CreateGateBranch(F, FunctionGateCmp, I);
948 IRBuilder<> GateIRB(GateBranch);
949 GateIRB.CreateCall(SanCovTraceSwitchFunction, {Cond, GV});
950 } else {
951 IRB.CreateCall(SanCovTraceSwitchFunction, {Cond, GV});
952 }
953 }
954 }
955}
956
957void ModuleSanitizerCoverage::InjectTraceForDiv(
958 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
959 for (auto *BO : DivTraceTargets) {
961 Value *A1 = BO->getOperand(1);
962 if (isa<ConstantInt>(A1))
963 continue;
964 if (!A1->getType()->isIntegerTy())
965 continue;
966 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
967 int CallbackIdx = TypeSize == 32 ? 0 : TypeSize == 64 ? 1 : -1;
968 if (CallbackIdx < 0)
969 continue;
970 auto Ty = Type::getIntNTy(*C, TypeSize);
971 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
972 {IRB.CreateIntCast(A1, Ty, true)});
973 }
974}
975
976void ModuleSanitizerCoverage::InjectTraceForGep(
977 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
978 for (auto *GEP : GepTraceTargets) {
980 for (Use &Idx : GEP->indices())
981 if (!isa<ConstantInt>(Idx) && Idx->getType()->isIntegerTy())
982 IRB.CreateCall(SanCovTraceGepFunction,
983 {IRB.CreateIntCast(Idx, IntptrTy, true)});
984 }
985}
986
987void ModuleSanitizerCoverage::InjectTraceForLoadsAndStores(
989 auto CallbackIdx = [&](Type *ElementTy) -> int {
990 uint64_t TypeSize = DL->getTypeStoreSizeInBits(ElementTy);
991 return TypeSize == 8 ? 0
992 : TypeSize == 16 ? 1
993 : TypeSize == 32 ? 2
994 : TypeSize == 64 ? 3
995 : TypeSize == 128 ? 4
996 : -1;
997 };
998 for (auto *LI : Loads) {
1000 auto Ptr = LI->getPointerOperand();
1001 int Idx = CallbackIdx(LI->getType());
1002 if (Idx < 0)
1003 continue;
1004 IRB.CreateCall(SanCovLoadFunction[Idx], Ptr);
1005 }
1006 for (auto *SI : Stores) {
1008 auto Ptr = SI->getPointerOperand();
1009 int Idx = CallbackIdx(SI->getValueOperand()->getType());
1010 if (Idx < 0)
1011 continue;
1012 IRB.CreateCall(SanCovStoreFunction[Idx], Ptr);
1013 }
1014}
1015
1016void ModuleSanitizerCoverage::InjectTraceForExits(Function &F) {
1017 EscapeEnumerator EE(F, "sancov_exit");
1018 while (IRBuilder<> *AtExit = EE.Next()) {
1020 AtExit->CreateCall(SanCovTracePCExit, {})
1021 ->setTailCallKind(CallInst::TCK_NoTail);
1022 }
1023}
1024
1025void ModuleSanitizerCoverage::InjectTraceForCmp(
1026 Function &F, ArrayRef<Instruction *> CmpTraceTargets,
1027 Value *&FunctionGateCmp) {
1028 for (auto *I : CmpTraceTargets) {
1029 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
1030 InstrumentationIRBuilder IRB(ICMP);
1031 Value *A0 = ICMP->getOperand(0);
1032 Value *A1 = ICMP->getOperand(1);
1033 if (!A0->getType()->isIntegerTy())
1034 continue;
1035 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
1036 int CallbackIdx = TypeSize == 8 ? 0
1037 : TypeSize == 16 ? 1
1038 : TypeSize == 32 ? 2
1039 : TypeSize == 64 ? 3
1040 : -1;
1041 if (CallbackIdx < 0)
1042 continue;
1043 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
1044 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
1045 bool FirstIsConst = isa<ConstantInt>(A0);
1046 bool SecondIsConst = isa<ConstantInt>(A1);
1047 // If both are const, then we don't need such a comparison.
1048 if (FirstIsConst && SecondIsConst)
1049 continue;
1050 // If only one is const, then make it the first callback argument.
1051 if (FirstIsConst || SecondIsConst) {
1052 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
1053 if (SecondIsConst)
1054 std::swap(A0, A1);
1055 }
1056
1057 auto Ty = Type::getIntNTy(*C, TypeSize);
1058 if (Options.GatedCallbacks) {
1059 auto GateBranch = CreateGateBranch(F, FunctionGateCmp, I);
1060 IRBuilder<> GateIRB(GateBranch);
1061 GateIRB.CreateCall(CallbackFunc, {GateIRB.CreateIntCast(A0, Ty, true),
1062 GateIRB.CreateIntCast(A1, Ty, true)});
1063 } else {
1064 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
1065 IRB.CreateIntCast(A1, Ty, true)});
1066 }
1067 }
1068 }
1069}
1070
1071void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
1072 size_t Idx,
1073 Value *&FunctionGateCmp,
1074 bool IsLeafFunc) {
1076 bool IsEntryBB = &BB == &F.getEntryBlock();
1077 DebugLoc EntryLoc;
1078 if (IsEntryBB) {
1079 if (auto SP = F.getSubprogram())
1080 EntryLoc = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
1081 // Keep static allocas and llvm.localescape calls in the entry block. Even
1082 // if we aren't splitting the block, it's nice for allocas to be before
1083 // calls.
1084 IP = PrepareToSplitEntryBlock(BB, IP);
1085 }
1086
1087 InstrumentationIRBuilder IRB(&*IP);
1088 if (EntryLoc)
1089 IRB.SetCurrentDebugLocation(EntryLoc);
1090 if (Options.TracePC || (IsEntryBB && Options.TracePCEntryExit)) {
1091 FunctionCallee Callee = IsEntryBB && Options.TracePCEntryExit
1092 ? SanCovTracePCEntry
1093 : SanCovTracePC;
1094 IRB.CreateCall(Callee)
1095 ->setCannotMerge(); // gets the PC using GET_CALLER_PC.
1096 }
1097 if (Options.TracePCGuard) {
1098 auto GuardPtr = IRB.CreateConstInBoundsGEP2_64(
1099 FunctionGuardArray->getValueType(), FunctionGuardArray, 0, Idx);
1100 if (Options.GatedCallbacks) {
1101 Instruction *I = &*IP;
1102 auto GateBranch = CreateGateBranch(F, FunctionGateCmp, I);
1103 IRBuilder<> GateIRB(GateBranch);
1104 GateIRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge();
1105 } else {
1106 IRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge();
1107 }
1108 }
1109 if (Options.Inline8bitCounters) {
1110 auto CounterPtr = IRB.CreateGEP(
1111 Function8bitCounterArray->getValueType(), Function8bitCounterArray,
1112 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
1113 auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
1114 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
1115 auto Store = IRB.CreateStore(Inc, CounterPtr);
1116 Load->setNoSanitizeMetadata();
1117 Store->setNoSanitizeMetadata();
1118 }
1119 if (Options.InlineBoolFlag) {
1120 auto FlagPtr = IRB.CreateGEP(
1121 FunctionBoolArray->getValueType(), FunctionBoolArray,
1122 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
1123 auto Load = IRB.CreateLoad(Int1Ty, FlagPtr);
1124 auto ThenTerm = SplitBlockAndInsertIfThen(
1125 IRB.CreateIsNull(Load), &*IP, false,
1127 InstrumentationIRBuilder ThenIRB(ThenTerm);
1128 auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr);
1129 if (EntryLoc)
1130 Store->setDebugLoc(EntryLoc);
1131 Load->setNoSanitizeMetadata();
1132 Store->setNoSanitizeMetadata();
1133 }
1134 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
1135 Module *M = F.getParent();
1136 const DataLayout &DL = M->getDataLayout();
1137
1138 if (Options.StackDepthCallbackMin) {
1139 // In callback mode, only add call when stack depth reaches minimum.
1140 int EstimatedStackSize = 0;
1141 // If dynamic alloca found, always add call.
1142 bool HasDynamicAlloc = false;
1143 // Find an insertion point after last "alloca".
1144 llvm::Instruction *InsertBefore = nullptr;
1145
1146 // Examine all allocas in the basic block. since we're too early
1147 // to have results from Intrinsic::frameaddress, we have to manually
1148 // estimate the stack size.
1149 for (auto &I : BB) {
1150 if (auto *AI = dyn_cast<AllocaInst>(&I)) {
1151 // Move potential insertion point past the "alloca".
1152 InsertBefore = AI->getNextNode();
1153
1154 // Make an estimate on the stack usage.
1155 if (auto AllocaSize = AI->getAllocationSize(DL)) {
1156 if (AllocaSize->isFixed())
1157 EstimatedStackSize += AllocaSize->getFixedValue();
1158 else
1159 HasDynamicAlloc = true;
1160 } else {
1161 HasDynamicAlloc = true;
1162 }
1163 }
1164 }
1165
1166 if (HasDynamicAlloc ||
1167 EstimatedStackSize >= Options.StackDepthCallbackMin) {
1168 if (InsertBefore)
1169 IRB.SetInsertPoint(InsertBefore);
1170 auto Call = IRB.CreateCall(SanCovStackDepthCallback);
1171 if (EntryLoc)
1172 Call->setDebugLoc(EntryLoc);
1174 }
1175 } else {
1176 // Check stack depth. If it's the deepest so far, record it.
1177 auto FrameAddrPtr = IRB.CreateIntrinsic(
1178 Intrinsic::frameaddress, IRB.getPtrTy(DL.getAllocaAddrSpace()),
1179 {Constant::getNullValue(Int32Ty)});
1180 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
1181 auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
1182 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
1183 auto ThenTerm = SplitBlockAndInsertIfThen(
1184 IsStackLower, &*IP, false,
1186 InstrumentationIRBuilder ThenIRB(ThenTerm);
1187 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
1188 if (EntryLoc)
1189 Store->setDebugLoc(EntryLoc);
1190 LowestStack->setNoSanitizeMetadata();
1191 Store->setNoSanitizeMetadata();
1192 }
1193 }
1194}
1195
1196std::string
1197ModuleSanitizerCoverage::getSectionName(const std::string &Section) const {
1198 if (TargetTriple.isOSBinFormatCOFF()) {
1199 if (Section == SanCovCountersSectionName)
1200 return ".SCOV$CM";
1201 if (Section == SanCovBoolFlagSectionName)
1202 return ".SCOV$BM";
1203 if (Section == SanCovPCsSectionName)
1204 return ".SCOVP$M";
1205 return ".SCOV$GM"; // For SanCovGuardsSectionName.
1206 }
1207 if (TargetTriple.isOSBinFormatMachO())
1208 return "__DATA,__" + Section;
1209 return "__" + Section;
1210}
1211
1212std::string
1213ModuleSanitizerCoverage::getSectionStart(const std::string &Section) const {
1214 if (TargetTriple.isOSBinFormatMachO())
1215 return "\1section$start$__DATA$__" + Section;
1216 return "__start___" + Section;
1217}
1218
1219std::string
1220ModuleSanitizerCoverage::getSectionEnd(const std::string &Section) const {
1221 if (TargetTriple.isOSBinFormatMachO())
1222 return "\1section$end$__DATA$__" + Section;
1223 return "__stop___" + Section;
1224}
1225
1226void ModuleSanitizerCoverage::createFunctionControlFlow(Function &F) {
1228 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
1229
1230 for (auto &BB : F) {
1231 // blockaddress can not be used on function's entry block.
1232 if (&BB == &F.getEntryBlock())
1233 CFs.push_back((Constant *)IRB.CreatePointerCast(&F, PtrTy));
1234 else
1235 CFs.push_back(
1236 (Constant *)IRB.CreatePointerCast(BlockAddress::get(&BB), PtrTy));
1237
1238 for (auto SuccBB : successors(&BB)) {
1239 assert(SuccBB != &F.getEntryBlock());
1240 CFs.push_back(
1241 (Constant *)IRB.CreatePointerCast(BlockAddress::get(SuccBB), PtrTy));
1242 }
1243
1245
1246 for (auto &Inst : BB) {
1247 if (CallBase *CB = dyn_cast<CallBase>(&Inst)) {
1248 if (CB->isIndirectCall()) {
1249 // TODO(navidem): handle indirect calls, for now mark its existence.
1251 ConstantInt::getAllOnesValue(IntptrTy), PtrTy));
1252 } else {
1253 auto CalledF = CB->getCalledFunction();
1254 if (CalledF && !CalledF->isIntrinsic())
1255 CFs.push_back((Constant *)IRB.CreatePointerCast(CalledF, PtrTy));
1256 }
1257 }
1258 }
1259
1261 }
1262
1263 FunctionCFsArray = CreateFunctionLocalArrayInSection(CFs.size(), F, PtrTy,
1265 FunctionCFsArray->setInitializer(
1266 ConstantArray::get(ArrayType::get(PtrTy, CFs.size()), CFs));
1267 FunctionCFsArray->setConstant(true);
1268}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
static cl::opt< bool > SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false), cl::Hidden, cl::desc("Split all critical edges during " "PHI elimination"))
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
if(PassOpts->AAPipeline)
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< bool > ClLoadTracing("sanitizer-coverage-trace-loads", cl::desc("Tracing of load instructions"), cl::Hidden)
const char SanCovCFsSectionName[]
static bool isFullPostDominator(const BasicBlock *BB, const PostDominatorTree &PDT)
static cl::opt< int > ClCoverageLevel("sanitizer-coverage-level", cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, " "3: all blocks and critical edges"), cl::Hidden)
static cl::opt< bool > ClSancovDropCtors("sanitizer-coverage-drop-ctors", cl::desc("do not emit module ctors for global counters"), cl::Hidden)
static cl::opt< bool > ClStackDepth("sanitizer-coverage-stack-depth", cl::desc("max stack depth tracing"), cl::Hidden)
static cl::opt< bool > ClTracePCEntryExit("sanitizer-coverage-trace-pc-entry-exit", cl::desc("pc tracing with separate entry/exit callbacks"), cl::Hidden)
static cl::opt< bool > ClInlineBoolFlag("sanitizer-coverage-inline-bool-flag", cl::desc("sets a boolean flag for every edge"), cl::Hidden)
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[]
static cl::opt< bool > ClCreatePCTable("sanitizer-coverage-pc-table", cl::desc("create a static PC table"), cl::Hidden)
const char SanCovPCsInitName[]
const char SanCovTracePCGuardName[]
static cl::opt< int > ClStackDepthCallbackMin("sanitizer-coverage-stack-depth-callback-min", cl::desc("max stack depth tracing should use callback and only when " "stack depth more than specified"), cl::Hidden)
const char SanCovModuleCtor8bitCountersName[]
const char SanCovTracePCGuardInitName[]
static cl::opt< bool > ClCollectCF("sanitizer-coverage-control-flow", cl::desc("collect control flow for each function"), cl::Hidden)
const char SanCovTraceDiv4[]
static const uint64_t SanCtorAndDtorPriority
const char SanCovBoolFlagInitName[]
static cl::opt< bool > ClGatedCallbacks("sanitizer-coverage-gated-trace-callbacks", cl::desc("Gate the invocation of the tracing callbacks on a global variable" ". Currently only supported for trace-pc-guard and trace-cmp."), cl::Hidden, cl::init(false))
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)
static cl::opt< bool > ClStoreTracing("sanitizer-coverage-trace-stores", cl::desc("Tracing of store instructions"), cl::Hidden)
const char SanCovCallbackGateName[]
static cl::opt< bool > ClTracePCGuard("sanitizer-coverage-trace-pc-guard", cl::desc("pc tracing with a guard"), cl::Hidden)
const char SanCovTraceDiv8[]
const char SanCovLoad4[]
static cl::opt< bool > ClGEPTracing("sanitizer-coverage-trace-geps", cl::desc("Tracing of GEP instructions"), cl::Hidden)
const char SanCovStackDepthCallbackName[]
const char SanCovCFsInitName[]
static cl::opt< bool > ClTracePC("sanitizer-coverage-trace-pc", cl::desc("Experimental pc tracing"), cl::Hidden)
const char SanCovStore2[]
static cl::opt< bool > ClPruneBlocks("sanitizer-coverage-prune-blocks", cl::desc("Reduce the number of instrumented blocks"), cl::Hidden, cl::init(true))
const char SanCovPCsSectionName[]
const char SanCovLoad1[]
const char SanCovTracePCExitName[]
static bool isFullDominator(const BasicBlock *BB, const DominatorTree &DT)
static cl::opt< bool > ClCMPTracing("sanitizer-coverage-trace-compares", cl::desc("Tracing of CMP and similar instructions"), cl::Hidden)
const char SanCovTraceCmp8[]
const char SanCovCallbackGateSectionName[]
const char SanCovStore16[]
static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree &DT, const SanitizerCoverageOptions &Options)
static cl::opt< bool > ClDIVTracing("sanitizer-coverage-trace-divs", cl::desc("Tracing of DIV instructions"), cl::Hidden)
static cl::opt< bool > ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters", cl::desc("increments 8-bit counter for every edge"), cl::Hidden)
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 SmallVector class.
Defines the virtual file system interface vfs::FileSystem.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
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:62
iterator end()
Definition BasicBlock.h:462
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.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode, a debug intrinsic,...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
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()
Value * getCalledOperand() const
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
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:43
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:64
A debug info location.
Definition DebugLoc.h:123
Analysis pass which computes a DominatorTree.
Definition Dominators.h:278
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:159
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:809
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:215
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:2347
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2246
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2194
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition IRBuilder.h:247
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:1967
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
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:1877
LLVMContext & getContext() const
Definition IRBuilder.h:203
Value * CreateConstInBoundsGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0, uint64_t Idx1, const Twine &Name="")
Definition IRBuilder.h:2032
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1890
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1429
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2189
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition IRBuilder.h:2664
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2510
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:622
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition IRBuilder.h:2272
Value * CreateIsNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg == 0.
Definition IRBuilder.h:2659
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:207
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2811
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
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:1572
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
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.
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.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Multiway switch.
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:286
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:317
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:256
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:440
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
CallInst * Call
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
initializer< Ty > init(const Ty &Val)
static constexpr const StringLiteral & getSectionName(DebugSectionKind SectionKind)
Return the name of the section.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
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:1739
bool succ_empty(const Instruction *I)
Definition CFG.h:153
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
FunctionAddr VTableAddr uintptr_t uintptr_t Int32Ty
Definition InstrProf.h:296
auto successors(const MachineBasicBlock *BB)
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
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:1636
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
FunctionAddr VTableAddr Next
Definition InstrProf.h:141
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
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:1917
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.
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)
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:119
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:870
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
#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