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