xref: /llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp (revision c485ca05ac279b7bced1caa77f05666090af2ad6)
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 done on LLVM IR level, works with Sanitizers.
11 //
12 //===----------------------------------------------------------------------===//
13 
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"
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "sancov"
41 
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;
55 
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";
62 
63 static const char *const SanCovGuardsSectionName = "sancov_guards";
64 static const char *const SanCovCountersSectionName = "sancov_cntrs";
65 
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));
71 
72 static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
73                                cl::desc("Experimental pc tracing"), cl::Hidden,
74                                cl::init(false));
75 
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));
79 
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));
83 
84 static cl::opt<bool>
85     ClCMPTracing("sanitizer-coverage-trace-compares",
86                  cl::desc("Tracing of CMP and similar instructions"),
87                  cl::Hidden, cl::init(false));
88 
89 static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
90                                   cl::desc("Tracing of DIV instructions"),
91                                   cl::Hidden, cl::init(false));
92 
93 static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
94                                   cl::desc("Tracing of GEP instructions"),
95                                   cl::Hidden, cl::init(false));
96 
97 static cl::opt<bool>
98     ClPruneBlocks("sanitizer-coverage-prune-blocks",
99                   cl::desc("Reduce the number of instrumented blocks"),
100                   cl::Hidden, cl::init(true));
101 
102 namespace {
103 
104 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
105   SanitizerCoverageOptions Res;
106   switch (LegacyCoverageLevel) {
107   case 0:
108     Res.CoverageType = SanitizerCoverageOptions::SCK_None;
109     break;
110   case 1:
111     Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
112     break;
113   case 2:
114     Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
115     break;
116   case 3:
117     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
118     break;
119   case 4:
120     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
121     Res.IndirectCalls = true;
122     break;
123   }
124   return Res;
125 }
126 
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;
141   return Options;
142 }
143 
144 class SanitizerCoverageModule : public ModulePass {
145 public:
146   SanitizerCoverageModule(
147       const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
148       : ModulePass(ID), Options(OverrideFromCL(Options)) {
149     initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
150   }
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"; }
155 
156   void getAnalysisUsage(AnalysisUsage &AU) const override {
157     AU.addRequired<DominatorTreeWrapperPass>();
158     AU.addRequired<PostDominatorTreeWrapperPass>();
159   }
160 
161 private:
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);
179 
180   void SetNoSanitizeMetadata(Instruction *I) {
181     I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
182                    MDNode::get(*C, None));
183   }
184 
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;
194   InlineAsm *EmptyAsm;
195   Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
196       *Int8Ty, *Int8PtrTy;
197   Module *CurModule;
198   Triple TargetTriple;
199   LLVMContext *C;
200   const DataLayout *DL;
201 
202   GlobalVariable *FunctionGuardArray;  // for trace-pc-guard.
203   GlobalVariable *Function8bitCounterArray;  // for inline-8bit-counters.
204 
205   SanitizerCoverageOptions Options;
206 };
207 
208 } // namespace
209 
210 void SanitizerCoverageModule::CreateInitCallForSection(
211     Module &M, const char *InitFunctionName, Type *Ty,
212     const std::string &Section) {
213   IRBuilder<> IRB(M.getContext());
214   Function *CtorFunc;
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);
223 
224   std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
225       M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
226       {IRB.CreatePointerCast(SecStart, Ty), IRB.CreatePointerCast(SecEnd, Ty)});
227 
228   if (TargetTriple.supportsCOMDAT()) {
229     // Use comdat to dedup CtorFunc.
230     CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
231     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
232   } else {
233     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
234   }
235 }
236 
237 bool SanitizerCoverageModule::runOnModule(Module &M) {
238   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
239     return false;
240   C = &(M.getContext());
241   DL = &M.getDataLayout();
242   CurModule = &M;
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);
249   IRBuilder<> IRB(*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();
256 
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(),
264                             IRB.getInt16Ty()));
265   SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
266       M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
267                             IRB.getInt32Ty()));
268   SanCovTraceCmpFunction[3] =
269       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
270           SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
271 
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));
284   // Make sure smaller parameters are zero-extended to i64 as required by the
285   // x86_64 ABI.
286   if (TargetTriple.getArch() == Triple::x86_64) {
287     for (int i = 0; i < 3; i++) {
288       SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
289       SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
290     }
291     SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
292   }
293 
294 
295   // We insert an empty inline asm after cov callbacks to avoid callback merge.
296   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
297                             StringRef(""), StringRef(""),
298                             /*hasSideEffects=*/true);
299 
300   SanCovTracePC = checkSanitizerInterfaceFunction(
301       M.getOrInsertFunction(SanCovTracePCName, VoidTy));
302   SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
303       SanCovTracePCGuardName, VoidTy, Int32PtrTy));
304 
305   for (auto &F : M)
306     runOnFunction(F);
307 
308   if (FunctionGuardArray)
309     CreateInitCallForSection(M, SanCovTracePCGuardInitName, Int32PtrTy,
310                              SanCovGuardsSectionName);
311   if (Function8bitCounterArray)
312     CreateInitCallForSection(M, SanCov8bitCountersInitName, Int8PtrTy,
313                              SanCovCountersSectionName);
314 
315   return true;
316 }
317 
318 // True if block has successors and it dominates all of them.
319 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
320   if (succ_begin(BB) == succ_end(BB))
321     return false;
322 
323   for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
324     if (!DT->dominates(BB, SUCC))
325       return false;
326   }
327 
328   return true;
329 }
330 
331 // True if block has predecessors and it postdominates all of them.
332 static bool isFullPostDominator(const BasicBlock *BB,
333                                 const PostDominatorTree *PDT) {
334   if (pred_begin(BB) == pred_end(BB))
335     return false;
336 
337   for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
338     if (!PDT->dominates(BB, PRED))
339       return false;
340   }
341 
342   return true;
343 }
344 
345 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
346                                   const DominatorTree *DT,
347                                   const PostDominatorTree *PDT,
348                                   const SanitizerCoverageOptions &Options) {
349   // Don't insert coverage for unreachable blocks: we will never call
350   // __sanitizer_cov() for them, so counting them in
351   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
352   // percentage. Also, unreachable instructions frequently have no debug
353   // locations.
354   if (isa<UnreachableInst>(BB->getTerminator()))
355     return false;
356 
357   // Don't insert coverage into blocks without a valid insertion point
358   // (catchswitch blocks).
359   if (BB->getFirstInsertionPt() == BB->end())
360     return false;
361 
362   if (Options.NoPrune || &F.getEntryBlock() == BB)
363     return true;
364 
365   if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
366       &F.getEntryBlock() != BB)
367     return false;
368 
369   // Do not instrument full dominators, or full post-dominators with multiple
370   // predecessors.
371   return !isFullDominator(BB, DT)
372     && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
373 }
374 
375 bool SanitizerCoverageModule::runOnFunction(Function &F) {
376   if (F.empty())
377     return false;
378   if (F.getName().find(".module_ctor") != std::string::npos)
379     return false; // Should not instrument sanitizer init functions.
380   if (F.getName().startswith("__sanitizer_"))
381     return false;  // Don't instrument __sanitizer_* callbacks.
382   // Don't instrument MSVC CRT configuration helpers. They may run before normal
383   // initialization.
384   if (F.getName() == "__local_stdio_printf_options" ||
385       F.getName() == "__local_stdio_scanf_options")
386     return false;
387   // Don't instrument functions using SEH for now. Splitting basic blocks like
388   // we do for coverage breaks WinEHPrepare.
389   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
390   if (F.hasPersonalityFn() &&
391       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
392     return false;
393   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
394     SplitAllCriticalEdges(F);
395   SmallVector<Instruction *, 8> IndirCalls;
396   SmallVector<BasicBlock *, 16> BlocksToInstrument;
397   SmallVector<Instruction *, 8> CmpTraceTargets;
398   SmallVector<Instruction *, 8> SwitchTraceTargets;
399   SmallVector<BinaryOperator *, 8> DivTraceTargets;
400   SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
401 
402   const DominatorTree *DT =
403       &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
404   const PostDominatorTree *PDT =
405       &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
406 
407   for (auto &BB : F) {
408     if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
409       BlocksToInstrument.push_back(&BB);
410     for (auto &Inst : BB) {
411       if (Options.IndirectCalls) {
412         CallSite CS(&Inst);
413         if (CS && !CS.getCalledFunction())
414           IndirCalls.push_back(&Inst);
415       }
416       if (Options.TraceCmp) {
417         if (isa<ICmpInst>(&Inst))
418           CmpTraceTargets.push_back(&Inst);
419         if (isa<SwitchInst>(&Inst))
420           SwitchTraceTargets.push_back(&Inst);
421       }
422       if (Options.TraceDiv)
423         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
424           if (BO->getOpcode() == Instruction::SDiv ||
425               BO->getOpcode() == Instruction::UDiv)
426             DivTraceTargets.push_back(BO);
427       if (Options.TraceGep)
428         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
429           GepTraceTargets.push_back(GEP);
430    }
431   }
432 
433   InjectCoverage(F, BlocksToInstrument);
434   InjectCoverageForIndirectCalls(F, IndirCalls);
435   InjectTraceForCmp(F, CmpTraceTargets);
436   InjectTraceForSwitch(F, SwitchTraceTargets);
437   InjectTraceForDiv(F, DivTraceTargets);
438   InjectTraceForGep(F, GepTraceTargets);
439   return true;
440 }
441 
442 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
443     size_t NumElements, Function &F, Type *Ty, const char *Section) {
444   ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
445   auto Array = new GlobalVariable(
446       *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
447       Constant::getNullValue(ArrayTy), "__sancov_gen_");
448   if (auto Comdat = F.getComdat())
449     Array->setComdat(Comdat);
450   Array->setSection(getSectionName(Section));
451   return Array;
452 }
453 void SanitizerCoverageModule::CreateFunctionLocalArrays(size_t NumGuards,
454                                                        Function &F) {
455   if (Options.TracePCGuard)
456     FunctionGuardArray = CreateFunctionLocalArrayInSection(
457         NumGuards, F, Int32Ty, SanCovGuardsSectionName);
458   if (Options.Inline8bitCounters)
459     Function8bitCounterArray = CreateFunctionLocalArrayInSection(
460         NumGuards, F, Int8Ty, SanCovCountersSectionName);
461 }
462 
463 bool SanitizerCoverageModule::InjectCoverage(Function &F,
464                                              ArrayRef<BasicBlock *> AllBlocks) {
465   if (AllBlocks.empty()) return false;
466   CreateFunctionLocalArrays(AllBlocks.size(), F);
467   for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
468     InjectCoverageAtBlock(F, *AllBlocks[i], i);
469   return true;
470 }
471 
472 // On every indirect call we call a run-time function
473 // __sanitizer_cov_indir_call* with two parameters:
474 //   - callee address,
475 //   - global cache array that contains CacheSize pointers (zero-initialized).
476 //     The cache is used to speed up recording the caller-callee pairs.
477 // The address of the caller is passed implicitly via caller PC.
478 // CacheSize is encoded in the name of the run-time function.
479 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
480     Function &F, ArrayRef<Instruction *> IndirCalls) {
481   if (IndirCalls.empty())
482     return;
483   assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
484   for (auto I : IndirCalls) {
485     IRBuilder<> IRB(I);
486     CallSite CS(I);
487     Value *Callee = CS.getCalledValue();
488     if (isa<InlineAsm>(Callee))
489       continue;
490     IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
491   }
492 }
493 
494 // For every switch statement we insert a call:
495 // __sanitizer_cov_trace_switch(CondValue,
496 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
497 
498 void SanitizerCoverageModule::InjectTraceForSwitch(
499     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
500   for (auto I : SwitchTraceTargets) {
501     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
502       IRBuilder<> IRB(I);
503       SmallVector<Constant *, 16> Initializers;
504       Value *Cond = SI->getCondition();
505       if (Cond->getType()->getScalarSizeInBits() >
506           Int64Ty->getScalarSizeInBits())
507         continue;
508       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
509       Initializers.push_back(
510           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
511       if (Cond->getType()->getScalarSizeInBits() <
512           Int64Ty->getScalarSizeInBits())
513         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
514       for (auto It : SI->cases()) {
515         Constant *C = It.getCaseValue();
516         if (C->getType()->getScalarSizeInBits() <
517             Int64Ty->getScalarSizeInBits())
518           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
519         Initializers.push_back(C);
520       }
521       std::sort(Initializers.begin() + 2, Initializers.end(),
522                 [](const Constant *A, const Constant *B) {
523                   return cast<ConstantInt>(A)->getLimitedValue() <
524                          cast<ConstantInt>(B)->getLimitedValue();
525                 });
526       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
527       GlobalVariable *GV = new GlobalVariable(
528           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
529           ConstantArray::get(ArrayOfInt64Ty, Initializers),
530           "__sancov_gen_cov_switch_values");
531       IRB.CreateCall(SanCovTraceSwitchFunction,
532                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
533     }
534   }
535 }
536 
537 void SanitizerCoverageModule::InjectTraceForDiv(
538     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
539   for (auto BO : DivTraceTargets) {
540     IRBuilder<> IRB(BO);
541     Value *A1 = BO->getOperand(1);
542     if (isa<ConstantInt>(A1)) continue;
543     if (!A1->getType()->isIntegerTy())
544       continue;
545     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
546     int CallbackIdx = TypeSize == 32 ? 0 :
547         TypeSize == 64 ? 1 : -1;
548     if (CallbackIdx < 0) continue;
549     auto Ty = Type::getIntNTy(*C, TypeSize);
550     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
551                    {IRB.CreateIntCast(A1, Ty, true)});
552   }
553 }
554 
555 void SanitizerCoverageModule::InjectTraceForGep(
556     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
557   for (auto GEP : GepTraceTargets) {
558     IRBuilder<> IRB(GEP);
559     for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
560       if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
561         IRB.CreateCall(SanCovTraceGepFunction,
562                        {IRB.CreateIntCast(*I, IntptrTy, true)});
563   }
564 }
565 
566 void SanitizerCoverageModule::InjectTraceForCmp(
567     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
568   for (auto I : CmpTraceTargets) {
569     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
570       IRBuilder<> IRB(ICMP);
571       Value *A0 = ICMP->getOperand(0);
572       Value *A1 = ICMP->getOperand(1);
573       if (!A0->getType()->isIntegerTy())
574         continue;
575       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
576       int CallbackIdx = TypeSize == 8 ? 0 :
577                         TypeSize == 16 ? 1 :
578                         TypeSize == 32 ? 2 :
579                         TypeSize == 64 ? 3 : -1;
580       if (CallbackIdx < 0) continue;
581       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
582       auto Ty = Type::getIntNTy(*C, TypeSize);
583       IRB.CreateCall(
584           SanCovTraceCmpFunction[CallbackIdx],
585           {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
586     }
587   }
588 }
589 
590 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
591                                                     size_t Idx) {
592   BasicBlock::iterator IP = BB.getFirstInsertionPt();
593   bool IsEntryBB = &BB == &F.getEntryBlock();
594   DebugLoc EntryLoc;
595   if (IsEntryBB) {
596     if (auto SP = F.getSubprogram())
597       EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
598     // Keep static allocas and llvm.localescape calls in the entry block.  Even
599     // if we aren't splitting the block, it's nice for allocas to be before
600     // calls.
601     IP = PrepareToSplitEntryBlock(BB, IP);
602   } else {
603     EntryLoc = IP->getDebugLoc();
604   }
605 
606   IRBuilder<> IRB(&*IP);
607   IRB.SetCurrentDebugLocation(EntryLoc);
608   if (Options.TracePC) {
609     IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
610     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
611   }
612   if (Options.TracePCGuard) {
613     auto GuardPtr = IRB.CreateIntToPtr(
614         IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
615                       ConstantInt::get(IntptrTy, Idx * 4)),
616         Int32PtrTy);
617     IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
618     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
619   }
620   if (Options.Inline8bitCounters) {
621     auto CounterPtr = IRB.CreateGEP(
622         Function8bitCounterArray,
623         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
624     auto Load = IRB.CreateLoad(CounterPtr);
625     auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
626     auto Store = IRB.CreateStore(Inc, CounterPtr);
627     SetNoSanitizeMetadata(Load);
628     SetNoSanitizeMetadata(Store);
629   }
630 }
631 
632 std::string
633 SanitizerCoverageModule::getSectionName(const std::string &Section) const {
634   if (TargetTriple.getObjectFormat() == Triple::COFF)
635     return ".SCOV$M";
636   if (TargetTriple.isOSBinFormatMachO())
637     return "__DATA,__" + Section;
638   return "__" + Section;
639 }
640 
641 std::string
642 SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
643   if (TargetTriple.isOSBinFormatMachO())
644     return "\1section$start$__DATA$__" + Section;
645   return "__start___" + Section;
646 }
647 
648 std::string
649 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
650   if (TargetTriple.isOSBinFormatMachO())
651     return "\1section$end$__DATA$__" + Section;
652   return "__stop___" + Section;
653 }
654 
655 
656 char SanitizerCoverageModule::ID = 0;
657 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
658                       "SanitizerCoverage: TODO."
659                       "ModulePass",
660                       false, false)
661 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
662 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
663 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
664                     "SanitizerCoverage: TODO."
665                     "ModulePass",
666                     false, false)
667 ModulePass *llvm::createSanitizerCoverageModulePass(
668     const SanitizerCoverageOptions &Options) {
669   return new SanitizerCoverageModule(Options);
670 }
671