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