]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
Merge ^/head r319801 through r320041.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Transforms / Instrumentation / SanitizerCoverage.cpp
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
285   // We insert an empty inline asm after cov callbacks to avoid callback merge.
286   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
287                             StringRef(""), StringRef(""),
288                             /*hasSideEffects=*/true);
289
290   SanCovTracePC = checkSanitizerInterfaceFunction(
291       M.getOrInsertFunction(SanCovTracePCName, VoidTy));
292   SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
293       SanCovTracePCGuardName, VoidTy, Int32PtrTy));
294
295   for (auto &F : M)
296     runOnFunction(F);
297
298   if (FunctionGuardArray)
299     CreateInitCallForSection(M, SanCovTracePCGuardInitName, Int32PtrTy,
300                              SanCovGuardsSectionName);
301   if (Function8bitCounterArray)
302     CreateInitCallForSection(M, SanCov8bitCountersInitName, Int8PtrTy,
303                              SanCovCountersSectionName);
304
305   return true;
306 }
307
308 // True if block has successors and it dominates all of them.
309 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
310   if (succ_begin(BB) == succ_end(BB))
311     return false;
312
313   for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
314     if (!DT->dominates(BB, SUCC))
315       return false;
316   }
317
318   return true;
319 }
320
321 // True if block has predecessors and it postdominates all of them.
322 static bool isFullPostDominator(const BasicBlock *BB,
323                                 const PostDominatorTree *PDT) {
324   if (pred_begin(BB) == pred_end(BB))
325     return false;
326
327   for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
328     if (!PDT->dominates(BB, PRED))
329       return false;
330   }
331
332   return true;
333 }
334
335 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
336                                   const DominatorTree *DT,
337                                   const PostDominatorTree *PDT,
338                                   const SanitizerCoverageOptions &Options) {
339   // Don't insert coverage for unreachable blocks: we will never call
340   // __sanitizer_cov() for them, so counting them in
341   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
342   // percentage. Also, unreachable instructions frequently have no debug
343   // locations.
344   if (isa<UnreachableInst>(BB->getTerminator()))
345     return false;
346
347   // Don't insert coverage into blocks without a valid insertion point
348   // (catchswitch blocks).
349   if (BB->getFirstInsertionPt() == BB->end())
350     return false;
351
352   if (Options.NoPrune || &F.getEntryBlock() == BB)
353     return true;
354
355   // Do not instrument full dominators, or full post-dominators with multiple
356   // predecessors.
357   return !isFullDominator(BB, DT)
358     && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
359 }
360
361 bool SanitizerCoverageModule::runOnFunction(Function &F) {
362   if (F.empty())
363     return false;
364   if (F.getName().find(".module_ctor") != std::string::npos)
365     return false; // Should not instrument sanitizer init functions.
366   if (F.getName().startswith("__sanitizer_"))
367     return false;  // Don't instrument __sanitizer_* callbacks.
368   // Don't instrument MSVC CRT configuration helpers. They may run before normal
369   // initialization.
370   if (F.getName() == "__local_stdio_printf_options" ||
371       F.getName() == "__local_stdio_scanf_options")
372     return false;
373   // Don't instrument functions using SEH for now. Splitting basic blocks like
374   // we do for coverage breaks WinEHPrepare.
375   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
376   if (F.hasPersonalityFn() &&
377       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
378     return false;
379   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
380     SplitAllCriticalEdges(F);
381   SmallVector<Instruction *, 8> IndirCalls;
382   SmallVector<BasicBlock *, 16> BlocksToInstrument;
383   SmallVector<Instruction *, 8> CmpTraceTargets;
384   SmallVector<Instruction *, 8> SwitchTraceTargets;
385   SmallVector<BinaryOperator *, 8> DivTraceTargets;
386   SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
387
388   const DominatorTree *DT =
389       &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
390   const PostDominatorTree *PDT =
391       &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
392
393   for (auto &BB : F) {
394     if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
395       BlocksToInstrument.push_back(&BB);
396     for (auto &Inst : BB) {
397       if (Options.IndirectCalls) {
398         CallSite CS(&Inst);
399         if (CS && !CS.getCalledFunction())
400           IndirCalls.push_back(&Inst);
401       }
402       if (Options.TraceCmp) {
403         if (isa<ICmpInst>(&Inst))
404           CmpTraceTargets.push_back(&Inst);
405         if (isa<SwitchInst>(&Inst))
406           SwitchTraceTargets.push_back(&Inst);
407       }
408       if (Options.TraceDiv)
409         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
410           if (BO->getOpcode() == Instruction::SDiv ||
411               BO->getOpcode() == Instruction::UDiv)
412             DivTraceTargets.push_back(BO);
413       if (Options.TraceGep)
414         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
415           GepTraceTargets.push_back(GEP);
416    }
417   }
418
419   InjectCoverage(F, BlocksToInstrument);
420   InjectCoverageForIndirectCalls(F, IndirCalls);
421   InjectTraceForCmp(F, CmpTraceTargets);
422   InjectTraceForSwitch(F, SwitchTraceTargets);
423   InjectTraceForDiv(F, DivTraceTargets);
424   InjectTraceForGep(F, GepTraceTargets);
425   return true;
426 }
427
428 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
429     size_t NumElements, Function &F, Type *Ty, const char *Section) {
430   ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
431   auto Array = new GlobalVariable(
432       *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
433       Constant::getNullValue(ArrayTy), "__sancov_gen_");
434   if (auto Comdat = F.getComdat())
435     Array->setComdat(Comdat);
436   Array->setSection(getSectionName(Section));
437   return Array;
438 }
439 void SanitizerCoverageModule::CreateFunctionLocalArrays(size_t NumGuards,
440                                                        Function &F) {
441   if (Options.TracePCGuard)
442     FunctionGuardArray = CreateFunctionLocalArrayInSection(
443         NumGuards, F, Int32Ty, SanCovGuardsSectionName);
444   if (Options.Inline8bitCounters)
445     Function8bitCounterArray = CreateFunctionLocalArrayInSection(
446         NumGuards, F, Int8Ty, SanCovCountersSectionName);
447 }
448
449 bool SanitizerCoverageModule::InjectCoverage(Function &F,
450                                              ArrayRef<BasicBlock *> AllBlocks) {
451   if (AllBlocks.empty()) return false;
452   switch (Options.CoverageType) {
453   case SanitizerCoverageOptions::SCK_None:
454     return false;
455   case SanitizerCoverageOptions::SCK_Function:
456     CreateFunctionLocalArrays(1, F);
457     InjectCoverageAtBlock(F, F.getEntryBlock(), 0);
458     return true;
459   default: {
460     CreateFunctionLocalArrays(AllBlocks.size(), F);
461     for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
462       InjectCoverageAtBlock(F, *AllBlocks[i], i);
463     return true;
464   }
465   }
466 }
467
468 // On every indirect call we call a run-time function
469 // __sanitizer_cov_indir_call* with two parameters:
470 //   - callee address,
471 //   - global cache array that contains CacheSize pointers (zero-initialized).
472 //     The cache is used to speed up recording the caller-callee pairs.
473 // The address of the caller is passed implicitly via caller PC.
474 // CacheSize is encoded in the name of the run-time function.
475 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
476     Function &F, ArrayRef<Instruction *> IndirCalls) {
477   if (IndirCalls.empty())
478     return;
479   assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
480   for (auto I : IndirCalls) {
481     IRBuilder<> IRB(I);
482     CallSite CS(I);
483     Value *Callee = CS.getCalledValue();
484     if (isa<InlineAsm>(Callee))
485       continue;
486     IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
487   }
488 }
489
490 // For every switch statement we insert a call:
491 // __sanitizer_cov_trace_switch(CondValue,
492 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
493
494 void SanitizerCoverageModule::InjectTraceForSwitch(
495     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
496   for (auto I : SwitchTraceTargets) {
497     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
498       IRBuilder<> IRB(I);
499       SmallVector<Constant *, 16> Initializers;
500       Value *Cond = SI->getCondition();
501       if (Cond->getType()->getScalarSizeInBits() >
502           Int64Ty->getScalarSizeInBits())
503         continue;
504       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
505       Initializers.push_back(
506           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
507       if (Cond->getType()->getScalarSizeInBits() <
508           Int64Ty->getScalarSizeInBits())
509         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
510       for (auto It : SI->cases()) {
511         Constant *C = It.getCaseValue();
512         if (C->getType()->getScalarSizeInBits() <
513             Int64Ty->getScalarSizeInBits())
514           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
515         Initializers.push_back(C);
516       }
517       std::sort(Initializers.begin() + 2, Initializers.end(),
518                 [](const Constant *A, const Constant *B) {
519                   return cast<ConstantInt>(A)->getLimitedValue() <
520                          cast<ConstantInt>(B)->getLimitedValue();
521                 });
522       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
523       GlobalVariable *GV = new GlobalVariable(
524           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
525           ConstantArray::get(ArrayOfInt64Ty, Initializers),
526           "__sancov_gen_cov_switch_values");
527       IRB.CreateCall(SanCovTraceSwitchFunction,
528                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
529     }
530   }
531 }
532
533 void SanitizerCoverageModule::InjectTraceForDiv(
534     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
535   for (auto BO : DivTraceTargets) {
536     IRBuilder<> IRB(BO);
537     Value *A1 = BO->getOperand(1);
538     if (isa<ConstantInt>(A1)) continue;
539     if (!A1->getType()->isIntegerTy())
540       continue;
541     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
542     int CallbackIdx = TypeSize == 32 ? 0 :
543         TypeSize == 64 ? 1 : -1;
544     if (CallbackIdx < 0) continue;
545     auto Ty = Type::getIntNTy(*C, TypeSize);
546     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
547                    {IRB.CreateIntCast(A1, Ty, true)});
548   }
549 }
550
551 void SanitizerCoverageModule::InjectTraceForGep(
552     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
553   for (auto GEP : GepTraceTargets) {
554     IRBuilder<> IRB(GEP);
555     for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
556       if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
557         IRB.CreateCall(SanCovTraceGepFunction,
558                        {IRB.CreateIntCast(*I, IntptrTy, true)});
559   }
560 }
561
562 void SanitizerCoverageModule::InjectTraceForCmp(
563     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
564   for (auto I : CmpTraceTargets) {
565     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
566       IRBuilder<> IRB(ICMP);
567       Value *A0 = ICMP->getOperand(0);
568       Value *A1 = ICMP->getOperand(1);
569       if (!A0->getType()->isIntegerTy())
570         continue;
571       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
572       int CallbackIdx = TypeSize == 8 ? 0 :
573                         TypeSize == 16 ? 1 :
574                         TypeSize == 32 ? 2 :
575                         TypeSize == 64 ? 3 : -1;
576       if (CallbackIdx < 0) continue;
577       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
578       auto Ty = Type::getIntNTy(*C, TypeSize);
579       IRB.CreateCall(
580           SanCovTraceCmpFunction[CallbackIdx],
581           {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
582     }
583   }
584 }
585
586 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
587                                                     size_t Idx) {
588   BasicBlock::iterator IP = BB.getFirstInsertionPt();
589   bool IsEntryBB = &BB == &F.getEntryBlock();
590   DebugLoc EntryLoc;
591   if (IsEntryBB) {
592     if (auto SP = F.getSubprogram())
593       EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
594     // Keep static allocas and llvm.localescape calls in the entry block.  Even
595     // if we aren't splitting the block, it's nice for allocas to be before
596     // calls.
597     IP = PrepareToSplitEntryBlock(BB, IP);
598   } else {
599     EntryLoc = IP->getDebugLoc();
600   }
601
602   IRBuilder<> IRB(&*IP);
603   IRB.SetCurrentDebugLocation(EntryLoc);
604   if (Options.TracePC) {
605     IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
606     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
607   }
608   if (Options.TracePCGuard) {
609     auto GuardPtr = IRB.CreateIntToPtr(
610         IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
611                       ConstantInt::get(IntptrTy, Idx * 4)),
612         Int32PtrTy);
613     IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
614     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
615   }
616   if (Options.Inline8bitCounters) {
617     auto CounterPtr = IRB.CreateGEP(
618         Function8bitCounterArray,
619         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
620     auto Load = IRB.CreateLoad(CounterPtr);
621     auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
622     auto Store = IRB.CreateStore(Inc, CounterPtr);
623     SetNoSanitizeMetadata(Load);
624     SetNoSanitizeMetadata(Store);
625   }
626 }
627
628 std::string
629 SanitizerCoverageModule::getSectionName(const std::string &Section) const {
630   if (TargetTriple.getObjectFormat() == Triple::COFF)
631     return ".SCOV$M";
632   if (TargetTriple.isOSBinFormatMachO())
633     return "__DATA,__" + Section;
634   return "__" + Section;
635 }
636
637 std::string
638 SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
639   if (TargetTriple.isOSBinFormatMachO())
640     return "\1section$start$__DATA$__" + Section;
641   return "__start___" + Section;
642 }
643
644 std::string
645 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
646   if (TargetTriple.isOSBinFormatMachO())
647     return "\1section$end$__DATA$__" + Section;
648   return "__stop___" + Section;
649 }
650
651
652 char SanitizerCoverageModule::ID = 0;
653 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
654                       "SanitizerCoverage: TODO."
655                       "ModulePass",
656                       false, false)
657 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
658 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
659 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
660                     "SanitizerCoverage: TODO."
661                     "ModulePass",
662                     false, false)
663 ModulePass *llvm::createSanitizerCoverageModulePass(
664     const SanitizerCoverageOptions &Options) {
665   return new SanitizerCoverageModule(Options);
666 }