xref: /llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp (revision 075ed3eec1b13719dfd0bcb80ef2b51b9065fc61)
1 //===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Coverage instrumentation that works with AddressSanitizer
11 // and potentially with other Sanitizers.
12 //
13 // We create a Guard variable with the same linkage
14 // as the function and inject this code into the entry block (SCK_Function)
15 // or all blocks (SCK_BB):
16 // if (Guard < 0) {
17 //    __sanitizer_cov(&Guard);
18 // }
19 // The accesses to Guard are atomic. The rest of the logic is
20 // in __sanitizer_cov (it's fine to call it more than once).
21 //
22 // With SCK_Edge we also split critical edges this effectively
23 // instrumenting all edges.
24 //
25 // This coverage implementation provides very limited data:
26 // it only tells if a given function (block) was ever executed. No counters.
27 // But for many use cases this is what we need and the added slowdown small.
28 //
29 //===----------------------------------------------------------------------===//
30 
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/IR/CFG.h"
35 #include "llvm/IR/CallSite.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/DebugInfo.h"
38 #include "llvm/IR/Dominators.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/InlineAsm.h"
42 #include "llvm/IR/LLVMContext.h"
43 #include "llvm/IR/MDBuilder.h"
44 #include "llvm/IR/Module.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Transforms/Instrumentation.h"
50 #include "llvm/Transforms/Scalar.h"
51 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
52 #include "llvm/Transforms/Utils/ModuleUtils.h"
53 
54 using namespace llvm;
55 
56 #define DEBUG_TYPE "sancov"
57 
58 static const char *const kSanCovModuleInitName = "__sanitizer_cov_module_init";
59 static const char *const kSanCovName = "__sanitizer_cov";
60 static const char *const kSanCovWithCheckName = "__sanitizer_cov_with_check";
61 static const char *const kSanCovIndirCallName = "__sanitizer_cov_indir_call16";
62 static const char *const kSanCovTracePCIndir = "__sanitizer_cov_trace_pc_indir";
63 static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter";
64 static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block";
65 static const char *const kSanCovTracePC = "__sanitizer_cov_trace_pc";
66 static const char *const kSanCovTraceCmp = "__sanitizer_cov_trace_cmp";
67 static const char *const kSanCovTraceSwitch = "__sanitizer_cov_trace_switch";
68 static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
69 static const uint64_t    kSanCtorAndDtorPriority = 2;
70 
71 static cl::opt<int> ClCoverageLevel("sanitizer-coverage-level",
72        cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
73                 "3: all blocks and critical edges, "
74                 "4: above plus indirect calls"),
75        cl::Hidden, cl::init(0));
76 
77 static cl::opt<unsigned> ClCoverageBlockThreshold(
78     "sanitizer-coverage-block-threshold",
79     cl::desc("Use a callback with a guard check inside it if there are"
80              " more than this number of blocks."),
81     cl::Hidden, cl::init(500));
82 
83 static cl::opt<bool>
84     ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
85                           cl::desc("Experimental basic-block tracing: insert "
86                                    "callbacks at every basic block"),
87                           cl::Hidden, cl::init(false));
88 
89 static cl::opt<bool> ClExperimentalTracePC("sanitizer-coverage-trace-pc",
90                                            cl::desc("Experimental pc tracing"),
91                                            cl::Hidden, cl::init(false));
92 
93 static cl::opt<bool>
94     ClExperimentalCMPTracing("sanitizer-coverage-experimental-trace-compares",
95                              cl::desc("Experimental tracing of CMP and similar "
96                                       "instructions"),
97                              cl::Hidden, cl::init(false));
98 
99 static cl::opt<bool> ClPruneBlocks(
100     "sanitizer-coverage-prune-blocks",
101     cl::desc("Reduce the number of instrumented blocks (experimental)"),
102     cl::Hidden, cl::init(false));
103 
104 // Experimental 8-bit counters used as an additional search heuristic during
105 // coverage-guided fuzzing.
106 // The counters are not thread-friendly:
107 //   - contention on these counters may cause significant slowdown;
108 //   - the counter updates are racy and the results may be inaccurate.
109 // They are also inaccurate due to 8-bit integer overflow.
110 static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters",
111                                        cl::desc("Experimental 8-bit counters"),
112                                        cl::Hidden, cl::init(false));
113 
114 namespace {
115 
116 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
117   SanitizerCoverageOptions Res;
118   switch (LegacyCoverageLevel) {
119   case 0:
120     Res.CoverageType = SanitizerCoverageOptions::SCK_None;
121     break;
122   case 1:
123     Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
124     break;
125   case 2:
126     Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
127     break;
128   case 3:
129     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
130     break;
131   case 4:
132     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
133     Res.IndirectCalls = true;
134     break;
135   }
136   return Res;
137 }
138 
139 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
140   // Sets CoverageType and IndirectCalls.
141   SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
142   Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
143   Options.IndirectCalls |= CLOpts.IndirectCalls;
144   Options.TraceBB |= ClExperimentalTracing;
145   Options.TraceCmp |= ClExperimentalCMPTracing;
146   Options.Use8bitCounters |= ClUse8bitCounters;
147   Options.TracePC |= ClExperimentalTracePC;
148   return Options;
149 }
150 
151 class SanitizerCoverageModule : public ModulePass {
152  public:
153   SanitizerCoverageModule(
154       const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
155       : ModulePass(ID), Options(OverrideFromCL(Options)) {}
156   bool runOnModule(Module &M) override;
157   bool runOnFunction(Function &F);
158   static char ID;  // Pass identification, replacement for typeid
159   const char *getPassName() const override {
160     return "SanitizerCoverageModule";
161   }
162 
163  private:
164   void InjectCoverageForIndirectCalls(Function &F,
165                                       ArrayRef<Instruction *> IndirCalls);
166   void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
167   void InjectTraceForSwitch(Function &F,
168                             ArrayRef<Instruction *> SwitchTraceTargets);
169   bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
170   void SetNoSanitizeMetadata(Instruction *I);
171   void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
172   unsigned NumberOfInstrumentedBlocks() {
173     return SanCovFunction->getNumUses() +
174            SanCovWithCheckFunction->getNumUses() + SanCovTraceBB->getNumUses() +
175            SanCovTraceEnter->getNumUses();
176   }
177   Function *SanCovFunction;
178   Function *SanCovWithCheckFunction;
179   Function *SanCovIndirCallFunction, *SanCovTracePCIndir;
180   Function *SanCovTraceEnter, *SanCovTraceBB, *SanCovTracePC;
181   Function *SanCovTraceCmpFunction;
182   Function *SanCovTraceSwitchFunction;
183   InlineAsm *EmptyAsm;
184   Type *IntptrTy, *Int64Ty, *Int64PtrTy;
185   Module *CurModule;
186   LLVMContext *C;
187   const DataLayout *DL;
188 
189   GlobalVariable *GuardArray;
190   GlobalVariable *EightBitCounterArray;
191 
192   SanitizerCoverageOptions Options;
193 };
194 
195 }  // namespace
196 
197 bool SanitizerCoverageModule::runOnModule(Module &M) {
198   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
199     return false;
200   C = &(M.getContext());
201   DL = &M.getDataLayout();
202   CurModule = &M;
203   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
204   Type *VoidTy = Type::getVoidTy(*C);
205   IRBuilder<> IRB(*C);
206   Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
207   Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
208   Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
209   Int64Ty = IRB.getInt64Ty();
210 
211   SanCovFunction = checkSanitizerInterfaceFunction(
212       M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr));
213   SanCovWithCheckFunction = checkSanitizerInterfaceFunction(
214       M.getOrInsertFunction(kSanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
215   SanCovTracePCIndir =
216       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
217           kSanCovTracePCIndir, VoidTy, IntptrTy, nullptr));
218   SanCovIndirCallFunction =
219       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
220           kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
221   SanCovTraceCmpFunction =
222       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
223           kSanCovTraceCmp, VoidTy, Int64Ty, Int64Ty, Int64Ty, nullptr));
224   SanCovTraceSwitchFunction =
225       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
226           kSanCovTraceSwitch, VoidTy, Int64Ty, Int64PtrTy, nullptr));
227 
228   // We insert an empty inline asm after cov callbacks to avoid callback merge.
229   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
230                             StringRef(""), StringRef(""),
231                             /*hasSideEffects=*/true);
232 
233   SanCovTracePC = checkSanitizerInterfaceFunction(
234       M.getOrInsertFunction(kSanCovTracePC, VoidTy, nullptr));
235   SanCovTraceEnter = checkSanitizerInterfaceFunction(
236       M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr));
237   SanCovTraceBB = checkSanitizerInterfaceFunction(
238       M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr));
239 
240   // At this point we create a dummy array of guards because we don't
241   // know how many elements we will need.
242   Type *Int32Ty = IRB.getInt32Ty();
243   Type *Int8Ty = IRB.getInt8Ty();
244 
245   GuardArray =
246       new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
247                          nullptr, "__sancov_gen_cov_tmp");
248   if (Options.Use8bitCounters)
249     EightBitCounterArray =
250         new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
251                            nullptr, "__sancov_gen_cov_tmp");
252 
253   for (auto &F : M)
254     runOnFunction(F);
255 
256   auto N = NumberOfInstrumentedBlocks();
257 
258   // Now we know how many elements we need. Create an array of guards
259   // with one extra element at the beginning for the size.
260   Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1);
261   GlobalVariable *RealGuardArray = new GlobalVariable(
262       M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
263       Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
264 
265 
266   // Replace the dummy array with the real one.
267   GuardArray->replaceAllUsesWith(
268       IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
269   GuardArray->eraseFromParent();
270 
271   GlobalVariable *RealEightBitCounterArray;
272   if (Options.Use8bitCounters) {
273     // Make sure the array is 16-aligned.
274     static const int kCounterAlignment = 16;
275     Type *Int8ArrayNTy = ArrayType::get(Int8Ty, alignTo(N, kCounterAlignment));
276     RealEightBitCounterArray = new GlobalVariable(
277         M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
278         Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
279     RealEightBitCounterArray->setAlignment(kCounterAlignment);
280     EightBitCounterArray->replaceAllUsesWith(
281         IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
282     EightBitCounterArray->eraseFromParent();
283   }
284 
285   // Create variable for module (compilation unit) name
286   Constant *ModNameStrConst =
287       ConstantDataArray::getString(M.getContext(), M.getName(), true);
288   GlobalVariable *ModuleName =
289       new GlobalVariable(M, ModNameStrConst->getType(), true,
290                          GlobalValue::PrivateLinkage, ModNameStrConst);
291 
292   if (!Options.TracePC) {
293     Function *CtorFunc;
294     std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
295         M, kSanCovModuleCtorName, kSanCovModuleInitName,
296         {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy},
297         {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
298           ConstantInt::get(IntptrTy, N),
299           Options.Use8bitCounters
300               ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
301               : Constant::getNullValue(Int8PtrTy),
302           IRB.CreatePointerCast(ModuleName, Int8PtrTy)});
303 
304     appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
305   }
306 
307   return true;
308 }
309 
310 static bool shouldInstrumentBlock(const BasicBlock *BB,
311                                   const DominatorTree *DT) {
312   if (!ClPruneBlocks)
313     return true;
314   if (succ_begin(BB) == succ_end(BB))
315     return true;
316 
317   // Check if BB dominates all its successors.
318   for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
319     if (!DT->dominates(BB, SUCC))
320       return true;
321   }
322 
323   return false;
324 }
325 
326 bool SanitizerCoverageModule::runOnFunction(Function &F) {
327   if (F.empty()) return false;
328   if (F.getName().find(".module_ctor") != std::string::npos)
329     return false;  // Should not instrument sanitizer init functions.
330   // Don't instrument functions using SEH for now. Splitting basic blocks like
331   // we do for coverage breaks WinEHPrepare.
332   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
333   if (F.hasPersonalityFn() &&
334       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
335     return false;
336   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
337     SplitAllCriticalEdges(F);
338   SmallVector<Instruction*, 8> IndirCalls;
339   SmallVector<BasicBlock *, 16> BlocksToInstrument;
340   SmallVector<Instruction*, 8> CmpTraceTargets;
341   SmallVector<Instruction*, 8> SwitchTraceTargets;
342 
343   DominatorTree DT;
344   DT.recalculate(F);
345   for (auto &BB : F) {
346     if (shouldInstrumentBlock(&BB, &DT))
347       BlocksToInstrument.push_back(&BB);
348     for (auto &Inst : BB) {
349       if (Options.IndirectCalls) {
350         CallSite CS(&Inst);
351         if (CS && !CS.getCalledFunction())
352           IndirCalls.push_back(&Inst);
353       }
354       if (Options.TraceCmp) {
355         if (isa<ICmpInst>(&Inst))
356           CmpTraceTargets.push_back(&Inst);
357         if (isa<SwitchInst>(&Inst))
358           SwitchTraceTargets.push_back(&Inst);
359       }
360     }
361   }
362 
363   InjectCoverage(F, BlocksToInstrument);
364   InjectCoverageForIndirectCalls(F, IndirCalls);
365   InjectTraceForCmp(F, CmpTraceTargets);
366   InjectTraceForSwitch(F, SwitchTraceTargets);
367   return true;
368 }
369 
370 bool SanitizerCoverageModule::InjectCoverage(Function &F,
371                                              ArrayRef<BasicBlock *> AllBlocks) {
372   switch (Options.CoverageType) {
373   case SanitizerCoverageOptions::SCK_None:
374     return false;
375   case SanitizerCoverageOptions::SCK_Function:
376     InjectCoverageAtBlock(F, F.getEntryBlock(), false);
377     return true;
378   default: {
379     bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size();
380     for (auto BB : AllBlocks)
381       InjectCoverageAtBlock(F, *BB, UseCalls);
382     return true;
383   }
384   }
385 }
386 
387 // On every indirect call we call a run-time function
388 // __sanitizer_cov_indir_call* with two parameters:
389 //   - callee address,
390 //   - global cache array that contains kCacheSize pointers (zero-initialized).
391 //     The cache is used to speed up recording the caller-callee pairs.
392 // The address of the caller is passed implicitly via caller PC.
393 // kCacheSize is encoded in the name of the run-time function.
394 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
395     Function &F, ArrayRef<Instruction *> IndirCalls) {
396   if (IndirCalls.empty()) return;
397   const int kCacheSize = 16;
398   const int kCacheAlignment = 64;  // Align for better performance.
399   Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
400   for (auto I : IndirCalls) {
401     IRBuilder<> IRB(I);
402     CallSite CS(I);
403     Value *Callee = CS.getCalledValue();
404     if (isa<InlineAsm>(Callee)) continue;
405     GlobalVariable *CalleeCache = new GlobalVariable(
406         *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
407         Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
408     CalleeCache->setAlignment(kCacheAlignment);
409     if (Options.TracePC)
410       IRB.CreateCall(SanCovTracePCIndir,
411                      IRB.CreatePointerCast(Callee, IntptrTy));
412     else
413       IRB.CreateCall(SanCovIndirCallFunction,
414                      {IRB.CreatePointerCast(Callee, IntptrTy),
415                        IRB.CreatePointerCast(CalleeCache, IntptrTy)});
416   }
417 }
418 
419 // For every switch statement we insert a call:
420 // __sanitizer_cov_trace_switch(CondValue,
421 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
422 
423 void SanitizerCoverageModule::InjectTraceForSwitch(
424     Function &F, ArrayRef<Instruction *> SwitchTraceTargets) {
425   for (auto I : SwitchTraceTargets) {
426     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
427       IRBuilder<> IRB(I);
428       SmallVector<Constant *, 16> Initializers;
429       Value *Cond = SI->getCondition();
430       if (Cond->getType()->getScalarSizeInBits() >
431           Int64Ty->getScalarSizeInBits())
432         continue;
433       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
434       Initializers.push_back(
435           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
436       if (Cond->getType()->getScalarSizeInBits() <
437           Int64Ty->getScalarSizeInBits())
438         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
439       for (auto It: SI->cases()) {
440         Constant *C = It.getCaseValue();
441         if (C->getType()->getScalarSizeInBits() <
442             Int64Ty->getScalarSizeInBits())
443           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
444         Initializers.push_back(C);
445       }
446       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
447       GlobalVariable *GV = new GlobalVariable(
448           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
449           ConstantArray::get(ArrayOfInt64Ty, Initializers),
450           "__sancov_gen_cov_switch_values");
451       IRB.CreateCall(SanCovTraceSwitchFunction,
452                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
453     }
454   }
455 }
456 
457 
458 void SanitizerCoverageModule::InjectTraceForCmp(
459     Function &F, ArrayRef<Instruction *> CmpTraceTargets) {
460   for (auto I : CmpTraceTargets) {
461     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
462       IRBuilder<> IRB(ICMP);
463       Value *A0 = ICMP->getOperand(0);
464       Value *A1 = ICMP->getOperand(1);
465       if (!A0->getType()->isIntegerTy()) continue;
466       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
467       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
468       IRB.CreateCall(
469           SanCovTraceCmpFunction,
470           {ConstantInt::get(Int64Ty, (TypeSize << 32) | ICMP->getPredicate()),
471            IRB.CreateIntCast(A0, Int64Ty, true),
472            IRB.CreateIntCast(A1, Int64Ty, true)});
473     }
474   }
475 }
476 
477 void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) {
478   I->setMetadata(
479       I->getModule()->getMDKindID("nosanitize"), MDNode::get(*C, None));
480 }
481 
482 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
483                                                     bool UseCalls) {
484   // Don't insert coverage for unreachable blocks: we will never call
485   // __sanitizer_cov() for them, so counting them in
486   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
487   // percentage. Also, unreachable instructions frequently have no debug
488   // locations.
489   if (isa<UnreachableInst>(BB.getTerminator()))
490     return;
491   BasicBlock::iterator IP = BB.getFirstInsertionPt();
492 
493   bool IsEntryBB = &BB == &F.getEntryBlock();
494   DebugLoc EntryLoc;
495   if (IsEntryBB) {
496     if (auto SP = F.getSubprogram())
497       EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
498     // Keep static allocas and llvm.localescape calls in the entry block.  Even
499     // if we aren't splitting the block, it's nice for allocas to be before
500     // calls.
501     IP = PrepareToSplitEntryBlock(BB, IP);
502   } else {
503     EntryLoc = IP->getDebugLoc();
504   }
505 
506   IRBuilder<> IRB(&*IP);
507   IRB.SetCurrentDebugLocation(EntryLoc);
508   Value *GuardP = IRB.CreateAdd(
509       IRB.CreatePointerCast(GuardArray, IntptrTy),
510       ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4));
511   Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
512   GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
513   if (Options.TracePC) {
514     IRB.CreateCall(SanCovTracePC);
515   } else if (Options.TraceBB) {
516     IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
517   } else if (UseCalls) {
518     IRB.CreateCall(SanCovWithCheckFunction, GuardP);
519   } else {
520     LoadInst *Load = IRB.CreateLoad(GuardP);
521     Load->setAtomic(Monotonic);
522     Load->setAlignment(4);
523     SetNoSanitizeMetadata(Load);
524     Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
525     Instruction *Ins = SplitBlockAndInsertIfThen(
526         Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
527     IRB.SetInsertPoint(Ins);
528     IRB.SetCurrentDebugLocation(EntryLoc);
529     // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
530     IRB.CreateCall(SanCovFunction, GuardP);
531     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
532   }
533 
534   if (Options.Use8bitCounters) {
535     IRB.SetInsertPoint(&*IP);
536     Value *P = IRB.CreateAdd(
537         IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
538         ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1));
539     P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
540     LoadInst *LI = IRB.CreateLoad(P);
541     Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
542     StoreInst *SI = IRB.CreateStore(Inc, P);
543     SetNoSanitizeMetadata(LI);
544     SetNoSanitizeMetadata(SI);
545   }
546 }
547 
548 char SanitizerCoverageModule::ID = 0;
549 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
550     "SanitizerCoverage: TODO."
551     "ModulePass", false, false)
552 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
553 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
554 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
555     "SanitizerCoverage: TODO."
556     "ModulePass", false, false)
557 ModulePass *llvm::createSanitizerCoverageModulePass(
558     const SanitizerCoverageOptions &Options) {
559   return new SanitizerCoverageModule(Options);
560 }
561