xref: /llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp (revision eac270caf45ce957daf3c01b01a5752a818344bd)
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/IntrinsicInst.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/MDBuilder.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Transforms/Instrumentation.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                       bool IsLeafFunc = true);
205   GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
206                                                     Function &F, Type *Ty,
207                                                     const char *Section);
208   GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
209   void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
210   void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
211                              bool IsLeafFunc = true);
212   Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName,
213                                        Type *Ty, const char *Section);
214   std::pair<GlobalVariable *, GlobalVariable *>
215   CreateSecStartEnd(Module &M, const char *Section, Type *Ty);
216 
217   void SetNoSanitizeMetadata(Instruction *I) {
218     I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
219                    MDNode::get(*C, None));
220   }
221 
222   std::string UniqueSuffix() {
223     static size_t Count = 0;
224     return "_sancov" + std::to_string(Count++);
225   }
226 
227   std::string getSectionName(const std::string &Section) const;
228   std::string getSectionStart(const std::string &Section) const;
229   std::string getSectionEnd(const std::string &Section) const;
230   Function *SanCovTracePCIndir;
231   Function *SanCovTracePC, *SanCovTracePCGuard;
232   Function *SanCovTraceCmpFunction[4];
233   Function *SanCovTraceConstCmpFunction[4];
234   Function *SanCovTraceDivFunction[2];
235   Function *SanCovTraceGepFunction;
236   Function *SanCovTraceSwitchFunction;
237   GlobalVariable *SanCovLowestStack;
238   InlineAsm *EmptyAsm;
239   Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
240       *Int16Ty, *Int8Ty, *Int8PtrTy;
241   Module *CurModule;
242   Triple TargetTriple;
243   LLVMContext *C;
244   const DataLayout *DL;
245 
246   GlobalVariable *FunctionGuardArray;  // for trace-pc-guard.
247   GlobalVariable *Function8bitCounterArray;  // for inline-8bit-counters.
248   GlobalVariable *FunctionPCsArray;  // for pc-table.
249   SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
250   SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
251 
252   SanitizerCoverageOptions Options;
253 };
254 
255 } // namespace
256 
257 std::pair<GlobalVariable *, GlobalVariable *>
258 SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section,
259                                            Type *Ty) {
260   GlobalVariable *SecStart =
261       new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
262                          getSectionStart(Section));
263   SecStart->setVisibility(GlobalValue::HiddenVisibility);
264   GlobalVariable *SecEnd =
265       new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
266                          nullptr, getSectionEnd(Section));
267   SecEnd->setVisibility(GlobalValue::HiddenVisibility);
268 
269   return std::make_pair(SecStart, SecEnd);
270 }
271 
272 
273 Function *SanitizerCoverageModule::CreateInitCallsForSections(
274     Module &M, const char *InitFunctionName, Type *Ty,
275     const char *Section) {
276   IRBuilder<> IRB(M.getContext());
277   auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
278   auto SecStart = SecStartEnd.first;
279   auto SecEnd = SecStartEnd.second;
280   Function *CtorFunc;
281   Value *SecStartPtr = nullptr;
282   // Account for the fact that on windows-msvc __start_* symbols actually
283   // point to a uint64_t before the start of the array.
284   if (TargetTriple.getObjectFormat() == Triple::COFF) {
285     auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
286     auto GEP = IRB.CreateGEP(SecStartI8Ptr,
287                              ConstantInt::get(IntptrTy, sizeof(uint64_t)));
288     SecStartPtr = IRB.CreatePointerCast(GEP, Ty);
289   } else {
290     SecStartPtr = IRB.CreatePointerCast(SecStart, Ty);
291   }
292   std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
293       M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
294       {SecStartPtr, IRB.CreatePointerCast(SecEnd, Ty)});
295 
296   if (TargetTriple.supportsCOMDAT()) {
297     // Use comdat to dedup CtorFunc.
298     CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
299     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
300   } else {
301     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
302   }
303   return CtorFunc;
304 }
305 
306 bool SanitizerCoverageModule::runOnModule(Module &M) {
307   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
308     return false;
309   C = &(M.getContext());
310   DL = &M.getDataLayout();
311   CurModule = &M;
312   TargetTriple = Triple(M.getTargetTriple());
313   FunctionGuardArray = nullptr;
314   Function8bitCounterArray = nullptr;
315   FunctionPCsArray = nullptr;
316   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
317   IntptrPtrTy = PointerType::getUnqual(IntptrTy);
318   Type *VoidTy = Type::getVoidTy(*C);
319   IRBuilder<> IRB(*C);
320   Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
321   Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
322   Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
323   Int64Ty = IRB.getInt64Ty();
324   Int32Ty = IRB.getInt32Ty();
325   Int16Ty = IRB.getInt16Ty();
326   Int8Ty = IRB.getInt8Ty();
327 
328   SanCovTracePCIndir = checkSanitizerInterfaceFunction(
329       M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
330   SanCovTraceCmpFunction[0] =
331       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
332           SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
333   SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
334       M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
335                             IRB.getInt16Ty()));
336   SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
337       M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
338                             IRB.getInt32Ty()));
339   SanCovTraceCmpFunction[3] =
340       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
341           SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
342 
343   SanCovTraceConstCmpFunction[0] =
344       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
345           SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty));
346   SanCovTraceConstCmpFunction[1] =
347       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
348           SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty));
349   SanCovTraceConstCmpFunction[2] =
350       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
351           SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty));
352   SanCovTraceConstCmpFunction[3] =
353       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
354           SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty));
355 
356   SanCovTraceDivFunction[0] =
357       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
358           SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
359   SanCovTraceDivFunction[1] =
360       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
361           SanCovTraceDiv8, VoidTy, Int64Ty));
362   SanCovTraceGepFunction =
363       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
364           SanCovTraceGep, VoidTy, IntptrTy));
365   SanCovTraceSwitchFunction =
366       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
367           SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
368 
369   Constant *SanCovLowestStackConstant =
370       M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
371   SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant);
372   SanCovLowestStack->setThreadLocalMode(
373       GlobalValue::ThreadLocalMode::InitialExecTLSModel);
374   if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
375     SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
376 
377   // Make sure smaller parameters are zero-extended to i64 as required by the
378   // x86_64 ABI.
379   if (TargetTriple.getArch() == Triple::x86_64) {
380     for (int i = 0; i < 3; i++) {
381       SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
382       SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
383       SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
384       SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
385     }
386     SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
387   }
388 
389 
390   // We insert an empty inline asm after cov callbacks to avoid callback merge.
391   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
392                             StringRef(""), StringRef(""),
393                             /*hasSideEffects=*/true);
394 
395   SanCovTracePC = checkSanitizerInterfaceFunction(
396       M.getOrInsertFunction(SanCovTracePCName, VoidTy));
397   SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
398       SanCovTracePCGuardName, VoidTy, Int32PtrTy));
399 
400   for (auto &F : M)
401     runOnFunction(F);
402 
403   Function *Ctor = nullptr;
404 
405   if (FunctionGuardArray)
406     Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
407                                       SanCovGuardsSectionName);
408   if (Function8bitCounterArray)
409     Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
410                                       SanCovCountersSectionName);
411   if (Ctor && Options.PCTable) {
412     auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
413     Function *InitFunction = declareSanitizerInitFunction(
414         M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
415     IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
416     Value *SecStartPtr = nullptr;
417     // Account for the fact that on windows-msvc __start_pc_table actually
418     // points to a uint64_t before the start of the PC table.
419     if (TargetTriple.getObjectFormat() == Triple::COFF) {
420       auto SecStartI8Ptr = IRB.CreatePointerCast(SecStartEnd.first, Int8PtrTy);
421       auto GEP = IRB.CreateGEP(SecStartI8Ptr,
422                                ConstantInt::get(IntptrTy, sizeof(uint64_t)));
423       SecStartPtr = IRB.CreatePointerCast(GEP, IntptrPtrTy);
424     } else {
425       SecStartPtr = IRB.CreatePointerCast(SecStartEnd.first, IntptrPtrTy);
426     }
427     IRBCtor.CreateCall(
428         InitFunction,
429         {SecStartPtr, IRB.CreatePointerCast(SecStartEnd.second, IntptrPtrTy)});
430   }
431   // We don't reference these arrays directly in any of our runtime functions,
432   // so we need to prevent them from being dead stripped.
433   if (TargetTriple.isOSBinFormatMachO())
434     appendToUsed(M, GlobalsToAppendToUsed);
435   appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
436   return true;
437 }
438 
439 // True if block has successors and it dominates all of them.
440 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
441   if (succ_begin(BB) == succ_end(BB))
442     return false;
443 
444   for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
445     if (!DT->dominates(BB, SUCC))
446       return false;
447   }
448 
449   return true;
450 }
451 
452 // True if block has predecessors and it postdominates all of them.
453 static bool isFullPostDominator(const BasicBlock *BB,
454                                 const PostDominatorTree *PDT) {
455   if (pred_begin(BB) == pred_end(BB))
456     return false;
457 
458   for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
459     if (!PDT->dominates(BB, PRED))
460       return false;
461   }
462 
463   return true;
464 }
465 
466 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
467                                   const DominatorTree *DT,
468                                   const PostDominatorTree *PDT,
469                                   const SanitizerCoverageOptions &Options) {
470   // Don't insert coverage for unreachable blocks: we will never call
471   // __sanitizer_cov() for them, so counting them in
472   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
473   // percentage. Also, unreachable instructions frequently have no debug
474   // locations.
475   if (isa<UnreachableInst>(BB->getTerminator()))
476     return false;
477 
478   // Don't insert coverage into blocks without a valid insertion point
479   // (catchswitch blocks).
480   if (BB->getFirstInsertionPt() == BB->end())
481     return false;
482 
483   if (Options.NoPrune || &F.getEntryBlock() == BB)
484     return true;
485 
486   if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
487       &F.getEntryBlock() != BB)
488     return false;
489 
490   // Do not instrument full dominators, or full post-dominators with multiple
491   // predecessors.
492   return !isFullDominator(BB, DT)
493     && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
494 }
495 
496 bool SanitizerCoverageModule::runOnFunction(Function &F) {
497   if (F.empty())
498     return false;
499   if (F.getName().find(".module_ctor") != std::string::npos)
500     return false; // Should not instrument sanitizer init functions.
501   if (F.getName().startswith("__sanitizer_"))
502     return false;  // Don't instrument __sanitizer_* callbacks.
503   // Don't touch available_externally functions, their actual body is elewhere.
504   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
505     return false;
506   // Don't instrument MSVC CRT configuration helpers. They may run before normal
507   // initialization.
508   if (F.getName() == "__local_stdio_printf_options" ||
509       F.getName() == "__local_stdio_scanf_options")
510     return false;
511   if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
512     return false;
513   // Don't instrument functions using SEH for now. Splitting basic blocks like
514   // we do for coverage breaks WinEHPrepare.
515   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
516   if (F.hasPersonalityFn() &&
517       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
518     return false;
519   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
520     SplitAllCriticalEdges(F);
521   SmallVector<Instruction *, 8> IndirCalls;
522   SmallVector<BasicBlock *, 16> BlocksToInstrument;
523   SmallVector<Instruction *, 8> CmpTraceTargets;
524   SmallVector<Instruction *, 8> SwitchTraceTargets;
525   SmallVector<BinaryOperator *, 8> DivTraceTargets;
526   SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
527 
528   const DominatorTree *DT =
529       &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
530   const PostDominatorTree *PDT =
531       &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
532   bool IsLeafFunc = true;
533 
534   for (auto &BB : F) {
535     if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
536       BlocksToInstrument.push_back(&BB);
537     for (auto &Inst : BB) {
538       if (Options.IndirectCalls) {
539         CallSite CS(&Inst);
540         if (CS && !CS.getCalledFunction())
541           IndirCalls.push_back(&Inst);
542       }
543       if (Options.TraceCmp) {
544         if (isa<ICmpInst>(&Inst))
545           CmpTraceTargets.push_back(&Inst);
546         if (isa<SwitchInst>(&Inst))
547           SwitchTraceTargets.push_back(&Inst);
548       }
549       if (Options.TraceDiv)
550         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
551           if (BO->getOpcode() == Instruction::SDiv ||
552               BO->getOpcode() == Instruction::UDiv)
553             DivTraceTargets.push_back(BO);
554       if (Options.TraceGep)
555         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
556           GepTraceTargets.push_back(GEP);
557       if (Options.StackDepth)
558         if (isa<InvokeInst>(Inst) ||
559             (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
560           IsLeafFunc = false;
561     }
562   }
563 
564   InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
565   InjectCoverageForIndirectCalls(F, IndirCalls);
566   InjectTraceForCmp(F, CmpTraceTargets);
567   InjectTraceForSwitch(F, SwitchTraceTargets);
568   InjectTraceForDiv(F, DivTraceTargets);
569   InjectTraceForGep(F, GepTraceTargets);
570   return true;
571 }
572 
573 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
574     size_t NumElements, Function &F, Type *Ty, const char *Section) {
575   ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
576   auto Array = new GlobalVariable(
577       *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
578       Constant::getNullValue(ArrayTy), "__sancov_gen_");
579   if (auto Comdat = F.getComdat()) {
580     Array->setComdat(Comdat);
581   } else {
582     // TODO: Refactor into a helper function and use it in ASan.
583     assert(F.hasName());
584     std::string Name = F.getName();
585     if (F.hasLocalLinkage()) {
586       std::string ModuleId = getUniqueModuleId(CurModule);
587       Name += ModuleId.empty() ? UniqueSuffix() : ModuleId;
588     }
589     Comdat = CurModule->getOrInsertComdat(Name);
590     // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
591     // linkage to internal linkage so that a symbol table entry is emitted. This
592     // is necessary in order to create the comdat group.
593     if (TargetTriple.isOSBinFormatCOFF()) {
594       Comdat->setSelectionKind(Comdat::NoDuplicates);
595       if (F.hasPrivateLinkage())
596         F.setLinkage(GlobalValue::InternalLinkage);
597     }
598     F.setComdat(Comdat);
599     Array->setComdat(Comdat);
600   }
601   Array->setSection(getSectionName(Section));
602   Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
603                                         : Ty->getPrimitiveSizeInBits() / 8);
604   GlobalsToAppendToCompilerUsed.push_back(Array);
605   MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F));
606   Array->addMetadata(LLVMContext::MD_associated, *MD);
607   return Array;
608 }
609 
610 GlobalVariable *
611 SanitizerCoverageModule::CreatePCArray(Function &F,
612                                        ArrayRef<BasicBlock *> AllBlocks) {
613   size_t N = AllBlocks.size();
614   assert(N);
615   SmallVector<Constant *, 32> PCs;
616   IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
617   for (size_t i = 0; i < N; i++) {
618     if (&F.getEntryBlock() == AllBlocks[i]) {
619       PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
620       PCs.push_back((Constant *)IRB.CreateIntToPtr(
621           ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
622     } else {
623       PCs.push_back((Constant *)IRB.CreatePointerCast(
624           BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
625       PCs.push_back((Constant *)IRB.CreateIntToPtr(
626           ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
627     }
628   }
629   auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
630                                                     SanCovPCsSectionName);
631   PCArray->setInitializer(
632       ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
633   PCArray->setConstant(true);
634 
635   return PCArray;
636 }
637 
638 void SanitizerCoverageModule::CreateFunctionLocalArrays(
639     Function &F, ArrayRef<BasicBlock *> AllBlocks) {
640   if (Options.TracePCGuard) {
641     FunctionGuardArray = CreateFunctionLocalArrayInSection(
642         AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
643     GlobalsToAppendToUsed.push_back(FunctionGuardArray);
644   }
645   if (Options.Inline8bitCounters)
646     Function8bitCounterArray = CreateFunctionLocalArrayInSection(
647         AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
648   if (Options.PCTable)
649     FunctionPCsArray = CreatePCArray(F, AllBlocks);
650 }
651 
652 bool SanitizerCoverageModule::InjectCoverage(Function &F,
653                                              ArrayRef<BasicBlock *> AllBlocks,
654                                              bool IsLeafFunc) {
655   if (AllBlocks.empty()) return false;
656   CreateFunctionLocalArrays(F, AllBlocks);
657   for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
658     InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
659   return true;
660 }
661 
662 // On every indirect call we call a run-time function
663 // __sanitizer_cov_indir_call* with two parameters:
664 //   - callee address,
665 //   - global cache array that contains CacheSize pointers (zero-initialized).
666 //     The cache is used to speed up recording the caller-callee pairs.
667 // The address of the caller is passed implicitly via caller PC.
668 // CacheSize is encoded in the name of the run-time function.
669 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
670     Function &F, ArrayRef<Instruction *> IndirCalls) {
671   if (IndirCalls.empty())
672     return;
673   assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
674   for (auto I : IndirCalls) {
675     IRBuilder<> IRB(I);
676     CallSite CS(I);
677     Value *Callee = CS.getCalledValue();
678     if (isa<InlineAsm>(Callee))
679       continue;
680     IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
681   }
682 }
683 
684 // For every switch statement we insert a call:
685 // __sanitizer_cov_trace_switch(CondValue,
686 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
687 
688 void SanitizerCoverageModule::InjectTraceForSwitch(
689     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
690   for (auto I : SwitchTraceTargets) {
691     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
692       IRBuilder<> IRB(I);
693       SmallVector<Constant *, 16> Initializers;
694       Value *Cond = SI->getCondition();
695       if (Cond->getType()->getScalarSizeInBits() >
696           Int64Ty->getScalarSizeInBits())
697         continue;
698       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
699       Initializers.push_back(
700           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
701       if (Cond->getType()->getScalarSizeInBits() <
702           Int64Ty->getScalarSizeInBits())
703         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
704       for (auto It : SI->cases()) {
705         Constant *C = It.getCaseValue();
706         if (C->getType()->getScalarSizeInBits() <
707             Int64Ty->getScalarSizeInBits())
708           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
709         Initializers.push_back(C);
710       }
711       llvm::sort(Initializers.begin() + 2, Initializers.end(),
712                  [](const Constant *A, const Constant *B) {
713                    return cast<ConstantInt>(A)->getLimitedValue() <
714                           cast<ConstantInt>(B)->getLimitedValue();
715                  });
716       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
717       GlobalVariable *GV = new GlobalVariable(
718           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
719           ConstantArray::get(ArrayOfInt64Ty, Initializers),
720           "__sancov_gen_cov_switch_values");
721       IRB.CreateCall(SanCovTraceSwitchFunction,
722                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
723     }
724   }
725 }
726 
727 void SanitizerCoverageModule::InjectTraceForDiv(
728     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
729   for (auto BO : DivTraceTargets) {
730     IRBuilder<> IRB(BO);
731     Value *A1 = BO->getOperand(1);
732     if (isa<ConstantInt>(A1)) continue;
733     if (!A1->getType()->isIntegerTy())
734       continue;
735     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
736     int CallbackIdx = TypeSize == 32 ? 0 :
737         TypeSize == 64 ? 1 : -1;
738     if (CallbackIdx < 0) continue;
739     auto Ty = Type::getIntNTy(*C, TypeSize);
740     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
741                    {IRB.CreateIntCast(A1, Ty, true)});
742   }
743 }
744 
745 void SanitizerCoverageModule::InjectTraceForGep(
746     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
747   for (auto GEP : GepTraceTargets) {
748     IRBuilder<> IRB(GEP);
749     for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
750       if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
751         IRB.CreateCall(SanCovTraceGepFunction,
752                        {IRB.CreateIntCast(*I, IntptrTy, true)});
753   }
754 }
755 
756 void SanitizerCoverageModule::InjectTraceForCmp(
757     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
758   for (auto I : CmpTraceTargets) {
759     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
760       IRBuilder<> IRB(ICMP);
761       Value *A0 = ICMP->getOperand(0);
762       Value *A1 = ICMP->getOperand(1);
763       if (!A0->getType()->isIntegerTy())
764         continue;
765       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
766       int CallbackIdx = TypeSize == 8 ? 0 :
767                         TypeSize == 16 ? 1 :
768                         TypeSize == 32 ? 2 :
769                         TypeSize == 64 ? 3 : -1;
770       if (CallbackIdx < 0) continue;
771       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
772       auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
773       bool FirstIsConst = isa<ConstantInt>(A0);
774       bool SecondIsConst = isa<ConstantInt>(A1);
775       // If both are const, then we don't need such a comparison.
776       if (FirstIsConst && SecondIsConst) continue;
777       // If only one is const, then make it the first callback argument.
778       if (FirstIsConst || SecondIsConst) {
779         CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
780         if (SecondIsConst)
781           std::swap(A0, A1);
782       }
783 
784       auto Ty = Type::getIntNTy(*C, TypeSize);
785       IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
786               IRB.CreateIntCast(A1, Ty, true)});
787     }
788   }
789 }
790 
791 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
792                                                     size_t Idx,
793                                                     bool IsLeafFunc) {
794   BasicBlock::iterator IP = BB.getFirstInsertionPt();
795   bool IsEntryBB = &BB == &F.getEntryBlock();
796   DebugLoc EntryLoc;
797   if (IsEntryBB) {
798     if (auto SP = F.getSubprogram())
799       EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
800     // Keep static allocas and llvm.localescape calls in the entry block.  Even
801     // if we aren't splitting the block, it's nice for allocas to be before
802     // calls.
803     IP = PrepareToSplitEntryBlock(BB, IP);
804   } else {
805     EntryLoc = IP->getDebugLoc();
806   }
807 
808   IRBuilder<> IRB(&*IP);
809   IRB.SetCurrentDebugLocation(EntryLoc);
810   if (Options.TracePC) {
811     IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
812     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
813   }
814   if (Options.TracePCGuard) {
815     auto GuardPtr = IRB.CreateIntToPtr(
816         IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
817                       ConstantInt::get(IntptrTy, Idx * 4)),
818         Int32PtrTy);
819     IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
820     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
821   }
822   if (Options.Inline8bitCounters) {
823     auto CounterPtr = IRB.CreateGEP(
824         Function8bitCounterArray,
825         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
826     auto Load = IRB.CreateLoad(CounterPtr);
827     auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
828     auto Store = IRB.CreateStore(Inc, CounterPtr);
829     SetNoSanitizeMetadata(Load);
830     SetNoSanitizeMetadata(Store);
831   }
832   if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
833     // Check stack depth.  If it's the deepest so far, record it.
834     Function *GetFrameAddr =
835         Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
836     auto FrameAddrPtr =
837         IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
838     auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
839     auto LowestStack = IRB.CreateLoad(SanCovLowestStack);
840     auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
841     auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
842     IRBuilder<> ThenIRB(ThenTerm);
843     auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
844     SetNoSanitizeMetadata(LowestStack);
845     SetNoSanitizeMetadata(Store);
846   }
847 }
848 
849 std::string
850 SanitizerCoverageModule::getSectionName(const std::string &Section) const {
851   if (TargetTriple.getObjectFormat() == Triple::COFF) {
852     if (Section == SanCovCountersSectionName)
853       return ".SCOV$CM";
854     if (Section == SanCovPCsSectionName)
855       return ".SCOVP$M";
856     return ".SCOV$GM"; // For SanCovGuardsSectionName.
857   }
858   if (TargetTriple.isOSBinFormatMachO())
859     return "__DATA,__" + Section;
860   return "__" + Section;
861 }
862 
863 std::string
864 SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
865   if (TargetTriple.isOSBinFormatMachO())
866     return "\1section$start$__DATA$__" + Section;
867   return "__start___" + Section;
868 }
869 
870 std::string
871 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
872   if (TargetTriple.isOSBinFormatMachO())
873     return "\1section$end$__DATA$__" + Section;
874   return "__stop___" + Section;
875 }
876 
877 
878 char SanitizerCoverageModule::ID = 0;
879 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
880                       "SanitizerCoverage: TODO."
881                       "ModulePass",
882                       false, false)
883 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
884 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
885 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
886                     "SanitizerCoverage: TODO."
887                     "ModulePass",
888                     false, false)
889 ModulePass *llvm::createSanitizerCoverageModulePass(
890     const SanitizerCoverageOptions &Options) {
891   return new SanitizerCoverageModule(Options);
892 }
893