xref: /llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp (revision 6ec7595b1e2ab79a1b456fe3338cce9619a08083)
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   void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
208   void CreatePCArray(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 void SanitizerCoverageModule::CreatePCArray(Function &F,
545                                             ArrayRef<BasicBlock *> AllBlocks) {
546   size_t N = AllBlocks.size();
547   assert(N);
548   SmallVector<Constant *, 32> PCs;
549   IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
550   for (size_t i = 0; i < N; i++) {
551     if (&F.getEntryBlock() == AllBlocks[i]) {
552       PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
553       PCs.push_back((Constant *)IRB.CreateIntToPtr(
554           ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
555     } else {
556       PCs.push_back((Constant *)IRB.CreatePointerCast(
557           BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
558       PCs.push_back((Constant *)IRB.CreateIntToPtr(
559           ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
560     }
561   }
562   FunctionPCsArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
563                                                        SanCovPCsSectionName);
564   FunctionPCsArray->setInitializer(
565       ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
566   FunctionPCsArray->setConstant(true);
567 
568   // We don't reference the PCs array in any of our runtime functions, so we
569   // need to prevent it from being dead stripped.
570   appendToUsed(*F.getParent(), {FunctionPCsArray});
571 }
572 
573 void SanitizerCoverageModule::CreateFunctionLocalArrays(
574     Function &F, ArrayRef<BasicBlock *> AllBlocks) {
575   if (Options.TracePCGuard)
576     FunctionGuardArray = CreateFunctionLocalArrayInSection(
577         AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
578   if (Options.Inline8bitCounters)
579     Function8bitCounterArray = CreateFunctionLocalArrayInSection(
580         AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
581   if (Options.PCTable)
582     CreatePCArray(F, AllBlocks);
583 }
584 
585 bool SanitizerCoverageModule::InjectCoverage(Function &F,
586                                              ArrayRef<BasicBlock *> AllBlocks) {
587   if (AllBlocks.empty()) return false;
588   CreateFunctionLocalArrays(F, AllBlocks);
589   for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
590     InjectCoverageAtBlock(F, *AllBlocks[i], i);
591   return true;
592 }
593 
594 // On every indirect call we call a run-time function
595 // __sanitizer_cov_indir_call* with two parameters:
596 //   - callee address,
597 //   - global cache array that contains CacheSize pointers (zero-initialized).
598 //     The cache is used to speed up recording the caller-callee pairs.
599 // The address of the caller is passed implicitly via caller PC.
600 // CacheSize is encoded in the name of the run-time function.
601 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
602     Function &F, ArrayRef<Instruction *> IndirCalls) {
603   if (IndirCalls.empty())
604     return;
605   assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
606   for (auto I : IndirCalls) {
607     IRBuilder<> IRB(I);
608     CallSite CS(I);
609     Value *Callee = CS.getCalledValue();
610     if (isa<InlineAsm>(Callee))
611       continue;
612     IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
613   }
614 }
615 
616 // For every switch statement we insert a call:
617 // __sanitizer_cov_trace_switch(CondValue,
618 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
619 
620 void SanitizerCoverageModule::InjectTraceForSwitch(
621     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
622   for (auto I : SwitchTraceTargets) {
623     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
624       IRBuilder<> IRB(I);
625       SmallVector<Constant *, 16> Initializers;
626       Value *Cond = SI->getCondition();
627       if (Cond->getType()->getScalarSizeInBits() >
628           Int64Ty->getScalarSizeInBits())
629         continue;
630       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
631       Initializers.push_back(
632           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
633       if (Cond->getType()->getScalarSizeInBits() <
634           Int64Ty->getScalarSizeInBits())
635         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
636       for (auto It : SI->cases()) {
637         Constant *C = It.getCaseValue();
638         if (C->getType()->getScalarSizeInBits() <
639             Int64Ty->getScalarSizeInBits())
640           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
641         Initializers.push_back(C);
642       }
643       std::sort(Initializers.begin() + 2, Initializers.end(),
644                 [](const Constant *A, const Constant *B) {
645                   return cast<ConstantInt>(A)->getLimitedValue() <
646                          cast<ConstantInt>(B)->getLimitedValue();
647                 });
648       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
649       GlobalVariable *GV = new GlobalVariable(
650           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
651           ConstantArray::get(ArrayOfInt64Ty, Initializers),
652           "__sancov_gen_cov_switch_values");
653       IRB.CreateCall(SanCovTraceSwitchFunction,
654                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
655     }
656   }
657 }
658 
659 void SanitizerCoverageModule::InjectTraceForDiv(
660     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
661   for (auto BO : DivTraceTargets) {
662     IRBuilder<> IRB(BO);
663     Value *A1 = BO->getOperand(1);
664     if (isa<ConstantInt>(A1)) continue;
665     if (!A1->getType()->isIntegerTy())
666       continue;
667     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
668     int CallbackIdx = TypeSize == 32 ? 0 :
669         TypeSize == 64 ? 1 : -1;
670     if (CallbackIdx < 0) continue;
671     auto Ty = Type::getIntNTy(*C, TypeSize);
672     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
673                    {IRB.CreateIntCast(A1, Ty, true)});
674   }
675 }
676 
677 void SanitizerCoverageModule::InjectTraceForGep(
678     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
679   for (auto GEP : GepTraceTargets) {
680     IRBuilder<> IRB(GEP);
681     for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
682       if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
683         IRB.CreateCall(SanCovTraceGepFunction,
684                        {IRB.CreateIntCast(*I, IntptrTy, true)});
685   }
686 }
687 
688 void SanitizerCoverageModule::InjectTraceForCmp(
689     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
690   for (auto I : CmpTraceTargets) {
691     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
692       IRBuilder<> IRB(ICMP);
693       Value *A0 = ICMP->getOperand(0);
694       Value *A1 = ICMP->getOperand(1);
695       if (!A0->getType()->isIntegerTy())
696         continue;
697       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
698       int CallbackIdx = TypeSize == 8 ? 0 :
699                         TypeSize == 16 ? 1 :
700                         TypeSize == 32 ? 2 :
701                         TypeSize == 64 ? 3 : -1;
702       if (CallbackIdx < 0) continue;
703       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
704       auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
705       bool FirstIsConst = isa<ConstantInt>(A0);
706       bool SecondIsConst = isa<ConstantInt>(A1);
707       // If both are const, then we don't need such a comparison.
708       if (FirstIsConst && SecondIsConst) continue;
709       // If only one is const, then make it the first callback argument.
710       if (FirstIsConst || SecondIsConst) {
711         CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
712         if (SecondIsConst)
713           std::swap(A0, A1);
714       }
715 
716       auto Ty = Type::getIntNTy(*C, TypeSize);
717       IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
718               IRB.CreateIntCast(A1, Ty, true)});
719     }
720   }
721 }
722 
723 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
724                                                     size_t Idx) {
725   BasicBlock::iterator IP = BB.getFirstInsertionPt();
726   bool IsEntryBB = &BB == &F.getEntryBlock();
727   DebugLoc EntryLoc;
728   if (IsEntryBB) {
729     if (auto SP = F.getSubprogram())
730       EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
731     // Keep static allocas and llvm.localescape calls in the entry block.  Even
732     // if we aren't splitting the block, it's nice for allocas to be before
733     // calls.
734     IP = PrepareToSplitEntryBlock(BB, IP);
735   } else {
736     EntryLoc = IP->getDebugLoc();
737   }
738 
739   IRBuilder<> IRB(&*IP);
740   IRB.SetCurrentDebugLocation(EntryLoc);
741   if (Options.TracePC) {
742     IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
743     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
744   }
745   if (Options.TracePCGuard) {
746     auto GuardPtr = IRB.CreateIntToPtr(
747         IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
748                       ConstantInt::get(IntptrTy, Idx * 4)),
749         Int32PtrTy);
750     IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
751     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
752   }
753   if (Options.Inline8bitCounters) {
754     auto CounterPtr = IRB.CreateGEP(
755         Function8bitCounterArray,
756         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
757     auto Load = IRB.CreateLoad(CounterPtr);
758     auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
759     auto Store = IRB.CreateStore(Inc, CounterPtr);
760     SetNoSanitizeMetadata(Load);
761     SetNoSanitizeMetadata(Store);
762   }
763   if (Options.StackDepth && IsEntryBB) {
764     // Check stack depth.  If it's the deepest so far, record it.
765     Function *GetFrameAddr =
766         Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
767     auto FrameAddrPtr =
768         IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
769     auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
770     auto LowestStack = IRB.CreateLoad(SanCovLowestStack);
771     auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
772     auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
773     IRBuilder<> ThenIRB(ThenTerm);
774     ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
775   }
776 }
777 
778 std::string
779 SanitizerCoverageModule::getSectionName(const std::string &Section) const {
780   if (TargetTriple.getObjectFormat() == Triple::COFF)
781     return ".SCOV$M";
782   if (TargetTriple.isOSBinFormatMachO())
783     return "__DATA,__" + Section;
784   return "__" + Section;
785 }
786 
787 std::string
788 SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
789   if (TargetTriple.isOSBinFormatMachO())
790     return "\1section$start$__DATA$__" + Section;
791   return "__start___" + Section;
792 }
793 
794 std::string
795 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
796   if (TargetTriple.isOSBinFormatMachO())
797     return "\1section$end$__DATA$__" + Section;
798   return "__stop___" + Section;
799 }
800 
801 
802 char SanitizerCoverageModule::ID = 0;
803 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
804                       "SanitizerCoverage: TODO."
805                       "ModulePass",
806                       false, false)
807 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
808 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
809 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
810                     "SanitizerCoverage: TODO."
811                     "ModulePass",
812                     false, false)
813 ModulePass *llvm::createSanitizerCoverageModulePass(
814     const SanitizerCoverageOptions &Options) {
815   return new SanitizerCoverageModule(Options);
816 }
817