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