LLVM 19.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/DataLayout.h"
20#include "llvm/IR/Dominators.h"
22#include "llvm/IR/Function.h"
24#include "llvm/IR/IRBuilder.h"
26#include "llvm/IR/Intrinsics.h"
27#include "llvm/IR/LLVMContext.h"
28#include "llvm/IR/MDBuilder.h"
29#include "llvm/IR/Module.h"
30#include "llvm/IR/Type.h"
37
38using namespace llvm;
39
40#define DEBUG_TYPE "sancov"
41
42const char SanCovTracePCIndirName[] = "__sanitizer_cov_trace_pc_indir";
43const char SanCovTracePCName[] = "__sanitizer_cov_trace_pc";
44const char SanCovTraceCmp1[] = "__sanitizer_cov_trace_cmp1";
45const char SanCovTraceCmp2[] = "__sanitizer_cov_trace_cmp2";
46const char SanCovTraceCmp4[] = "__sanitizer_cov_trace_cmp4";
47const char SanCovTraceCmp8[] = "__sanitizer_cov_trace_cmp8";
48const char SanCovTraceConstCmp1[] = "__sanitizer_cov_trace_const_cmp1";
49const char SanCovTraceConstCmp2[] = "__sanitizer_cov_trace_const_cmp2";
50const char SanCovTraceConstCmp4[] = "__sanitizer_cov_trace_const_cmp4";
51const char SanCovTraceConstCmp8[] = "__sanitizer_cov_trace_const_cmp8";
52const char SanCovLoad1[] = "__sanitizer_cov_load1";
53const char SanCovLoad2[] = "__sanitizer_cov_load2";
54const char SanCovLoad4[] = "__sanitizer_cov_load4";
55const char SanCovLoad8[] = "__sanitizer_cov_load8";
56const char SanCovLoad16[] = "__sanitizer_cov_load16";
57const char SanCovStore1[] = "__sanitizer_cov_store1";
58const char SanCovStore2[] = "__sanitizer_cov_store2";
59const char SanCovStore4[] = "__sanitizer_cov_store4";
60const char SanCovStore8[] = "__sanitizer_cov_store8";
61const char SanCovStore16[] = "__sanitizer_cov_store16";
62const char SanCovTraceDiv4[] = "__sanitizer_cov_trace_div4";
63const char SanCovTraceDiv8[] = "__sanitizer_cov_trace_div8";
64const char SanCovTraceGep[] = "__sanitizer_cov_trace_gep";
65const char SanCovTraceSwitchName[] = "__sanitizer_cov_trace_switch";
67 "sancov.module_ctor_trace_pc_guard";
69 "sancov.module_ctor_8bit_counters";
70const char SanCovModuleCtorBoolFlagName[] = "sancov.module_ctor_bool_flag";
72
73const char SanCovTracePCGuardName[] = "__sanitizer_cov_trace_pc_guard";
74const char SanCovTracePCGuardInitName[] = "__sanitizer_cov_trace_pc_guard_init";
75const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init";
76const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init";
77const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init";
78const char SanCovCFsInitName[] = "__sanitizer_cov_cfs_init";
79
80const char SanCovGuardsSectionName[] = "sancov_guards";
81const char SanCovCountersSectionName[] = "sancov_cntrs";
82const char SanCovBoolFlagSectionName[] = "sancov_bools";
83const char SanCovPCsSectionName[] = "sancov_pcs";
84const char SanCovCFsSectionName[] = "sancov_cfs";
85
86const char SanCovLowestStackName[] = "__sancov_lowest_stack";
87
89 "sanitizer-coverage-level",
90 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
91 "3: all blocks and critical edges"),
93
94static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
95 cl::desc("Experimental pc tracing"), cl::Hidden);
96
97static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
98 cl::desc("pc tracing with a guard"),
100
101// If true, we create a global variable that contains PCs of all instrumented
102// BBs, put this global into a named section, and pass this section's bounds
103// to __sanitizer_cov_pcs_init.
104// This way the coverage instrumentation does not need to acquire the PCs
105// at run-time. Works with trace-pc-guard, inline-8bit-counters, and
106// inline-bool-flag.
107static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
108 cl::desc("create a static PC table"),
109 cl::Hidden);
110
111static cl::opt<bool>
112 ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
113 cl::desc("increments 8-bit counter for every edge"),
114 cl::Hidden);
115
116static cl::opt<bool>
117 ClInlineBoolFlag("sanitizer-coverage-inline-bool-flag",
118 cl::desc("sets a boolean flag for every edge"),
119 cl::Hidden);
120
121static cl::opt<bool>
122 ClCMPTracing("sanitizer-coverage-trace-compares",
123 cl::desc("Tracing of CMP and similar instructions"),
124 cl::Hidden);
125
126static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
127 cl::desc("Tracing of DIV instructions"),
128 cl::Hidden);
129
130static cl::opt<bool> ClLoadTracing("sanitizer-coverage-trace-loads",
131 cl::desc("Tracing of load instructions"),
132 cl::Hidden);
133
134static cl::opt<bool> ClStoreTracing("sanitizer-coverage-trace-stores",
135 cl::desc("Tracing of store instructions"),
136 cl::Hidden);
137
138static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
139 cl::desc("Tracing of GEP instructions"),
140 cl::Hidden);
141
142static cl::opt<bool>
143 ClPruneBlocks("sanitizer-coverage-prune-blocks",
144 cl::desc("Reduce the number of instrumented blocks"),
145 cl::Hidden, cl::init(true));
146
147static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
148 cl::desc("max stack depth tracing"),
149 cl::Hidden);
150
151static cl::opt<bool>
152 ClCollectCF("sanitizer-coverage-control-flow",
153 cl::desc("collect control flow for each function"), cl::Hidden);
154
155namespace {
156
157SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
159 switch (LegacyCoverageLevel) {
160 case 0:
162 break;
163 case 1:
165 break;
166 case 2:
168 break;
169 case 3:
171 break;
172 case 4:
174 Res.IndirectCalls = true;
175 break;
176 }
177 return Res;
178}
179
181 // Sets CoverageType and IndirectCalls.
182 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
183 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
184 Options.IndirectCalls |= CLOpts.IndirectCalls;
185 Options.TraceCmp |= ClCMPTracing;
186 Options.TraceDiv |= ClDIVTracing;
187 Options.TraceGep |= ClGEPTracing;
188 Options.TracePC |= ClTracePC;
189 Options.TracePCGuard |= ClTracePCGuard;
190 Options.Inline8bitCounters |= ClInline8bitCounters;
191 Options.InlineBoolFlag |= ClInlineBoolFlag;
192 Options.PCTable |= ClCreatePCTable;
193 Options.NoPrune |= !ClPruneBlocks;
194 Options.StackDepth |= ClStackDepth;
195 Options.TraceLoads |= ClLoadTracing;
196 Options.TraceStores |= ClStoreTracing;
197 if (!Options.TracePCGuard && !Options.TracePC &&
198 !Options.Inline8bitCounters && !Options.StackDepth &&
199 !Options.InlineBoolFlag && !Options.TraceLoads && !Options.TraceStores)
200 Options.TracePCGuard = true; // TracePCGuard is default.
201 Options.CollectControlFlow |= ClCollectCF;
202 return Options;
203}
204
205class ModuleSanitizerCoverage {
206public:
207 using DomTreeCallback = function_ref<const DominatorTree &(Function &F)>;
208 using PostDomTreeCallback =
210
211 ModuleSanitizerCoverage(Module &M, DomTreeCallback DTCallback,
212 PostDomTreeCallback PDTCallback,
213 const SanitizerCoverageOptions &Options,
214 const SpecialCaseList *Allowlist,
215 const SpecialCaseList *Blocklist)
216 : M(M), DTCallback(DTCallback), PDTCallback(PDTCallback),
217 Options(Options), Allowlist(Allowlist), Blocklist(Blocklist) {}
218
219 bool instrumentModule();
220
221private:
222 void createFunctionControlFlow(Function &F);
223 void instrumentFunction(Function &F);
224 void InjectCoverageForIndirectCalls(Function &F,
225 ArrayRef<Instruction *> IndirCalls);
226 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
227 void InjectTraceForDiv(Function &F,
228 ArrayRef<BinaryOperator *> DivTraceTargets);
229 void InjectTraceForGep(Function &F,
230 ArrayRef<GetElementPtrInst *> GepTraceTargets);
231 void InjectTraceForLoadsAndStores(Function &F, ArrayRef<LoadInst *> Loads,
232 ArrayRef<StoreInst *> Stores);
233 void InjectTraceForSwitch(Function &F,
234 ArrayRef<Instruction *> SwitchTraceTargets);
235 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
236 bool IsLeafFunc = true);
237 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
238 Function &F, Type *Ty,
239 const char *Section);
240 GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
241 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
242 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
243 bool IsLeafFunc = true);
244 Function *CreateInitCallsForSections(Module &M, const char *CtorName,
245 const char *InitFunctionName, Type *Ty,
246 const char *Section);
247 std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
248 Type *Ty);
249
250 std::string getSectionName(const std::string &Section) const;
251 std::string getSectionStart(const std::string &Section) const;
252 std::string getSectionEnd(const std::string &Section) const;
253
254 Module &M;
255 DomTreeCallback DTCallback;
256 PostDomTreeCallback PDTCallback;
257
258 FunctionCallee SanCovTracePCIndir;
259 FunctionCallee SanCovTracePC, SanCovTracePCGuard;
260 std::array<FunctionCallee, 4> SanCovTraceCmpFunction;
261 std::array<FunctionCallee, 4> SanCovTraceConstCmpFunction;
262 std::array<FunctionCallee, 5> SanCovLoadFunction;
263 std::array<FunctionCallee, 5> SanCovStoreFunction;
264 std::array<FunctionCallee, 2> SanCovTraceDivFunction;
265 FunctionCallee SanCovTraceGepFunction;
266 FunctionCallee SanCovTraceSwitchFunction;
267 GlobalVariable *SanCovLowestStack;
268 Type *PtrTy, *IntptrTy, *Int64Ty, *Int32Ty, *Int16Ty, *Int8Ty, *Int1Ty;
269 Module *CurModule;
270 std::string CurModuleUniqueId;
271 Triple TargetTriple;
272 LLVMContext *C;
273 const DataLayout *DL;
274
275 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
276 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
277 GlobalVariable *FunctionBoolArray; // for inline-bool-flag.
278 GlobalVariable *FunctionPCsArray; // for pc-table.
279 GlobalVariable *FunctionCFsArray; // for control flow table
280 SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
281 SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
282
284
285 const SpecialCaseList *Allowlist;
286 const SpecialCaseList *Blocklist;
287};
288} // namespace
289
292 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
293 auto DTCallback = [&FAM](Function &F) -> const DominatorTree & {
295 };
296 auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree & {
298 };
299 ModuleSanitizerCoverage ModuleSancov(M, DTCallback, PDTCallback,
300 OverrideFromCL(Options), Allowlist.get(),
301 Blocklist.get());
302 if (!ModuleSancov.instrumentModule())
303 return PreservedAnalyses::all();
304
306 // GlobalsAA is considered stateless and does not get invalidated unless
307 // explicitly invalidated; PreservedAnalyses::none() is not enough. Sanitizers
308 // make changes that require GlobalsAA to be invalidated.
309 PA.abandon<GlobalsAA>();
310 return PA;
311}
312
313std::pair<Value *, Value *>
314ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section,
315 Type *Ty) {
316 // Use ExternalWeak so that if all sections are discarded due to section
317 // garbage collection, the linker will not report undefined symbol errors.
318 // Windows defines the start/stop symbols in compiler-rt so no need for
319 // ExternalWeak.
320 GlobalValue::LinkageTypes Linkage = TargetTriple.isOSBinFormatCOFF()
323 GlobalVariable *SecStart =
324 new GlobalVariable(M, Ty, false, Linkage, nullptr,
325 getSectionStart(Section));
327 GlobalVariable *SecEnd =
328 new GlobalVariable(M, Ty, false, Linkage, nullptr,
329 getSectionEnd(Section));
331 IRBuilder<> IRB(M.getContext());
332 if (!TargetTriple.isOSBinFormatCOFF())
333 return std::make_pair(SecStart, SecEnd);
334
335 // Account for the fact that on windows-msvc __start_* symbols actually
336 // point to a uint64_t before the start of the array.
337 auto GEP =
338 IRB.CreatePtrAdd(SecStart, ConstantInt::get(IntptrTy, sizeof(uint64_t)));
339 return std::make_pair(GEP, SecEnd);
340}
341
342Function *ModuleSanitizerCoverage::CreateInitCallsForSections(
343 Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
344 const char *Section) {
345 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
346 auto SecStart = SecStartEnd.first;
347 auto SecEnd = SecStartEnd.second;
348 Function *CtorFunc;
349 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
350 M, CtorName, InitFunctionName, {PtrTy, PtrTy}, {SecStart, SecEnd});
351 assert(CtorFunc->getName() == CtorName);
352
353 if (TargetTriple.supportsCOMDAT()) {
354 // Use comdat to dedup CtorFunc.
355 CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
356 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
357 } else {
359 }
360
361 if (TargetTriple.isOSBinFormatCOFF()) {
362 // In COFF files, if the contructors are set as COMDAT (they are because
363 // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
364 // functions and data) is used, the constructors get stripped. To prevent
365 // this, give the constructors weak ODR linkage and ensure the linker knows
366 // to include the sancov constructor. This way the linker can deduplicate
367 // the constructors but always leave one copy.
369 }
370 return CtorFunc;
371}
372
373bool ModuleSanitizerCoverage::instrumentModule() {
375 return false;
376 if (Allowlist &&
377 !Allowlist->inSection("coverage", "src", M.getSourceFileName()))
378 return false;
379 if (Blocklist &&
380 Blocklist->inSection("coverage", "src", M.getSourceFileName()))
381 return false;
382 C = &(M.getContext());
383 DL = &M.getDataLayout();
384 CurModule = &M;
385 CurModuleUniqueId = getUniqueModuleId(CurModule);
386 TargetTriple = Triple(M.getTargetTriple());
387 FunctionGuardArray = nullptr;
388 Function8bitCounterArray = nullptr;
389 FunctionBoolArray = nullptr;
390 FunctionPCsArray = nullptr;
391 FunctionCFsArray = nullptr;
392 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
393 PtrTy = PointerType::getUnqual(*C);
394 Type *VoidTy = Type::getVoidTy(*C);
395 IRBuilder<> IRB(*C);
396 Int64Ty = IRB.getInt64Ty();
397 Int32Ty = IRB.getInt32Ty();
398 Int16Ty = IRB.getInt16Ty();
399 Int8Ty = IRB.getInt8Ty();
400 Int1Ty = IRB.getInt1Ty();
401
402 SanCovTracePCIndir =
403 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
404 // Make sure smaller parameters are zero-extended to i64 if required by the
405 // target ABI.
406 AttributeList SanCovTraceCmpZeroExtAL;
407 SanCovTraceCmpZeroExtAL =
408 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
409 SanCovTraceCmpZeroExtAL =
410 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
411
412 SanCovTraceCmpFunction[0] =
413 M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
414 IRB.getInt8Ty(), IRB.getInt8Ty());
415 SanCovTraceCmpFunction[1] =
416 M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
417 IRB.getInt16Ty(), IRB.getInt16Ty());
418 SanCovTraceCmpFunction[2] =
419 M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
420 IRB.getInt32Ty(), IRB.getInt32Ty());
421 SanCovTraceCmpFunction[3] =
422 M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
423
424 SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
425 SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
426 SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
427 SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
428 SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
429 SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
430 SanCovTraceConstCmpFunction[3] =
431 M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
432
433 // Loads.
434 SanCovLoadFunction[0] = M.getOrInsertFunction(SanCovLoad1, VoidTy, PtrTy);
435 SanCovLoadFunction[1] =
436 M.getOrInsertFunction(SanCovLoad2, VoidTy, PtrTy);
437 SanCovLoadFunction[2] =
438 M.getOrInsertFunction(SanCovLoad4, VoidTy, PtrTy);
439 SanCovLoadFunction[3] =
440 M.getOrInsertFunction(SanCovLoad8, VoidTy, PtrTy);
441 SanCovLoadFunction[4] =
442 M.getOrInsertFunction(SanCovLoad16, VoidTy, PtrTy);
443 // Stores.
444 SanCovStoreFunction[0] =
445 M.getOrInsertFunction(SanCovStore1, VoidTy, PtrTy);
446 SanCovStoreFunction[1] =
447 M.getOrInsertFunction(SanCovStore2, VoidTy, PtrTy);
448 SanCovStoreFunction[2] =
449 M.getOrInsertFunction(SanCovStore4, VoidTy, PtrTy);
450 SanCovStoreFunction[3] =
451 M.getOrInsertFunction(SanCovStore8, VoidTy, PtrTy);
452 SanCovStoreFunction[4] =
453 M.getOrInsertFunction(SanCovStore16, VoidTy, PtrTy);
454
455 {
457 AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
458 SanCovTraceDivFunction[0] =
459 M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
460 }
461 SanCovTraceDivFunction[1] =
462 M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
463 SanCovTraceGepFunction =
464 M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
465 SanCovTraceSwitchFunction =
466 M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, PtrTy);
467
468 Constant *SanCovLowestStackConstant =
469 M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
470 SanCovLowestStack = dyn_cast<GlobalVariable>(SanCovLowestStackConstant);
471 if (!SanCovLowestStack || SanCovLowestStack->getValueType() != IntptrTy) {
472 C->emitError(StringRef("'") + SanCovLowestStackName +
473 "' should not be declared by the user");
474 return true;
475 }
476 SanCovLowestStack->setThreadLocalMode(
478 if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
479 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
480
481 SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
482 SanCovTracePCGuard =
483 M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, PtrTy);
484
485 for (auto &F : M)
486 instrumentFunction(F);
487
488 Function *Ctor = nullptr;
489
490 if (FunctionGuardArray)
491 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
494 if (Function8bitCounterArray)
495 Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
498 if (FunctionBoolArray) {
499 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName,
502 }
503 if (Ctor && Options.PCTable) {
504 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrTy);
506 M, SanCovPCsInitName, {PtrTy, PtrTy});
507 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
508 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
509 }
510
511 if (Ctor && Options.CollectControlFlow) {
512 auto SecStartEnd = CreateSecStartEnd(M, SanCovCFsSectionName, IntptrTy);
514 M, SanCovCFsInitName, {PtrTy, PtrTy});
515 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
516 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
517 }
518
519 appendToUsed(M, GlobalsToAppendToUsed);
520 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
521 return true;
522}
523
524// True if block has successors and it dominates all of them.
525static bool isFullDominator(const BasicBlock *BB, const DominatorTree &DT) {
526 if (succ_empty(BB))
527 return false;
528
529 return llvm::all_of(successors(BB), [&](const BasicBlock *SUCC) {
530 return DT.dominates(BB, SUCC);
531 });
532}
533
534// True if block has predecessors and it postdominates all of them.
535static bool isFullPostDominator(const BasicBlock *BB,
536 const PostDominatorTree &PDT) {
537 if (pred_empty(BB))
538 return false;
539
540 return llvm::all_of(predecessors(BB), [&](const BasicBlock *PRED) {
541 return PDT.dominates(BB, PRED);
542 });
543}
544
545static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
546 const DominatorTree &DT,
547 const PostDominatorTree &PDT,
549 // Don't insert coverage for blocks containing nothing but unreachable: we
550 // will never call __sanitizer_cov() for them, so counting them in
551 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
552 // percentage. Also, unreachable instructions frequently have no debug
553 // locations.
554 if (isa<UnreachableInst>(BB->getFirstNonPHIOrDbgOrLifetime()))
555 return false;
556
557 // Don't insert coverage into blocks without a valid insertion point
558 // (catchswitch blocks).
559 if (BB->getFirstInsertionPt() == BB->end())
560 return false;
561
562 if (Options.NoPrune || &F.getEntryBlock() == BB)
563 return true;
564
566 &F.getEntryBlock() != BB)
567 return false;
568
569 // Do not instrument full dominators, or full post-dominators with multiple
570 // predecessors.
571 return !isFullDominator(BB, DT)
572 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
573}
574
575// Returns true iff From->To is a backedge.
576// A twist here is that we treat From->To as a backedge if
577// * To dominates From or
578// * To->UniqueSuccessor dominates From
580 const DominatorTree &DT) {
581 if (DT.dominates(To, From))
582 return true;
583 if (auto Next = To->getUniqueSuccessor())
584 if (DT.dominates(Next, From))
585 return true;
586 return false;
587}
588
589// Prunes uninteresting Cmp instrumentation:
590// * CMP instructions that feed into loop backedge branch.
591//
592// Note that Cmp pruning is controlled by the same flag as the
593// BB pruning.
594static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree &DT,
596 if (!Options.NoPrune)
597 if (CMP->hasOneUse())
598 if (auto BR = dyn_cast<BranchInst>(CMP->user_back()))
599 for (BasicBlock *B : BR->successors())
600 if (IsBackEdge(BR->getParent(), B, DT))
601 return false;
602 return true;
603}
604
605void ModuleSanitizerCoverage::instrumentFunction(Function &F) {
606 if (F.empty())
607 return;
608 if (F.getName().contains(".module_ctor"))
609 return; // Should not instrument sanitizer init functions.
610 if (F.getName().starts_with("__sanitizer_"))
611 return; // Don't instrument __sanitizer_* callbacks.
612 // Don't touch available_externally functions, their actual body is elewhere.
613 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
614 return;
615 // Don't instrument MSVC CRT configuration helpers. They may run before normal
616 // initialization.
617 if (F.getName() == "__local_stdio_printf_options" ||
618 F.getName() == "__local_stdio_scanf_options")
619 return;
620 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
621 return;
622 // Don't instrument functions using SEH for now. Splitting basic blocks like
623 // we do for coverage breaks WinEHPrepare.
624 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
625 if (F.hasPersonalityFn() &&
627 return;
628 if (Allowlist && !Allowlist->inSection("coverage", "fun", F.getName()))
629 return;
630 if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName()))
631 return;
632 if (F.hasFnAttribute(Attribute::NoSanitizeCoverage))
633 return;
634 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge) {
636 F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
637 }
639 SmallVector<BasicBlock *, 16> BlocksToInstrument;
640 SmallVector<Instruction *, 8> CmpTraceTargets;
641 SmallVector<Instruction *, 8> SwitchTraceTargets;
642 SmallVector<BinaryOperator *, 8> DivTraceTargets;
646
647 const DominatorTree &DT = DTCallback(F);
648 const PostDominatorTree &PDT = PDTCallback(F);
649 bool IsLeafFunc = true;
650
651 for (auto &BB : F) {
652 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
653 BlocksToInstrument.push_back(&BB);
654 for (auto &Inst : BB) {
655 if (Options.IndirectCalls) {
656 CallBase *CB = dyn_cast<CallBase>(&Inst);
657 if (CB && CB->isIndirectCall())
658 IndirCalls.push_back(&Inst);
659 }
660 if (Options.TraceCmp) {
661 if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
662 if (IsInterestingCmp(CMP, DT, Options))
663 CmpTraceTargets.push_back(&Inst);
664 if (isa<SwitchInst>(&Inst))
665 SwitchTraceTargets.push_back(&Inst);
666 }
667 if (Options.TraceDiv)
668 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
669 if (BO->getOpcode() == Instruction::SDiv ||
670 BO->getOpcode() == Instruction::UDiv)
671 DivTraceTargets.push_back(BO);
672 if (Options.TraceGep)
673 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
674 GepTraceTargets.push_back(GEP);
675 if (Options.TraceLoads)
676 if (LoadInst *LI = dyn_cast<LoadInst>(&Inst))
677 Loads.push_back(LI);
678 if (Options.TraceStores)
679 if (StoreInst *SI = dyn_cast<StoreInst>(&Inst))
680 Stores.push_back(SI);
681 if (Options.StackDepth)
682 if (isa<InvokeInst>(Inst) ||
683 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
684 IsLeafFunc = false;
685 }
686 }
687
688 if (Options.CollectControlFlow)
689 createFunctionControlFlow(F);
690
691 InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
692 InjectCoverageForIndirectCalls(F, IndirCalls);
693 InjectTraceForCmp(F, CmpTraceTargets);
694 InjectTraceForSwitch(F, SwitchTraceTargets);
695 InjectTraceForDiv(F, DivTraceTargets);
696 InjectTraceForGep(F, GepTraceTargets);
697 InjectTraceForLoadsAndStores(F, Loads, Stores);
698}
699
700GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection(
701 size_t NumElements, Function &F, Type *Ty, const char *Section) {
702 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
703 auto Array = new GlobalVariable(
704 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
705 Constant::getNullValue(ArrayTy), "__sancov_gen_");
706
707 if (TargetTriple.supportsCOMDAT() &&
708 (TargetTriple.isOSBinFormatELF() || !F.isInterposable()))
709 if (auto Comdat = getOrCreateFunctionComdat(F, TargetTriple))
710 Array->setComdat(Comdat);
711 Array->setSection(getSectionName(Section));
712 Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedValue()));
713
714 // sancov_pcs parallels the other metadata section(s). Optimizers (e.g.
715 // GlobalOpt/ConstantMerge) may not discard sancov_pcs and the other
716 // section(s) as a unit, so we conservatively retain all unconditionally in
717 // the compiler.
718 //
719 // With comdat (COFF/ELF), the linker can guarantee the associated sections
720 // will be retained or discarded as a unit, so llvm.compiler.used is
721 // sufficient. Otherwise, conservatively make all of them retained by the
722 // linker.
723 if (Array->hasComdat())
724 GlobalsToAppendToCompilerUsed.push_back(Array);
725 else
726 GlobalsToAppendToUsed.push_back(Array);
727
728 return Array;
729}
730
732ModuleSanitizerCoverage::CreatePCArray(Function &F,
733 ArrayRef<BasicBlock *> AllBlocks) {
734 size_t N = AllBlocks.size();
735 assert(N);
737 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
738 for (size_t i = 0; i < N; i++) {
739 if (&F.getEntryBlock() == AllBlocks[i]) {
740 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, PtrTy));
741 PCs.push_back((Constant *)IRB.CreateIntToPtr(
742 ConstantInt::get(IntptrTy, 1), PtrTy));
743 } else {
744 PCs.push_back((Constant *)IRB.CreatePointerCast(
745 BlockAddress::get(AllBlocks[i]), PtrTy));
747 }
748 }
749 auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, PtrTy,
751 PCArray->setInitializer(
752 ConstantArray::get(ArrayType::get(PtrTy, N * 2), PCs));
753 PCArray->setConstant(true);
754
755 return PCArray;
756}
757
758void ModuleSanitizerCoverage::CreateFunctionLocalArrays(
759 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
760 if (Options.TracePCGuard)
761 FunctionGuardArray = CreateFunctionLocalArrayInSection(
762 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
763
764 if (Options.Inline8bitCounters)
765 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
766 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
767 if (Options.InlineBoolFlag)
768 FunctionBoolArray = CreateFunctionLocalArrayInSection(
769 AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName);
770
771 if (Options.PCTable)
772 FunctionPCsArray = CreatePCArray(F, AllBlocks);
773}
774
775bool ModuleSanitizerCoverage::InjectCoverage(Function &F,
776 ArrayRef<BasicBlock *> AllBlocks,
777 bool IsLeafFunc) {
778 if (AllBlocks.empty()) return false;
779 CreateFunctionLocalArrays(F, AllBlocks);
780 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
781 InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
782 return true;
783}
784
785// On every indirect call we call a run-time function
786// __sanitizer_cov_indir_call* with two parameters:
787// - callee address,
788// - global cache array that contains CacheSize pointers (zero-initialized).
789// The cache is used to speed up recording the caller-callee pairs.
790// The address of the caller is passed implicitly via caller PC.
791// CacheSize is encoded in the name of the run-time function.
792void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls(
793 Function &F, ArrayRef<Instruction *> IndirCalls) {
794 if (IndirCalls.empty())
795 return;
796 assert(Options.TracePC || Options.TracePCGuard ||
797 Options.Inline8bitCounters || Options.InlineBoolFlag);
798 for (auto *I : IndirCalls) {
800 CallBase &CB = cast<CallBase>(*I);
802 if (isa<InlineAsm>(Callee))
803 continue;
804 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
805 }
806}
807
808// For every switch statement we insert a call:
809// __sanitizer_cov_trace_switch(CondValue,
810// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
811
812void ModuleSanitizerCoverage::InjectTraceForSwitch(
813 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
814 for (auto *I : SwitchTraceTargets) {
815 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
817 SmallVector<Constant *, 16> Initializers;
818 Value *Cond = SI->getCondition();
819 if (Cond->getType()->getScalarSizeInBits() >
820 Int64Ty->getScalarSizeInBits())
821 continue;
822 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
823 Initializers.push_back(
824 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
825 if (Cond->getType()->getScalarSizeInBits() <
826 Int64Ty->getScalarSizeInBits())
827 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
828 for (auto It : SI->cases()) {
829 ConstantInt *C = It.getCaseValue();
830 if (C->getType()->getScalarSizeInBits() < 64)
831 C = ConstantInt::get(C->getContext(), C->getValue().zext(64));
832 Initializers.push_back(C);
833 }
834 llvm::sort(drop_begin(Initializers, 2),
835 [](const Constant *A, const Constant *B) {
836 return cast<ConstantInt>(A)->getLimitedValue() <
837 cast<ConstantInt>(B)->getLimitedValue();
838 });
839 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
841 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
842 ConstantArray::get(ArrayOfInt64Ty, Initializers),
843 "__sancov_gen_cov_switch_values");
844 IRB.CreateCall(SanCovTraceSwitchFunction, {Cond, GV});
845 }
846 }
847}
848
849void ModuleSanitizerCoverage::InjectTraceForDiv(
850 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
851 for (auto *BO : DivTraceTargets) {
853 Value *A1 = BO->getOperand(1);
854 if (isa<ConstantInt>(A1)) continue;
855 if (!A1->getType()->isIntegerTy())
856 continue;
857 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
858 int CallbackIdx = TypeSize == 32 ? 0 :
859 TypeSize == 64 ? 1 : -1;
860 if (CallbackIdx < 0) continue;
861 auto Ty = Type::getIntNTy(*C, TypeSize);
862 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
863 {IRB.CreateIntCast(A1, Ty, true)});
864 }
865}
866
867void ModuleSanitizerCoverage::InjectTraceForGep(
868 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
869 for (auto *GEP : GepTraceTargets) {
871 for (Use &Idx : GEP->indices())
872 if (!isa<ConstantInt>(Idx) && Idx->getType()->isIntegerTy())
873 IRB.CreateCall(SanCovTraceGepFunction,
874 {IRB.CreateIntCast(Idx, IntptrTy, true)});
875 }
876}
877
878void ModuleSanitizerCoverage::InjectTraceForLoadsAndStores(
880 auto CallbackIdx = [&](Type *ElementTy) -> int {
881 uint64_t TypeSize = DL->getTypeStoreSizeInBits(ElementTy);
882 return TypeSize == 8 ? 0
883 : TypeSize == 16 ? 1
884 : TypeSize == 32 ? 2
885 : TypeSize == 64 ? 3
886 : TypeSize == 128 ? 4
887 : -1;
888 };
889 for (auto *LI : Loads) {
891 auto Ptr = LI->getPointerOperand();
892 int Idx = CallbackIdx(LI->getType());
893 if (Idx < 0)
894 continue;
895 IRB.CreateCall(SanCovLoadFunction[Idx], Ptr);
896 }
897 for (auto *SI : Stores) {
899 auto Ptr = SI->getPointerOperand();
900 int Idx = CallbackIdx(SI->getValueOperand()->getType());
901 if (Idx < 0)
902 continue;
903 IRB.CreateCall(SanCovStoreFunction[Idx], Ptr);
904 }
905}
906
907void ModuleSanitizerCoverage::InjectTraceForCmp(
908 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
909 for (auto *I : CmpTraceTargets) {
910 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
911 InstrumentationIRBuilder IRB(ICMP);
912 Value *A0 = ICMP->getOperand(0);
913 Value *A1 = ICMP->getOperand(1);
914 if (!A0->getType()->isIntegerTy())
915 continue;
916 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
917 int CallbackIdx = TypeSize == 8 ? 0 :
918 TypeSize == 16 ? 1 :
919 TypeSize == 32 ? 2 :
920 TypeSize == 64 ? 3 : -1;
921 if (CallbackIdx < 0) continue;
922 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
923 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
924 bool FirstIsConst = isa<ConstantInt>(A0);
925 bool SecondIsConst = isa<ConstantInt>(A1);
926 // If both are const, then we don't need such a comparison.
927 if (FirstIsConst && SecondIsConst) continue;
928 // If only one is const, then make it the first callback argument.
929 if (FirstIsConst || SecondIsConst) {
930 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
931 if (SecondIsConst)
932 std::swap(A0, A1);
933 }
934
935 auto Ty = Type::getIntNTy(*C, TypeSize);
936 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
937 IRB.CreateIntCast(A1, Ty, true)});
938 }
939 }
940}
941
942void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
943 size_t Idx,
944 bool IsLeafFunc) {
946 bool IsEntryBB = &BB == &F.getEntryBlock();
947 DebugLoc EntryLoc;
948 if (IsEntryBB) {
949 if (auto SP = F.getSubprogram())
950 EntryLoc = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
951 // Keep static allocas and llvm.localescape calls in the entry block. Even
952 // if we aren't splitting the block, it's nice for allocas to be before
953 // calls.
954 IP = PrepareToSplitEntryBlock(BB, IP);
955 }
956
957 InstrumentationIRBuilder IRB(&*IP);
958 if (EntryLoc)
959 IRB.SetCurrentDebugLocation(EntryLoc);
960 if (Options.TracePC) {
961 IRB.CreateCall(SanCovTracePC)
962 ->setCannotMerge(); // gets the PC using GET_CALLER_PC.
963 }
964 if (Options.TracePCGuard) {
965 auto GuardPtr = IRB.CreateIntToPtr(
966 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
967 ConstantInt::get(IntptrTy, Idx * 4)),
968 PtrTy);
969 IRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge();
970 }
971 if (Options.Inline8bitCounters) {
972 auto CounterPtr = IRB.CreateGEP(
973 Function8bitCounterArray->getValueType(), Function8bitCounterArray,
974 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
975 auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
976 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
977 auto Store = IRB.CreateStore(Inc, CounterPtr);
978 Load->setNoSanitizeMetadata();
979 Store->setNoSanitizeMetadata();
980 }
981 if (Options.InlineBoolFlag) {
982 auto FlagPtr = IRB.CreateGEP(
983 FunctionBoolArray->getValueType(), FunctionBoolArray,
984 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
985 auto Load = IRB.CreateLoad(Int1Ty, FlagPtr);
986 auto ThenTerm = SplitBlockAndInsertIfThen(
987 IRB.CreateIsNull(Load), &*IP, false,
988 MDBuilder(IRB.getContext()).createUnlikelyBranchWeights());
989 IRBuilder<> ThenIRB(ThenTerm);
990 auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr);
991 Load->setNoSanitizeMetadata();
992 Store->setNoSanitizeMetadata();
993 }
994 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
995 // Check stack depth. If it's the deepest so far, record it.
996 Module *M = F.getParent();
997 Function *GetFrameAddr = Intrinsic::getDeclaration(
998 M, Intrinsic::frameaddress,
999 IRB.getPtrTy(M->getDataLayout().getAllocaAddrSpace()));
1000 auto FrameAddrPtr =
1001 IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
1002 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
1003 auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
1004 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
1005 auto ThenTerm = SplitBlockAndInsertIfThen(
1006 IsStackLower, &*IP, false,
1007 MDBuilder(IRB.getContext()).createUnlikelyBranchWeights());
1008 IRBuilder<> ThenIRB(ThenTerm);
1009 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
1010 LowestStack->setNoSanitizeMetadata();
1011 Store->setNoSanitizeMetadata();
1012 }
1013}
1014
1015std::string
1016ModuleSanitizerCoverage::getSectionName(const std::string &Section) const {
1017 if (TargetTriple.isOSBinFormatCOFF()) {
1018 if (Section == SanCovCountersSectionName)
1019 return ".SCOV$CM";
1020 if (Section == SanCovBoolFlagSectionName)
1021 return ".SCOV$BM";
1022 if (Section == SanCovPCsSectionName)
1023 return ".SCOVP$M";
1024 return ".SCOV$GM"; // For SanCovGuardsSectionName.
1025 }
1026 if (TargetTriple.isOSBinFormatMachO())
1027 return "__DATA,__" + Section;
1028 return "__" + Section;
1029}
1030
1031std::string
1032ModuleSanitizerCoverage::getSectionStart(const std::string &Section) const {
1033 if (TargetTriple.isOSBinFormatMachO())
1034 return "\1section$start$__DATA$__" + Section;
1035 return "__start___" + Section;
1036}
1037
1038std::string
1039ModuleSanitizerCoverage::getSectionEnd(const std::string &Section) const {
1040 if (TargetTriple.isOSBinFormatMachO())
1041 return "\1section$end$__DATA$__" + Section;
1042 return "__stop___" + Section;
1043}
1044
1045void ModuleSanitizerCoverage::createFunctionControlFlow(Function &F) {
1047 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
1048
1049 for (auto &BB : F) {
1050 // blockaddress can not be used on function's entry block.
1051 if (&BB == &F.getEntryBlock())
1052 CFs.push_back((Constant *)IRB.CreatePointerCast(&F, PtrTy));
1053 else
1054 CFs.push_back((Constant *)IRB.CreatePointerCast(BlockAddress::get(&BB),
1055 PtrTy));
1056
1057 for (auto SuccBB : successors(&BB)) {
1058 assert(SuccBB != &F.getEntryBlock());
1059 CFs.push_back((Constant *)IRB.CreatePointerCast(BlockAddress::get(SuccBB),
1060 PtrTy));
1061 }
1062
1064
1065 for (auto &Inst : BB) {
1066 if (CallBase *CB = dyn_cast<CallBase>(&Inst)) {
1067 if (CB->isIndirectCall()) {
1068 // TODO(navidem): handle indirect calls, for now mark its existence.
1069 CFs.push_back((Constant *)IRB.CreateIntToPtr(
1070 ConstantInt::get(IntptrTy, -1), PtrTy));
1071 } else {
1072 auto CalledF = CB->getCalledFunction();
1073 if (CalledF && !CalledF->isIntrinsic())
1074 CFs.push_back(
1075 (Constant *)IRB.CreatePointerCast(CalledF, PtrTy));
1076 }
1077 }
1078 }
1079
1081 }
1082
1083 FunctionCFsArray = CreateFunctionLocalArrayInSection(
1084 CFs.size(), F, PtrTy, SanCovCFsSectionName);
1085 FunctionCFsArray->setInitializer(
1086 ConstantArray::get(ArrayType::get(PtrTy, CFs.size()), CFs));
1087 FunctionCFsArray->setConstant(true);
1088}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
static LVOptions Options
Definition: LVOptions.cpp:25
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Module.h This file contains the declarations for the Module class.
IntegerType * Int32Ty
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"))
const char LLVMTargetMachineRef LLVMPassBuilderOptionsRef Options
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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 > ClStackDepth("sanitizer-coverage-stack-depth", cl::desc("max stack depth tracing"), 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 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[]
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[]
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)
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 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[]
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 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.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:321
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:473
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:160
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:647
AttributeList addParamAttribute(LLVMContext &C, unsigned ArgNo, Attribute::AttrKind Kind) const
Add an argument attribute to the list.
Definition: Attributes.h:589
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
iterator end()
Definition: BasicBlock.h:443
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:409
const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
Definition: BasicBlock.cpp:490
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:452
const Instruction * getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode, a debug intrinsic,...
Definition: BasicBlock.cpp:393
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:165
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:221
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1846
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1494
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Definition: InstrTypes.h:1742
bool isIndirectCall() const
Return true if the callsite is an indirect call.
Value * getCalledOperand() const
Definition: InstrTypes.h:1735
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1291
This is the shared class of boolean and integer constants.
Definition: Constants.h:80
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:849
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:417
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
A debug info location.
Definition: DebugLoc.h:33
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Definition: Dominators.cpp:122
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:168
const BasicBlock & getEntryBlock() const
Definition: Function.h:783
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:973
void setComdat(Comdat *C)
Definition: Globals.cpp:197
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:537
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:68
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:254
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:51
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:60
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:57
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition: GlobalValue.h:53
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition: GlobalValue.h:61
Analysis pass providing a never-invalidated alias analysis result.
This instruction compares its operands according to the predicate given to the constructor.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2666
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:631
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
An instruction for reading from memory.
Definition: Instructions.h:184
MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
Definition: MDBuilder.cpp:47
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1541
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Definition: DerivedTypes.h:662
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
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:109
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:115
void abandon()
Mark an analysis as abandoned.
Definition: Analysis.h:162
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
size_t size() const
Definition: SmallVector.h:91
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
This is a utility class used to parse user-provided text files with "special case lists" for code san...
An instruction for storing to memory.
Definition: Instructions.h:317
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Multiway switch.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static IntegerType * getInt1Ty(LLVMContext &C)
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
static Type * getVoidTy(LLVMContext &C)
static IntegerType * getInt16Ty(LLVMContext &C)
static IntegerType * getInt8Ty(LLVMContext &C)
static IntegerType * getInt32Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:228
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
An efficient, type-erasing, non-owning reference to a callable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1465
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
static constexpr const StringLiteral & getSectionName(DebugSectionKind SectionKind)
Return the name of the section.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
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:1722
bool succ_empty(const Instruction *I)
Definition: CFG.h:255
auto successors(const MachineBasicBlock *BB)
FunctionCallee declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type * > InitArgTypes, bool Weak=false)
std::string getUniqueModuleId(Module *M)
Produce a unique identifier for this module by taking the MD5 sum of the names of the module's strong...
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:1647
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Comdat * getOrCreateFunctionComdat(Function &F, Triple &T)
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.
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.
Definition: ModuleUtils.cpp:73
auto predecessors(const MachineBasicBlock *BB)
bool pred_empty(const BasicBlock *BB)
Definition: CFG.h:118
BasicBlock::iterator PrepareToSplitEntryBlock(BasicBlock &BB, BasicBlock::iterator IP)
Instrumentation passes often insert conditional checks into entry blocks.
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 ...
void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
#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.
enum llvm::SanitizerCoverageOptions::Type CoverageType