1 //===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Coverage instrumentation done on LLVM IR level, works with Sanitizers.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/Analysis/EHPersonalities.h"
17 #include "llvm/Analysis/PostDominators.h"
18 #include "llvm/IR/CFG.h"
19 #include "llvm/IR/CallSite.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/DebugInfo.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/InlineAsm.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/MDBuilder.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Transforms/Instrumentation.h"
34 #include "llvm/Transforms/Scalar.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/ModuleUtils.h"
40 #define DEBUG_TYPE "sancov"
42 static const char *const SanCovTracePCIndirName =
43 "__sanitizer_cov_trace_pc_indir";
44 static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
45 static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
46 static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
47 static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
48 static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
49 static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
50 static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
51 static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
52 static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
53 static const char *const SanCovModuleCtorName = "sancov.module_ctor";
54 static const uint64_t SanCtorAndDtorPriority = 2;
56 static const char *const SanCovTracePCGuardName =
57 "__sanitizer_cov_trace_pc_guard";
58 static const char *const SanCovTracePCGuardInitName =
59 "__sanitizer_cov_trace_pc_guard_init";
60 static const char *const SanCov8bitCountersInitName =
61 "__sanitizer_cov_8bit_counters_init";
63 static const char *const SanCovGuardsSectionName = "sancov_guards";
64 static const char *const SanCovCountersSectionName = "sancov_cntrs";
66 static cl::opt<int> ClCoverageLevel(
67 "sanitizer-coverage-level",
68 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
69 "3: all blocks and critical edges"),
70 cl::Hidden, cl::init(0));
72 static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
73 cl::desc("Experimental pc tracing"), cl::Hidden,
76 static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
77 cl::desc("pc tracing with a guard"),
78 cl::Hidden, cl::init(false));
80 static cl::opt<bool> ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
81 cl::desc("increments 8-bit counter for every edge"),
82 cl::Hidden, cl::init(false));
85 ClCMPTracing("sanitizer-coverage-trace-compares",
86 cl::desc("Tracing of CMP and similar instructions"),
87 cl::Hidden, cl::init(false));
89 static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
90 cl::desc("Tracing of DIV instructions"),
91 cl::Hidden, cl::init(false));
93 static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
94 cl::desc("Tracing of GEP instructions"),
95 cl::Hidden, cl::init(false));
98 ClPruneBlocks("sanitizer-coverage-prune-blocks",
99 cl::desc("Reduce the number of instrumented blocks"),
100 cl::Hidden, cl::init(true));
104 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
105 SanitizerCoverageOptions Res;
106 switch (LegacyCoverageLevel) {
108 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
111 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
114 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
117 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
120 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
121 Res.IndirectCalls = true;
127 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
128 // Sets CoverageType and IndirectCalls.
129 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
130 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
131 Options.IndirectCalls |= CLOpts.IndirectCalls;
132 Options.TraceCmp |= ClCMPTracing;
133 Options.TraceDiv |= ClDIVTracing;
134 Options.TraceGep |= ClGEPTracing;
135 Options.TracePC |= ClTracePC;
136 Options.TracePCGuard |= ClTracePCGuard;
137 Options.Inline8bitCounters |= ClInline8bitCounters;
138 if (!Options.TracePCGuard && !Options.TracePC && !Options.Inline8bitCounters)
139 Options.TracePCGuard = true; // TracePCGuard is default.
140 Options.NoPrune |= !ClPruneBlocks;
144 class SanitizerCoverageModule : public ModulePass {
146 SanitizerCoverageModule(
147 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
148 : ModulePass(ID), Options(OverrideFromCL(Options)) {
149 initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
151 bool runOnModule(Module &M) override;
152 bool runOnFunction(Function &F);
153 static char ID; // Pass identification, replacement for typeid
154 StringRef getPassName() const override { return "SanitizerCoverageModule"; }
156 void getAnalysisUsage(AnalysisUsage &AU) const override {
157 AU.addRequired<DominatorTreeWrapperPass>();
158 AU.addRequired<PostDominatorTreeWrapperPass>();
162 void InjectCoverageForIndirectCalls(Function &F,
163 ArrayRef<Instruction *> IndirCalls);
164 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
165 void InjectTraceForDiv(Function &F,
166 ArrayRef<BinaryOperator *> DivTraceTargets);
167 void InjectTraceForGep(Function &F,
168 ArrayRef<GetElementPtrInst *> GepTraceTargets);
169 void InjectTraceForSwitch(Function &F,
170 ArrayRef<Instruction *> SwitchTraceTargets);
171 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
172 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
173 Function &F, Type *Ty,
174 const char *Section);
175 void CreateFunctionLocalArrays(size_t NumGuards, Function &F);
176 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx);
177 void CreateInitCallForSection(Module &M, const char *InitFunctionName,
178 Type *Ty, const std::string &Section);
180 void SetNoSanitizeMetadata(Instruction *I) {
181 I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
182 MDNode::get(*C, None));
185 std::string getSectionName(const std::string &Section) const;
186 std::string getSectionStart(const std::string &Section) const;
187 std::string getSectionEnd(const std::string &Section) const;
188 Function *SanCovTracePCIndir;
189 Function *SanCovTracePC, *SanCovTracePCGuard;
190 Function *SanCovTraceCmpFunction[4];
191 Function *SanCovTraceDivFunction[2];
192 Function *SanCovTraceGepFunction;
193 Function *SanCovTraceSwitchFunction;
195 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
200 const DataLayout *DL;
202 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
203 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
205 SanitizerCoverageOptions Options;
210 void SanitizerCoverageModule::CreateInitCallForSection(
211 Module &M, const char *InitFunctionName, Type *Ty,
212 const std::string &Section) {
213 IRBuilder<> IRB(M.getContext());
215 GlobalVariable *SecStart =
216 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
217 getSectionStart(Section));
218 SecStart->setVisibility(GlobalValue::HiddenVisibility);
219 GlobalVariable *SecEnd =
220 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
221 nullptr, getSectionEnd(Section));
222 SecEnd->setVisibility(GlobalValue::HiddenVisibility);
224 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
225 M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
226 {IRB.CreatePointerCast(SecStart, Ty), IRB.CreatePointerCast(SecEnd, Ty)});
228 if (TargetTriple.supportsCOMDAT()) {
229 // Use comdat to dedup CtorFunc.
230 CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
231 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
233 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
237 bool SanitizerCoverageModule::runOnModule(Module &M) {
238 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
240 C = &(M.getContext());
241 DL = &M.getDataLayout();
243 TargetTriple = Triple(M.getTargetTriple());
244 FunctionGuardArray = nullptr;
245 Function8bitCounterArray = nullptr;
246 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
247 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
248 Type *VoidTy = Type::getVoidTy(*C);
250 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
251 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
252 Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
253 Int64Ty = IRB.getInt64Ty();
254 Int32Ty = IRB.getInt32Ty();
255 Int8Ty = IRB.getInt8Ty();
257 SanCovTracePCIndir = checkSanitizerInterfaceFunction(
258 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
259 SanCovTraceCmpFunction[0] =
260 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
261 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
262 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
263 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
265 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
266 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
268 SanCovTraceCmpFunction[3] =
269 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
270 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
272 SanCovTraceDivFunction[0] =
273 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
274 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
275 SanCovTraceDivFunction[1] =
276 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
277 SanCovTraceDiv8, VoidTy, Int64Ty));
278 SanCovTraceGepFunction =
279 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
280 SanCovTraceGep, VoidTy, IntptrTy));
281 SanCovTraceSwitchFunction =
282 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
283 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
285 // We insert an empty inline asm after cov callbacks to avoid callback merge.
286 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
287 StringRef(""), StringRef(""),
288 /*hasSideEffects=*/true);
290 SanCovTracePC = checkSanitizerInterfaceFunction(
291 M.getOrInsertFunction(SanCovTracePCName, VoidTy));
292 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
293 SanCovTracePCGuardName, VoidTy, Int32PtrTy));
298 if (FunctionGuardArray)
299 CreateInitCallForSection(M, SanCovTracePCGuardInitName, Int32PtrTy,
300 SanCovGuardsSectionName);
301 if (Function8bitCounterArray)
302 CreateInitCallForSection(M, SanCov8bitCountersInitName, Int8PtrTy,
303 SanCovCountersSectionName);
308 // True if block has successors and it dominates all of them.
309 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
310 if (succ_begin(BB) == succ_end(BB))
313 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
314 if (!DT->dominates(BB, SUCC))
321 // True if block has predecessors and it postdominates all of them.
322 static bool isFullPostDominator(const BasicBlock *BB,
323 const PostDominatorTree *PDT) {
324 if (pred_begin(BB) == pred_end(BB))
327 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
328 if (!PDT->dominates(BB, PRED))
335 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
336 const DominatorTree *DT,
337 const PostDominatorTree *PDT,
338 const SanitizerCoverageOptions &Options) {
339 // Don't insert coverage for unreachable blocks: we will never call
340 // __sanitizer_cov() for them, so counting them in
341 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
342 // percentage. Also, unreachable instructions frequently have no debug
344 if (isa<UnreachableInst>(BB->getTerminator()))
347 // Don't insert coverage into blocks without a valid insertion point
348 // (catchswitch blocks).
349 if (BB->getFirstInsertionPt() == BB->end())
352 if (Options.NoPrune || &F.getEntryBlock() == BB)
355 // Do not instrument full dominators, or full post-dominators with multiple
357 return !isFullDominator(BB, DT)
358 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
361 bool SanitizerCoverageModule::runOnFunction(Function &F) {
364 if (F.getName().find(".module_ctor") != std::string::npos)
365 return false; // Should not instrument sanitizer init functions.
366 if (F.getName().startswith("__sanitizer_"))
367 return false; // Don't instrument __sanitizer_* callbacks.
368 // Don't instrument MSVC CRT configuration helpers. They may run before normal
370 if (F.getName() == "__local_stdio_printf_options" ||
371 F.getName() == "__local_stdio_scanf_options")
373 // Don't instrument functions using SEH for now. Splitting basic blocks like
374 // we do for coverage breaks WinEHPrepare.
375 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
376 if (F.hasPersonalityFn() &&
377 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
379 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
380 SplitAllCriticalEdges(F);
381 SmallVector<Instruction *, 8> IndirCalls;
382 SmallVector<BasicBlock *, 16> BlocksToInstrument;
383 SmallVector<Instruction *, 8> CmpTraceTargets;
384 SmallVector<Instruction *, 8> SwitchTraceTargets;
385 SmallVector<BinaryOperator *, 8> DivTraceTargets;
386 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
388 const DominatorTree *DT =
389 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
390 const PostDominatorTree *PDT =
391 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
394 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
395 BlocksToInstrument.push_back(&BB);
396 for (auto &Inst : BB) {
397 if (Options.IndirectCalls) {
399 if (CS && !CS.getCalledFunction())
400 IndirCalls.push_back(&Inst);
402 if (Options.TraceCmp) {
403 if (isa<ICmpInst>(&Inst))
404 CmpTraceTargets.push_back(&Inst);
405 if (isa<SwitchInst>(&Inst))
406 SwitchTraceTargets.push_back(&Inst);
408 if (Options.TraceDiv)
409 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
410 if (BO->getOpcode() == Instruction::SDiv ||
411 BO->getOpcode() == Instruction::UDiv)
412 DivTraceTargets.push_back(BO);
413 if (Options.TraceGep)
414 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
415 GepTraceTargets.push_back(GEP);
419 InjectCoverage(F, BlocksToInstrument);
420 InjectCoverageForIndirectCalls(F, IndirCalls);
421 InjectTraceForCmp(F, CmpTraceTargets);
422 InjectTraceForSwitch(F, SwitchTraceTargets);
423 InjectTraceForDiv(F, DivTraceTargets);
424 InjectTraceForGep(F, GepTraceTargets);
428 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
429 size_t NumElements, Function &F, Type *Ty, const char *Section) {
430 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
431 auto Array = new GlobalVariable(
432 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
433 Constant::getNullValue(ArrayTy), "__sancov_gen_");
434 if (auto Comdat = F.getComdat())
435 Array->setComdat(Comdat);
436 Array->setSection(getSectionName(Section));
439 void SanitizerCoverageModule::CreateFunctionLocalArrays(size_t NumGuards,
441 if (Options.TracePCGuard)
442 FunctionGuardArray = CreateFunctionLocalArrayInSection(
443 NumGuards, F, Int32Ty, SanCovGuardsSectionName);
444 if (Options.Inline8bitCounters)
445 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
446 NumGuards, F, Int8Ty, SanCovCountersSectionName);
449 bool SanitizerCoverageModule::InjectCoverage(Function &F,
450 ArrayRef<BasicBlock *> AllBlocks) {
451 if (AllBlocks.empty()) return false;
452 switch (Options.CoverageType) {
453 case SanitizerCoverageOptions::SCK_None:
455 case SanitizerCoverageOptions::SCK_Function:
456 CreateFunctionLocalArrays(1, F);
457 InjectCoverageAtBlock(F, F.getEntryBlock(), 0);
460 CreateFunctionLocalArrays(AllBlocks.size(), F);
461 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
462 InjectCoverageAtBlock(F, *AllBlocks[i], i);
468 // On every indirect call we call a run-time function
469 // __sanitizer_cov_indir_call* with two parameters:
471 // - global cache array that contains CacheSize pointers (zero-initialized).
472 // The cache is used to speed up recording the caller-callee pairs.
473 // The address of the caller is passed implicitly via caller PC.
474 // CacheSize is encoded in the name of the run-time function.
475 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
476 Function &F, ArrayRef<Instruction *> IndirCalls) {
477 if (IndirCalls.empty())
479 assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
480 for (auto I : IndirCalls) {
483 Value *Callee = CS.getCalledValue();
484 if (isa<InlineAsm>(Callee))
486 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
490 // For every switch statement we insert a call:
491 // __sanitizer_cov_trace_switch(CondValue,
492 // {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
494 void SanitizerCoverageModule::InjectTraceForSwitch(
495 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
496 for (auto I : SwitchTraceTargets) {
497 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
499 SmallVector<Constant *, 16> Initializers;
500 Value *Cond = SI->getCondition();
501 if (Cond->getType()->getScalarSizeInBits() >
502 Int64Ty->getScalarSizeInBits())
504 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
505 Initializers.push_back(
506 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
507 if (Cond->getType()->getScalarSizeInBits() <
508 Int64Ty->getScalarSizeInBits())
509 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
510 for (auto It : SI->cases()) {
511 Constant *C = It.getCaseValue();
512 if (C->getType()->getScalarSizeInBits() <
513 Int64Ty->getScalarSizeInBits())
514 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
515 Initializers.push_back(C);
517 std::sort(Initializers.begin() + 2, Initializers.end(),
518 [](const Constant *A, const Constant *B) {
519 return cast<ConstantInt>(A)->getLimitedValue() <
520 cast<ConstantInt>(B)->getLimitedValue();
522 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
523 GlobalVariable *GV = new GlobalVariable(
524 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
525 ConstantArray::get(ArrayOfInt64Ty, Initializers),
526 "__sancov_gen_cov_switch_values");
527 IRB.CreateCall(SanCovTraceSwitchFunction,
528 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
533 void SanitizerCoverageModule::InjectTraceForDiv(
534 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
535 for (auto BO : DivTraceTargets) {
537 Value *A1 = BO->getOperand(1);
538 if (isa<ConstantInt>(A1)) continue;
539 if (!A1->getType()->isIntegerTy())
541 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
542 int CallbackIdx = TypeSize == 32 ? 0 :
543 TypeSize == 64 ? 1 : -1;
544 if (CallbackIdx < 0) continue;
545 auto Ty = Type::getIntNTy(*C, TypeSize);
546 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
547 {IRB.CreateIntCast(A1, Ty, true)});
551 void SanitizerCoverageModule::InjectTraceForGep(
552 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
553 for (auto GEP : GepTraceTargets) {
554 IRBuilder<> IRB(GEP);
555 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
556 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
557 IRB.CreateCall(SanCovTraceGepFunction,
558 {IRB.CreateIntCast(*I, IntptrTy, true)});
562 void SanitizerCoverageModule::InjectTraceForCmp(
563 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
564 for (auto I : CmpTraceTargets) {
565 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
566 IRBuilder<> IRB(ICMP);
567 Value *A0 = ICMP->getOperand(0);
568 Value *A1 = ICMP->getOperand(1);
569 if (!A0->getType()->isIntegerTy())
571 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
572 int CallbackIdx = TypeSize == 8 ? 0 :
575 TypeSize == 64 ? 3 : -1;
576 if (CallbackIdx < 0) continue;
577 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
578 auto Ty = Type::getIntNTy(*C, TypeSize);
580 SanCovTraceCmpFunction[CallbackIdx],
581 {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
586 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
588 BasicBlock::iterator IP = BB.getFirstInsertionPt();
589 bool IsEntryBB = &BB == &F.getEntryBlock();
592 if (auto SP = F.getSubprogram())
593 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
594 // Keep static allocas and llvm.localescape calls in the entry block. Even
595 // if we aren't splitting the block, it's nice for allocas to be before
597 IP = PrepareToSplitEntryBlock(BB, IP);
599 EntryLoc = IP->getDebugLoc();
602 IRBuilder<> IRB(&*IP);
603 IRB.SetCurrentDebugLocation(EntryLoc);
604 if (Options.TracePC) {
605 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
606 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
608 if (Options.TracePCGuard) {
609 auto GuardPtr = IRB.CreateIntToPtr(
610 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
611 ConstantInt::get(IntptrTy, Idx * 4)),
613 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
614 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
616 if (Options.Inline8bitCounters) {
617 auto CounterPtr = IRB.CreateGEP(
618 Function8bitCounterArray,
619 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
620 auto Load = IRB.CreateLoad(CounterPtr);
621 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
622 auto Store = IRB.CreateStore(Inc, CounterPtr);
623 SetNoSanitizeMetadata(Load);
624 SetNoSanitizeMetadata(Store);
629 SanitizerCoverageModule::getSectionName(const std::string &Section) const {
630 if (TargetTriple.getObjectFormat() == Triple::COFF)
632 if (TargetTriple.isOSBinFormatMachO())
633 return "__DATA,__" + Section;
634 return "__" + Section;
638 SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
639 if (TargetTriple.isOSBinFormatMachO())
640 return "\1section$start$__DATA$__" + Section;
641 return "__start___" + Section;
645 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
646 if (TargetTriple.isOSBinFormatMachO())
647 return "\1section$end$__DATA$__" + Section;
648 return "__stop___" + Section;
652 char SanitizerCoverageModule::ID = 0;
653 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
654 "SanitizerCoverage: TODO."
657 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
658 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
659 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
660 "SanitizerCoverage: TODO."
663 ModulePass *llvm::createSanitizerCoverageModulePass(
664 const SanitizerCoverageOptions &Options) {
665 return new SanitizerCoverageModule(Options);