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