xref: /llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp (revision f1a54a47b08df197b037aef97d04d87b5997f221)
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/Constant.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DebugInfo.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/MDBuilder.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Transforms/Instrumentation.h"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "llvm/Transforms/Utils/ModuleUtils.h"
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "sancov"
44 
45 static const char *const SanCovTracePCIndirName =
46     "__sanitizer_cov_trace_pc_indir";
47 static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
48 static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
49 static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
50 static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
51 static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
52 static const char *const SanCovTraceConstCmp1 =
53     "__sanitizer_cov_trace_const_cmp1";
54 static const char *const SanCovTraceConstCmp2 =
55     "__sanitizer_cov_trace_const_cmp2";
56 static const char *const SanCovTraceConstCmp4 =
57     "__sanitizer_cov_trace_const_cmp4";
58 static const char *const SanCovTraceConstCmp8 =
59     "__sanitizer_cov_trace_const_cmp8";
60 static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
61 static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
62 static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
63 static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
64 static const char *const SanCovModuleCtorName = "sancov.module_ctor";
65 static const uint64_t SanCtorAndDtorPriority = 2;
66 
67 static const char *const SanCovTracePCGuardName =
68     "__sanitizer_cov_trace_pc_guard";
69 static const char *const SanCovTracePCGuardInitName =
70     "__sanitizer_cov_trace_pc_guard_init";
71 static const char *const SanCov8bitCountersInitName =
72     "__sanitizer_cov_8bit_counters_init";
73 static const char *const SanCovPCsInitName = "__sanitizer_cov_pcs_init";
74 
75 static const char *const SanCovGuardsSectionName = "sancov_guards";
76 static const char *const SanCovCountersSectionName = "sancov_cntrs";
77 static const char *const SanCovPCsSectionName = "sancov_pcs";
78 
79 static const char *const SanCovLowestStackName = "__sancov_lowest_stack";
80 
81 static cl::opt<int> ClCoverageLevel(
82     "sanitizer-coverage-level",
83     cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
84              "3: all blocks and critical edges"),
85     cl::Hidden, cl::init(0));
86 
87 static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
88                                cl::desc("Experimental pc tracing"), cl::Hidden,
89                                cl::init(false));
90 
91 static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
92                                     cl::desc("pc tracing with a guard"),
93                                     cl::Hidden, cl::init(false));
94 
95 // If true, we create a global variable that contains PCs of all instrumented
96 // BBs, put this global into a named section, and pass this section's bounds
97 // to __sanitizer_cov_pcs_init.
98 // This way the coverage instrumentation does not need to acquire the PCs
99 // at run-time. Works with trace-pc-guard and inline-8bit-counters.
100 static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
101                                      cl::desc("create a static PC table"),
102                                      cl::Hidden, cl::init(false));
103 
104 static cl::opt<bool>
105     ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
106                          cl::desc("increments 8-bit counter for every edge"),
107                          cl::Hidden, cl::init(false));
108 
109 static cl::opt<bool>
110     ClCMPTracing("sanitizer-coverage-trace-compares",
111                  cl::desc("Tracing of CMP and similar instructions"),
112                  cl::Hidden, cl::init(false));
113 
114 static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
115                                   cl::desc("Tracing of DIV instructions"),
116                                   cl::Hidden, cl::init(false));
117 
118 static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
119                                   cl::desc("Tracing of GEP instructions"),
120                                   cl::Hidden, cl::init(false));
121 
122 static cl::opt<bool>
123     ClPruneBlocks("sanitizer-coverage-prune-blocks",
124                   cl::desc("Reduce the number of instrumented blocks"),
125                   cl::Hidden, cl::init(true));
126 
127 static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
128                                   cl::desc("max stack depth tracing"),
129                                   cl::Hidden, cl::init(false));
130 
131 namespace {
132 
133 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
134   SanitizerCoverageOptions Res;
135   switch (LegacyCoverageLevel) {
136   case 0:
137     Res.CoverageType = SanitizerCoverageOptions::SCK_None;
138     break;
139   case 1:
140     Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
141     break;
142   case 2:
143     Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
144     break;
145   case 3:
146     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
147     break;
148   case 4:
149     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
150     Res.IndirectCalls = true;
151     break;
152   }
153   return Res;
154 }
155 
156 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
157   // Sets CoverageType and IndirectCalls.
158   SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
159   Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
160   Options.IndirectCalls |= CLOpts.IndirectCalls;
161   Options.TraceCmp |= ClCMPTracing;
162   Options.TraceDiv |= ClDIVTracing;
163   Options.TraceGep |= ClGEPTracing;
164   Options.TracePC |= ClTracePC;
165   Options.TracePCGuard |= ClTracePCGuard;
166   Options.Inline8bitCounters |= ClInline8bitCounters;
167   Options.PCTable |= ClCreatePCTable;
168   Options.NoPrune |= !ClPruneBlocks;
169   Options.StackDepth |= ClStackDepth;
170   if (!Options.TracePCGuard && !Options.TracePC &&
171       !Options.Inline8bitCounters && !Options.StackDepth)
172     Options.TracePCGuard = true; // TracePCGuard is default.
173   return Options;
174 }
175 
176 class SanitizerCoverageModule : public ModulePass {
177 public:
178   SanitizerCoverageModule(
179       const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
180       : ModulePass(ID), Options(OverrideFromCL(Options)) {
181     initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
182   }
183   bool runOnModule(Module &M) override;
184   bool runOnFunction(Function &F);
185   static char ID; // Pass identification, replacement for typeid
186   StringRef getPassName() const override { return "SanitizerCoverageModule"; }
187 
188   void getAnalysisUsage(AnalysisUsage &AU) const override {
189     AU.addRequired<DominatorTreeWrapperPass>();
190     AU.addRequired<PostDominatorTreeWrapperPass>();
191   }
192 
193 private:
194   void InjectCoverageForIndirectCalls(Function &F,
195                                       ArrayRef<Instruction *> IndirCalls);
196   void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
197   void InjectTraceForDiv(Function &F,
198                          ArrayRef<BinaryOperator *> DivTraceTargets);
199   void InjectTraceForGep(Function &F,
200                          ArrayRef<GetElementPtrInst *> GepTraceTargets);
201   void InjectTraceForSwitch(Function &F,
202                             ArrayRef<Instruction *> SwitchTraceTargets);
203   bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
204   GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
205                                                     Function &F, Type *Ty,
206                                                     const char *Section);
207   GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
208   void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
209   void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx);
210   Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName,
211                                        Type *Ty, const char *Section);
212   std::pair<GlobalVariable *, GlobalVariable *>
213   CreateSecStartEnd(Module &M, const char *Section, Type *Ty);
214 
215   void SetNoSanitizeMetadata(Instruction *I) {
216     I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
217                    MDNode::get(*C, None));
218   }
219 
220   std::string getSectionName(const std::string &Section) const;
221   std::string getSectionStart(const std::string &Section) const;
222   std::string getSectionEnd(const std::string &Section) const;
223   Function *SanCovTracePCIndir;
224   Function *SanCovTracePC, *SanCovTracePCGuard;
225   Function *SanCovTraceCmpFunction[4];
226   Function *SanCovTraceConstCmpFunction[4];
227   Function *SanCovTraceDivFunction[2];
228   Function *SanCovTraceGepFunction;
229   Function *SanCovTraceSwitchFunction;
230   GlobalVariable *SanCovLowestStack;
231   InlineAsm *EmptyAsm;
232   Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
233       *Int16Ty, *Int8Ty, *Int8PtrTy;
234   Module *CurModule;
235   Triple TargetTriple;
236   LLVMContext *C;
237   const DataLayout *DL;
238 
239   GlobalVariable *FunctionGuardArray;  // for trace-pc-guard.
240   GlobalVariable *Function8bitCounterArray;  // for inline-8bit-counters.
241   GlobalVariable *FunctionPCsArray;  // for pc-table.
242 
243   SanitizerCoverageOptions Options;
244 };
245 
246 } // namespace
247 
248 std::pair<GlobalVariable *, GlobalVariable *>
249 SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section,
250                                            Type *Ty) {
251   GlobalVariable *SecStart =
252       new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
253                          getSectionStart(Section));
254   SecStart->setVisibility(GlobalValue::HiddenVisibility);
255   GlobalVariable *SecEnd =
256       new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
257                          nullptr, getSectionEnd(Section));
258   SecEnd->setVisibility(GlobalValue::HiddenVisibility);
259 
260   return std::make_pair(SecStart, SecEnd);
261 }
262 
263 
264 Function *SanitizerCoverageModule::CreateInitCallsForSections(
265     Module &M, const char *InitFunctionName, Type *Ty,
266     const char *Section) {
267   IRBuilder<> IRB(M.getContext());
268   auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
269   auto SecStart = SecStartEnd.first;
270   auto SecEnd = SecStartEnd.second;
271   Function *CtorFunc;
272   std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
273       M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
274       {IRB.CreatePointerCast(SecStart, Ty), IRB.CreatePointerCast(SecEnd, Ty)});
275 
276   if (TargetTriple.supportsCOMDAT()) {
277     // Use comdat to dedup CtorFunc.
278     CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
279     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
280   } else {
281     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
282   }
283   return CtorFunc;
284 }
285 
286 bool SanitizerCoverageModule::runOnModule(Module &M) {
287   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
288     return false;
289   C = &(M.getContext());
290   DL = &M.getDataLayout();
291   CurModule = &M;
292   TargetTriple = Triple(M.getTargetTriple());
293   FunctionGuardArray = nullptr;
294   Function8bitCounterArray = nullptr;
295   FunctionPCsArray = nullptr;
296   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
297   IntptrPtrTy = PointerType::getUnqual(IntptrTy);
298   Type *VoidTy = Type::getVoidTy(*C);
299   IRBuilder<> IRB(*C);
300   Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
301   Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
302   Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
303   Int64Ty = IRB.getInt64Ty();
304   Int32Ty = IRB.getInt32Ty();
305   Int16Ty = IRB.getInt16Ty();
306   Int8Ty = IRB.getInt8Ty();
307 
308   SanCovTracePCIndir = checkSanitizerInterfaceFunction(
309       M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
310   SanCovTraceCmpFunction[0] =
311       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
312           SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
313   SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
314       M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
315                             IRB.getInt16Ty()));
316   SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
317       M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
318                             IRB.getInt32Ty()));
319   SanCovTraceCmpFunction[3] =
320       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
321           SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
322 
323   SanCovTraceConstCmpFunction[0] =
324       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
325           SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty));
326   SanCovTraceConstCmpFunction[1] =
327       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
328           SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty));
329   SanCovTraceConstCmpFunction[2] =
330       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
331           SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty));
332   SanCovTraceConstCmpFunction[3] =
333       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
334           SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty));
335 
336   SanCovTraceDivFunction[0] =
337       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
338           SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
339   SanCovTraceDivFunction[1] =
340       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
341           SanCovTraceDiv8, VoidTy, Int64Ty));
342   SanCovTraceGepFunction =
343       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
344           SanCovTraceGep, VoidTy, IntptrTy));
345   SanCovTraceSwitchFunction =
346       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
347           SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
348 
349   Constant *SanCovLowestStackConstant =
350       M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
351   SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant);
352   SanCovLowestStack->setThreadLocalMode(
353       GlobalValue::ThreadLocalMode::InitialExecTLSModel);
354   if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
355     SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
356 
357   // Make sure smaller parameters are zero-extended to i64 as required by the
358   // x86_64 ABI.
359   if (TargetTriple.getArch() == Triple::x86_64) {
360     for (int i = 0; i < 3; i++) {
361       SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
362       SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
363       SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
364       SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
365     }
366     SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
367   }
368 
369 
370   // We insert an empty inline asm after cov callbacks to avoid callback merge.
371   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
372                             StringRef(""), StringRef(""),
373                             /*hasSideEffects=*/true);
374 
375   SanCovTracePC = checkSanitizerInterfaceFunction(
376       M.getOrInsertFunction(SanCovTracePCName, VoidTy));
377   SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
378       SanCovTracePCGuardName, VoidTy, Int32PtrTy));
379 
380   for (auto &F : M)
381     runOnFunction(F);
382 
383   Function *Ctor = nullptr;
384 
385   if (FunctionGuardArray)
386     Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
387                                       SanCovGuardsSectionName);
388   if (Function8bitCounterArray)
389     Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
390                                       SanCovCountersSectionName);
391   if (Ctor && Options.PCTable) {
392     auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
393     Function *InitFunction = declareSanitizerInitFunction(
394         M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
395     IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
396     IRBCtor.CreateCall(InitFunction,
397                        {IRB.CreatePointerCast(SecStartEnd.first, IntptrPtrTy),
398                         IRB.CreatePointerCast(SecStartEnd.second, IntptrPtrTy)});
399   }
400   return true;
401 }
402 
403 // True if block has successors and it dominates all of them.
404 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
405   if (succ_begin(BB) == succ_end(BB))
406     return false;
407 
408   for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
409     if (!DT->dominates(BB, SUCC))
410       return false;
411   }
412 
413   return true;
414 }
415 
416 // True if block has predecessors and it postdominates all of them.
417 static bool isFullPostDominator(const BasicBlock *BB,
418                                 const PostDominatorTree *PDT) {
419   if (pred_begin(BB) == pred_end(BB))
420     return false;
421 
422   for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
423     if (!PDT->dominates(BB, PRED))
424       return false;
425   }
426 
427   return true;
428 }
429 
430 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
431                                   const DominatorTree *DT,
432                                   const PostDominatorTree *PDT,
433                                   const SanitizerCoverageOptions &Options) {
434   // Don't insert coverage for unreachable blocks: we will never call
435   // __sanitizer_cov() for them, so counting them in
436   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
437   // percentage. Also, unreachable instructions frequently have no debug
438   // locations.
439   if (isa<UnreachableInst>(BB->getTerminator()))
440     return false;
441 
442   // Don't insert coverage into blocks without a valid insertion point
443   // (catchswitch blocks).
444   if (BB->getFirstInsertionPt() == BB->end())
445     return false;
446 
447   if (Options.NoPrune || &F.getEntryBlock() == BB)
448     return true;
449 
450   if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
451       &F.getEntryBlock() != BB)
452     return false;
453 
454   // Do not instrument full dominators, or full post-dominators with multiple
455   // predecessors.
456   return !isFullDominator(BB, DT)
457     && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
458 }
459 
460 bool SanitizerCoverageModule::runOnFunction(Function &F) {
461   if (F.empty())
462     return false;
463   if (F.getName().find(".module_ctor") != std::string::npos)
464     return false; // Should not instrument sanitizer init functions.
465   if (F.getName().startswith("__sanitizer_"))
466     return false;  // Don't instrument __sanitizer_* callbacks.
467   // Don't touch available_externally functions, their actual body is elewhere.
468   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
469     return false;
470   // Don't instrument MSVC CRT configuration helpers. They may run before normal
471   // initialization.
472   if (F.getName() == "__local_stdio_printf_options" ||
473       F.getName() == "__local_stdio_scanf_options")
474     return false;
475   // Don't instrument functions using SEH for now. Splitting basic blocks like
476   // we do for coverage breaks WinEHPrepare.
477   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
478   if (F.hasPersonalityFn() &&
479       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
480     return false;
481   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
482     SplitAllCriticalEdges(F);
483   SmallVector<Instruction *, 8> IndirCalls;
484   SmallVector<BasicBlock *, 16> BlocksToInstrument;
485   SmallVector<Instruction *, 8> CmpTraceTargets;
486   SmallVector<Instruction *, 8> SwitchTraceTargets;
487   SmallVector<BinaryOperator *, 8> DivTraceTargets;
488   SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
489 
490   const DominatorTree *DT =
491       &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
492   const PostDominatorTree *PDT =
493       &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
494 
495   for (auto &BB : F) {
496     if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
497       BlocksToInstrument.push_back(&BB);
498     for (auto &Inst : BB) {
499       if (Options.IndirectCalls) {
500         CallSite CS(&Inst);
501         if (CS && !CS.getCalledFunction())
502           IndirCalls.push_back(&Inst);
503       }
504       if (Options.TraceCmp) {
505         if (isa<ICmpInst>(&Inst))
506           CmpTraceTargets.push_back(&Inst);
507         if (isa<SwitchInst>(&Inst))
508           SwitchTraceTargets.push_back(&Inst);
509       }
510       if (Options.TraceDiv)
511         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
512           if (BO->getOpcode() == Instruction::SDiv ||
513               BO->getOpcode() == Instruction::UDiv)
514             DivTraceTargets.push_back(BO);
515       if (Options.TraceGep)
516         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
517           GepTraceTargets.push_back(GEP);
518    }
519   }
520 
521   InjectCoverage(F, BlocksToInstrument);
522   InjectCoverageForIndirectCalls(F, IndirCalls);
523   InjectTraceForCmp(F, CmpTraceTargets);
524   InjectTraceForSwitch(F, SwitchTraceTargets);
525   InjectTraceForDiv(F, DivTraceTargets);
526   InjectTraceForGep(F, GepTraceTargets);
527   return true;
528 }
529 
530 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
531     size_t NumElements, Function &F, Type *Ty, const char *Section) {
532   ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
533   auto Array = new GlobalVariable(
534       *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
535       Constant::getNullValue(ArrayTy), "__sancov_gen_");
536   if (auto Comdat = F.getComdat())
537     Array->setComdat(Comdat);
538   Array->setSection(getSectionName(Section));
539   Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
540                                         : Ty->getPrimitiveSizeInBits() / 8);
541   return Array;
542 }
543 
544 GlobalVariable *
545 SanitizerCoverageModule::CreatePCArray(Function &F,
546                                        ArrayRef<BasicBlock *> AllBlocks) {
547   size_t N = AllBlocks.size();
548   assert(N);
549   SmallVector<Constant *, 32> PCs;
550   IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
551   for (size_t i = 0; i < N; i++) {
552     if (&F.getEntryBlock() == AllBlocks[i]) {
553       PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
554       PCs.push_back((Constant *)IRB.CreateIntToPtr(
555           ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
556     } else {
557       PCs.push_back((Constant *)IRB.CreatePointerCast(
558           BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
559       PCs.push_back((Constant *)IRB.CreateIntToPtr(
560           ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
561     }
562   }
563   auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
564                                                     SanCovPCsSectionName);
565   PCArray->setInitializer(
566       ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
567   PCArray->setConstant(true);
568 
569   return PCArray;
570 }
571 
572 void SanitizerCoverageModule::CreateFunctionLocalArrays(
573     Function &F, ArrayRef<BasicBlock *> AllBlocks) {
574   SmallVector<GlobalValue *, 3> LocalArrays;
575   if (Options.TracePCGuard) {
576     FunctionGuardArray = CreateFunctionLocalArrayInSection(
577         AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
578     LocalArrays.push_back(FunctionGuardArray);
579   }
580   if (Options.Inline8bitCounters) {
581     Function8bitCounterArray = CreateFunctionLocalArrayInSection(
582         AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
583     LocalArrays.push_back(Function8bitCounterArray);
584   }
585   if (Options.PCTable) {
586     FunctionPCsArray = CreatePCArray(F, AllBlocks);
587     LocalArrays.push_back(FunctionPCsArray);
588   }
589 
590   // We don't reference these arrays directly in any of our runtime functions,
591   // so we need to prevent them from being dead stripped.
592   appendToUsed(*F.getParent(), LocalArrays);
593 }
594 
595 bool SanitizerCoverageModule::InjectCoverage(Function &F,
596                                              ArrayRef<BasicBlock *> AllBlocks) {
597   if (AllBlocks.empty()) return false;
598   CreateFunctionLocalArrays(F, AllBlocks);
599   for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
600     InjectCoverageAtBlock(F, *AllBlocks[i], i);
601   return true;
602 }
603 
604 // On every indirect call we call a run-time function
605 // __sanitizer_cov_indir_call* with two parameters:
606 //   - callee address,
607 //   - global cache array that contains CacheSize pointers (zero-initialized).
608 //     The cache is used to speed up recording the caller-callee pairs.
609 // The address of the caller is passed implicitly via caller PC.
610 // CacheSize is encoded in the name of the run-time function.
611 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
612     Function &F, ArrayRef<Instruction *> IndirCalls) {
613   if (IndirCalls.empty())
614     return;
615   assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
616   for (auto I : IndirCalls) {
617     IRBuilder<> IRB(I);
618     CallSite CS(I);
619     Value *Callee = CS.getCalledValue();
620     if (isa<InlineAsm>(Callee))
621       continue;
622     IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
623   }
624 }
625 
626 // For every switch statement we insert a call:
627 // __sanitizer_cov_trace_switch(CondValue,
628 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
629 
630 void SanitizerCoverageModule::InjectTraceForSwitch(
631     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
632   for (auto I : SwitchTraceTargets) {
633     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
634       IRBuilder<> IRB(I);
635       SmallVector<Constant *, 16> Initializers;
636       Value *Cond = SI->getCondition();
637       if (Cond->getType()->getScalarSizeInBits() >
638           Int64Ty->getScalarSizeInBits())
639         continue;
640       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
641       Initializers.push_back(
642           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
643       if (Cond->getType()->getScalarSizeInBits() <
644           Int64Ty->getScalarSizeInBits())
645         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
646       for (auto It : SI->cases()) {
647         Constant *C = It.getCaseValue();
648         if (C->getType()->getScalarSizeInBits() <
649             Int64Ty->getScalarSizeInBits())
650           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
651         Initializers.push_back(C);
652       }
653       std::sort(Initializers.begin() + 2, Initializers.end(),
654                 [](const Constant *A, const Constant *B) {
655                   return cast<ConstantInt>(A)->getLimitedValue() <
656                          cast<ConstantInt>(B)->getLimitedValue();
657                 });
658       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
659       GlobalVariable *GV = new GlobalVariable(
660           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
661           ConstantArray::get(ArrayOfInt64Ty, Initializers),
662           "__sancov_gen_cov_switch_values");
663       IRB.CreateCall(SanCovTraceSwitchFunction,
664                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
665     }
666   }
667 }
668 
669 void SanitizerCoverageModule::InjectTraceForDiv(
670     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
671   for (auto BO : DivTraceTargets) {
672     IRBuilder<> IRB(BO);
673     Value *A1 = BO->getOperand(1);
674     if (isa<ConstantInt>(A1)) continue;
675     if (!A1->getType()->isIntegerTy())
676       continue;
677     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
678     int CallbackIdx = TypeSize == 32 ? 0 :
679         TypeSize == 64 ? 1 : -1;
680     if (CallbackIdx < 0) continue;
681     auto Ty = Type::getIntNTy(*C, TypeSize);
682     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
683                    {IRB.CreateIntCast(A1, Ty, true)});
684   }
685 }
686 
687 void SanitizerCoverageModule::InjectTraceForGep(
688     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
689   for (auto GEP : GepTraceTargets) {
690     IRBuilder<> IRB(GEP);
691     for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
692       if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
693         IRB.CreateCall(SanCovTraceGepFunction,
694                        {IRB.CreateIntCast(*I, IntptrTy, true)});
695   }
696 }
697 
698 void SanitizerCoverageModule::InjectTraceForCmp(
699     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
700   for (auto I : CmpTraceTargets) {
701     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
702       IRBuilder<> IRB(ICMP);
703       Value *A0 = ICMP->getOperand(0);
704       Value *A1 = ICMP->getOperand(1);
705       if (!A0->getType()->isIntegerTy())
706         continue;
707       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
708       int CallbackIdx = TypeSize == 8 ? 0 :
709                         TypeSize == 16 ? 1 :
710                         TypeSize == 32 ? 2 :
711                         TypeSize == 64 ? 3 : -1;
712       if (CallbackIdx < 0) continue;
713       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
714       auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
715       bool FirstIsConst = isa<ConstantInt>(A0);
716       bool SecondIsConst = isa<ConstantInt>(A1);
717       // If both are const, then we don't need such a comparison.
718       if (FirstIsConst && SecondIsConst) continue;
719       // If only one is const, then make it the first callback argument.
720       if (FirstIsConst || SecondIsConst) {
721         CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
722         if (SecondIsConst)
723           std::swap(A0, A1);
724       }
725 
726       auto Ty = Type::getIntNTy(*C, TypeSize);
727       IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
728               IRB.CreateIntCast(A1, Ty, true)});
729     }
730   }
731 }
732 
733 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
734                                                     size_t Idx) {
735   BasicBlock::iterator IP = BB.getFirstInsertionPt();
736   bool IsEntryBB = &BB == &F.getEntryBlock();
737   DebugLoc EntryLoc;
738   if (IsEntryBB) {
739     if (auto SP = F.getSubprogram())
740       EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
741     // Keep static allocas and llvm.localescape calls in the entry block.  Even
742     // if we aren't splitting the block, it's nice for allocas to be before
743     // calls.
744     IP = PrepareToSplitEntryBlock(BB, IP);
745   } else {
746     EntryLoc = IP->getDebugLoc();
747   }
748 
749   IRBuilder<> IRB(&*IP);
750   IRB.SetCurrentDebugLocation(EntryLoc);
751   if (Options.TracePC) {
752     IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
753     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
754   }
755   if (Options.TracePCGuard) {
756     auto GuardPtr = IRB.CreateIntToPtr(
757         IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
758                       ConstantInt::get(IntptrTy, Idx * 4)),
759         Int32PtrTy);
760     IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
761     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
762   }
763   if (Options.Inline8bitCounters) {
764     auto CounterPtr = IRB.CreateGEP(
765         Function8bitCounterArray,
766         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
767     auto Load = IRB.CreateLoad(CounterPtr);
768     auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
769     auto Store = IRB.CreateStore(Inc, CounterPtr);
770     SetNoSanitizeMetadata(Load);
771     SetNoSanitizeMetadata(Store);
772   }
773   if (Options.StackDepth && IsEntryBB) {
774     // Check stack depth.  If it's the deepest so far, record it.
775     Function *GetFrameAddr =
776         Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
777     auto FrameAddrPtr =
778         IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
779     auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
780     auto LowestStack = IRB.CreateLoad(SanCovLowestStack);
781     auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
782     auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
783     IRBuilder<> ThenIRB(ThenTerm);
784     ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
785   }
786 }
787 
788 std::string
789 SanitizerCoverageModule::getSectionName(const std::string &Section) const {
790   if (TargetTriple.getObjectFormat() == Triple::COFF)
791     return ".SCOV$M";
792   if (TargetTriple.isOSBinFormatMachO())
793     return "__DATA,__" + Section;
794   return "__" + Section;
795 }
796 
797 std::string
798 SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
799   if (TargetTriple.isOSBinFormatMachO())
800     return "\1section$start$__DATA$__" + Section;
801   return "__start___" + Section;
802 }
803 
804 std::string
805 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
806   if (TargetTriple.isOSBinFormatMachO())
807     return "\1section$end$__DATA$__" + Section;
808   return "__stop___" + Section;
809 }
810 
811 
812 char SanitizerCoverageModule::ID = 0;
813 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
814                       "SanitizerCoverage: TODO."
815                       "ModulePass",
816                       false, false)
817 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
818 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
819 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
820                     "SanitizerCoverage: TODO."
821                     "ModulePass",
822                     false, false)
823 ModulePass *llvm::createSanitizerCoverageModulePass(
824     const SanitizerCoverageOptions &Options) {
825   return new SanitizerCoverageModule(Options);
826 }
827