LLVM  10.0.0svn
SanitizerCoverage.cpp
Go to the documentation of this file.
1 //===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Coverage instrumentation done on LLVM IR level, works with Sanitizers.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/SmallVector.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/Mangler.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Type.h"
36 #include "llvm/Support/Debug.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 SanCovModuleCtorTracePcGuardName =
66  "sancov.module_ctor_trace_pc_guard";
67 static const char *const SanCovModuleCtor8bitCountersName =
68  "sancov.module_ctor_8bit_counters";
69 static const uint64_t SanCtorAndDtorPriority = 2;
70 
71 static const char *const SanCovTracePCGuardName =
72  "__sanitizer_cov_trace_pc_guard";
73 static const char *const SanCovTracePCGuardInitName =
74  "__sanitizer_cov_trace_pc_guard_init";
75 static const char *const SanCov8bitCountersInitName =
76  "__sanitizer_cov_8bit_counters_init";
77 static const char *const SanCovPCsInitName = "__sanitizer_cov_pcs_init";
78 
79 static const char *const SanCovGuardsSectionName = "sancov_guards";
80 static const char *const SanCovCountersSectionName = "sancov_cntrs";
81 static const char *const SanCovPCsSectionName = "sancov_pcs";
82 
83 static const char *const SanCovLowestStackName = "__sancov_lowest_stack";
84 
86  "sanitizer-coverage-level",
87  cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
88  "3: all blocks and critical edges"),
89  cl::Hidden, cl::init(0));
90 
91 static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
92  cl::desc("Experimental pc tracing"), cl::Hidden,
93  cl::init(false));
94 
95 static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
96  cl::desc("pc tracing with a guard"),
97  cl::Hidden, cl::init(false));
98 
99 // If true, we create a global variable that contains PCs of all instrumented
100 // BBs, put this global into a named section, and pass this section's bounds
101 // to __sanitizer_cov_pcs_init.
102 // This way the coverage instrumentation does not need to acquire the PCs
103 // at run-time. Works with trace-pc-guard and inline-8bit-counters.
104 static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
105  cl::desc("create a static PC table"),
106  cl::Hidden, cl::init(false));
107 
108 static cl::opt<bool>
109  ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
110  cl::desc("increments 8-bit counter for every edge"),
111  cl::Hidden, cl::init(false));
112 
113 static cl::opt<bool>
114  ClCMPTracing("sanitizer-coverage-trace-compares",
115  cl::desc("Tracing of CMP and similar instructions"),
116  cl::Hidden, cl::init(false));
117 
118 static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
119  cl::desc("Tracing of DIV instructions"),
120  cl::Hidden, cl::init(false));
121 
122 static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
123  cl::desc("Tracing of GEP instructions"),
124  cl::Hidden, cl::init(false));
125 
126 static cl::opt<bool>
127  ClPruneBlocks("sanitizer-coverage-prune-blocks",
128  cl::desc("Reduce the number of instrumented blocks"),
129  cl::Hidden, cl::init(true));
130 
131 static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
132  cl::desc("max stack depth tracing"),
133  cl::Hidden, cl::init(false));
134 
135 namespace {
136 
137 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
139  switch (LegacyCoverageLevel) {
140  case 0:
142  break;
143  case 1:
145  break;
146  case 2:
148  break;
149  case 3:
151  break;
152  case 4:
154  Res.IndirectCalls = true;
155  break;
156  }
157  return Res;
158 }
159 
160 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
161  // Sets CoverageType and IndirectCalls.
162  SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
163  Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
164  Options.IndirectCalls |= CLOpts.IndirectCalls;
165  Options.TraceCmp |= ClCMPTracing;
166  Options.TraceDiv |= ClDIVTracing;
167  Options.TraceGep |= ClGEPTracing;
168  Options.TracePC |= ClTracePC;
169  Options.TracePCGuard |= ClTracePCGuard;
171  Options.PCTable |= ClCreatePCTable;
172  Options.NoPrune |= !ClPruneBlocks;
173  Options.StackDepth |= ClStackDepth;
174  if (!Options.TracePCGuard && !Options.TracePC &&
175  !Options.Inline8bitCounters && !Options.StackDepth)
176  Options.TracePCGuard = true; // TracePCGuard is default.
177  return Options;
178 }
179 
180 bool canInstrumentWithSancov(const Function &F) {
181  if (F.empty())
182  return false;
183  if (F.getName().find(".module_ctor") != std::string::npos)
184  return false; // Should not instrument sanitizer init functions.
185  if (F.getName().startswith("__sanitizer_"))
186  return false; // Don't instrument __sanitizer_* callbacks.
187  // Don't touch available_externally functions, their actual body is elewhere.
189  return false;
190  // Don't instrument MSVC CRT configuration helpers. They may run before normal
191  // initialization.
192  if (F.getName() == "__local_stdio_printf_options" ||
193  F.getName() == "__local_stdio_scanf_options")
194  return false;
195  if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
196  return false;
197  // Don't instrument functions using SEH for now. Splitting basic blocks like
198  // we do for coverage breaks WinEHPrepare.
199  // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
200  if (F.hasPersonalityFn() &&
202  return false;
203  return true;
204 }
205 
206 std::string getSectionStartImpl(const Triple &TargetTriple,
207  const std::string &Section) {
208  if (TargetTriple.isOSBinFormatMachO())
209  return "\1section$start$__DATA$__" + Section;
210  return "__start___" + Section;
211 }
212 
213 std::string getSectionEndImpl(const Triple &TargetTriple,
214  const std::string &Section) {
215  if (TargetTriple.isOSBinFormatMachO())
216  return "\1section$end$__DATA$__" + Section;
217  return "__stop___" + Section;
218 }
219 
220 /// This is a class for instrumenting the module to add calls to initializing
221 /// the trace PC guards and 8bit counter globals. This should only be done
222 /// though if there is at least one function that can be instrumented with
223 /// Sancov.
224 class ModuleSanitizerCoverage {
225 public:
226  ModuleSanitizerCoverage(const SanitizerCoverageOptions &Options)
227  : Options(OverrideFromCL(Options)) {}
228 
229  bool instrumentModule(Module &M) {
231  return false;
232 
233  Function *Ctor = nullptr;
234  LLVMContext *C = &(M.getContext());
235  const DataLayout *DL = &M.getDataLayout();
236  TargetTriple = Triple(M.getTargetTriple());
237  IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
238  Type *IntptrPtrTy = PointerType::getUnqual(IntptrTy);
239  IRBuilder<> IRB(*C);
240  Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
241  Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
242  Int8Ty = IRB.getInt8Ty();
243 
244  // Check that the __sancov_lowest_stack marker does not already exist.
245  Constant *SanCovLowestStackConstant =
246  M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
247  GlobalVariable *SanCovLowestStack =
248  dyn_cast<GlobalVariable>(SanCovLowestStackConstant);
249  if (!SanCovLowestStack) {
250  C->emitError(StringRef("'") + SanCovLowestStackName +
251  "' should not be declared by the user");
252  return true;
253  }
254 
255  // We want to emit guard init calls if the module contains a function that
256  // we can instrument with SanitizerCoverage. We ignore any functions that
257  // were inserted by SanitizerCoverage and get the result from the analysis
258  // that checks for a valid function that the analysis may have run over.
259  if (!llvm::any_of(
260  M, [](const Function &F) { return canInstrumentWithSancov(F); }))
261  return false;
262 
263  // Emit the init calls.
264  if (Options.TracePCGuard)
265  Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
266  SanCovTracePCGuardInitName, Int32PtrTy,
267  SanCovGuardsSectionName);
268  if (Options.Inline8bitCounters)
269  Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
270  SanCov8bitCountersInitName, Int8PtrTy,
271  SanCovCountersSectionName);
272  if (Ctor && Options.PCTable) {
273  auto SecStartEnd =
274  CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
276  M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
277  IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
278  IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
279  }
280  return Ctor;
281  }
282 
283 private:
284  Function *CreateInitCallsForSections(Module &M, const char *CtorName,
285  const char *InitFunctionName, Type *Ty,
286  const char *Section);
287  std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
288  Type *Ty);
289  std::string getSectionStart(const std::string &Section) const {
290  return getSectionStartImpl(TargetTriple, Section);
291  }
292  std::string getSectionEnd(const std::string &Section) const {
293  return getSectionEndImpl(TargetTriple, Section);
294  }
295 
296  SanitizerCoverageOptions Options;
297  Triple TargetTriple;
298  Type *IntptrTy, *Int8PtrTy, *Int8Ty;
299 };
300 
301 class ModuleSanitizerCoverageLegacyPass : public ModulePass {
302 public:
303  static char ID;
304 
305  ModuleSanitizerCoverageLegacyPass(
307  : ModulePass(ID), Options(Options) {
310  }
311 
312  bool runOnModule(Module &M) override {
313  ModuleSanitizerCoverage ModuleSancov(Options);
314  return ModuleSancov.instrumentModule(M);
315  };
316 
317  StringRef getPassName() const override {
318  return "ModuleSanitizerCoverageLegacyPass";
319  }
320 
321 private:
322  SanitizerCoverageOptions Options;
323 };
324 
326 
327 class SanitizerCoverage {
328 public:
329  SanitizerCoverage(Function &F, const SanitizerCoverageOptions &Options)
330  : CurModule(F.getParent()), Options(OverrideFromCL(Options)) {
331  initializeModule(*F.getParent());
332  }
333 
334  ~SanitizerCoverage() { finalizeModule(*CurModule); }
335 
336  bool instrumentFunction(Function &F, const DominatorTree *DT,
337  const PostDominatorTree *PDT);
338 
339 private:
340  void initializeModule(Module &M);
341  void finalizeModule(Module &M);
342  void InjectCoverageForIndirectCalls(Function &F,
343  ArrayRef<Instruction *> IndirCalls);
344  void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
345  void InjectTraceForDiv(Function &F,
346  ArrayRef<BinaryOperator *> DivTraceTargets);
347  void InjectTraceForGep(Function &F,
348  ArrayRef<GetElementPtrInst *> GepTraceTargets);
349  void InjectTraceForSwitch(Function &F,
350  ArrayRef<Instruction *> SwitchTraceTargets);
351  bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
352  bool IsLeafFunc = true);
353  GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
354  Function &F, Type *Ty,
355  const char *Section);
356  GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
357  void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
358  void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
359  bool IsLeafFunc = true);
360 
361  void SetNoSanitizeMetadata(Instruction *I) {
362  I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
363  MDNode::get(*C, None));
364  }
365 
366  std::string getSectionName(const std::string &Section) const;
367  std::string getSectionStart(const std::string &Section) const;
368  std::string getSectionEnd(const std::string &Section) const;
369  FunctionCallee SanCovTracePCIndir;
370  FunctionCallee SanCovTracePC, SanCovTracePCGuard;
371  FunctionCallee SanCovTraceCmpFunction[4];
372  FunctionCallee SanCovTraceConstCmpFunction[4];
373  FunctionCallee SanCovTraceDivFunction[2];
374  FunctionCallee SanCovTraceGepFunction;
375  FunctionCallee SanCovTraceSwitchFunction;
376  GlobalVariable *SanCovLowestStack;
377  InlineAsm *EmptyAsm;
378  Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
379  *Int16Ty, *Int8Ty, *Int8PtrTy;
380  Module *CurModule;
381  std::string CurModuleUniqueId;
382  Triple TargetTriple;
383  LLVMContext *C;
384  const DataLayout *DL;
385 
386  GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
387  GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
388  GlobalVariable *FunctionPCsArray; // for pc-table.
389  SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
390  SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
391 
392  SanitizerCoverageOptions Options;
393 };
394 
395 class SanitizerCoverageLegacyPass : public FunctionPass {
396 public:
397  static char ID; // Pass identification, replacement for typeid
398 
399  SanitizerCoverageLegacyPass(
401  : FunctionPass(ID), Options(Options) {
403  }
404 
405  bool runOnFunction(Function &F) override {
406  const DominatorTree *DT =
407  &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
408  const PostDominatorTree *PDT =
409  &getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
410  SanitizerCoverage Sancov(F, Options);
411  return Sancov.instrumentFunction(F, DT, PDT);
412  }
413 
414  StringRef getPassName() const override {
415  return "SanitizerCoverageLegacyPass";
416  }
417 
418  void getAnalysisUsage(AnalysisUsage &AU) const override {
419  // Make the module sancov pass required by this pass so that it runs when
420  // -sancov is passed.
421  AU.addRequired<ModuleSanitizerCoverageLegacyPass>();
424  }
425 
426 private:
427  SanitizerCoverageOptions Options;
428 };
429 
430 } // namespace
431 
436  SanitizerCoverage Sancov(F, Options);
437  if (Sancov.instrumentFunction(F, DT, PDT))
438  return PreservedAnalyses::none();
439  return PreservedAnalyses::all();
440 }
441 
443  ModuleAnalysisManager &AM) {
444  ModuleSanitizerCoverage ModuleSancov(Options);
445  if (ModuleSancov.instrumentModule(M))
446  return PreservedAnalyses::none();
447  return PreservedAnalyses::all();
448 }
449 
450 std::pair<Value *, Value *>
451 ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section,
452  Type *Ty) {
453  GlobalVariable *SecStart =
454  new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
455  getSectionStart(Section));
457  GlobalVariable *SecEnd =
459  nullptr, getSectionEnd(Section));
461 
462  IRBuilder<> IRB(M.getContext());
463  Value *SecEndPtr = IRB.CreatePointerCast(SecEnd, Ty);
464  if (!TargetTriple.isOSBinFormatCOFF())
465  return std::make_pair(IRB.CreatePointerCast(SecStart, Ty), SecEndPtr);
466 
467  // Account for the fact that on windows-msvc __start_* symbols actually
468  // point to a uint64_t before the start of the array.
469  auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
470  auto GEP = IRB.CreateGEP(Int8Ty, SecStartI8Ptr,
471  ConstantInt::get(IntptrTy, sizeof(uint64_t)));
472  return std::make_pair(IRB.CreatePointerCast(GEP, Ty), SecEndPtr);
473 }
474 
475 Function *ModuleSanitizerCoverage::CreateInitCallsForSections(
476  Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
477  const char *Section) {
478  auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
479  auto SecStart = SecStartEnd.first;
480  auto SecEnd = SecStartEnd.second;
481  Function *CtorFunc;
482  std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
483  M, CtorName, InitFunctionName, {Ty, Ty}, {SecStart, SecEnd});
484  assert(CtorFunc->getName() == CtorName);
485 
486  if (TargetTriple.supportsCOMDAT()) {
487  // Use comdat to dedup CtorFunc.
488  CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
489  appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
490  } else {
492  }
493 
494  if (TargetTriple.isOSBinFormatCOFF()) {
495  // In COFF files, if the contructors are set as COMDAT (they are because
496  // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
497  // functions and data) is used, the constructors get stripped. To prevent
498  // this, give the constructors weak ODR linkage and ensure the linker knows
499  // to include the sancov constructor. This way the linker can deduplicate
500  // the constructors but always leave one copy.
502  appendToUsed(M, CtorFunc);
503  }
504  return CtorFunc;
505 }
506 
507 void SanitizerCoverage::initializeModule(Module &M) {
509  return;
510  C = &(M.getContext());
511  DL = &M.getDataLayout();
512  CurModuleUniqueId = getUniqueModuleId(CurModule);
513  TargetTriple = Triple(M.getTargetTriple());
514  FunctionGuardArray = nullptr;
515  Function8bitCounterArray = nullptr;
516  FunctionPCsArray = nullptr;
517  IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
518  IntptrPtrTy = PointerType::getUnqual(IntptrTy);
519  Type *VoidTy = Type::getVoidTy(*C);
520  IRBuilder<> IRB(*C);
521  Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
522  Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
523  Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
524  Int64Ty = IRB.getInt64Ty();
525  Int32Ty = IRB.getInt32Ty();
526  Int16Ty = IRB.getInt16Ty();
527  Int8Ty = IRB.getInt8Ty();
528 
529  SanCovTracePCIndir =
530  M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
531  // Make sure smaller parameters are zero-extended to i64 as required by the
532  // x86_64 ABI.
533  AttributeList SanCovTraceCmpZeroExtAL;
534  if (TargetTriple.getArch() == Triple::x86_64) {
535  SanCovTraceCmpZeroExtAL =
536  SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
537  SanCovTraceCmpZeroExtAL =
538  SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
539  }
540 
541  SanCovTraceCmpFunction[0] =
542  M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
543  IRB.getInt8Ty(), IRB.getInt8Ty());
544  SanCovTraceCmpFunction[1] =
545  M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
546  IRB.getInt16Ty(), IRB.getInt16Ty());
547  SanCovTraceCmpFunction[2] =
548  M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
549  IRB.getInt32Ty(), IRB.getInt32Ty());
550  SanCovTraceCmpFunction[3] =
551  M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
552 
553  SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
554  SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
555  SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
556  SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
557  SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
558  SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
559  SanCovTraceConstCmpFunction[3] =
560  M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
561 
562  {
564  if (TargetTriple.getArch() == Triple::x86_64)
565  AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
566  SanCovTraceDivFunction[0] =
567  M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
568  }
569  SanCovTraceDivFunction[1] =
570  M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
571  SanCovTraceGepFunction =
572  M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
573  SanCovTraceSwitchFunction =
574  M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy);
575 
576  Constant *SanCovLowestStackConstant =
577  M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
578  SanCovLowestStack = dyn_cast<GlobalVariable>(SanCovLowestStackConstant);
579  SanCovLowestStack->setThreadLocalMode(
580  GlobalValue::ThreadLocalMode::InitialExecTLSModel);
581  if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
582  SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
583 
584  // We insert an empty inline asm after cov callbacks to avoid callback merge.
585  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
586  StringRef(""), StringRef(""),
587  /*hasSideEffects=*/true);
588 
589  SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
590  SanCovTracePCGuard =
591  M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy);
592 }
593 
594 void SanitizerCoverage::finalizeModule(Module &M) {
595  // We don't reference these arrays directly in any of our runtime functions,
596  // so we need to prevent them from being dead stripped.
597  if (TargetTriple.isOSBinFormatMachO())
598  appendToUsed(M, GlobalsToAppendToUsed);
599  appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
600 }
601 
602 // True if block has successors and it dominates all of them.
603 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
604  if (succ_begin(BB) == succ_end(BB))
605  return false;
606 
607  for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
608  if (!DT->dominates(BB, SUCC))
609  return false;
610  }
611 
612  return true;
613 }
614 
615 // True if block has predecessors and it postdominates all of them.
616 static bool isFullPostDominator(const BasicBlock *BB,
617  const PostDominatorTree *PDT) {
618  if (pred_begin(BB) == pred_end(BB))
619  return false;
620 
621  for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
622  if (!PDT->dominates(BB, PRED))
623  return false;
624  }
625 
626  return true;
627 }
628 
629 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
630  const DominatorTree *DT,
631  const PostDominatorTree *PDT,
632  const SanitizerCoverageOptions &Options) {
633  // Don't insert coverage for blocks containing nothing but unreachable: we
634  // will never call __sanitizer_cov() for them, so counting them in
635  // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
636  // percentage. Also, unreachable instructions frequently have no debug
637  // locations.
638  if (isa<UnreachableInst>(BB->getFirstNonPHIOrDbgOrLifetime()))
639  return false;
640 
641  // Don't insert coverage into blocks without a valid insertion point
642  // (catchswitch blocks).
643  if (BB->getFirstInsertionPt() == BB->end())
644  return false;
645 
646  if (Options.NoPrune || &F.getEntryBlock() == BB)
647  return true;
648 
650  &F.getEntryBlock() != BB)
651  return false;
652 
653  // Do not instrument full dominators, or full post-dominators with multiple
654  // predecessors.
655  return !isFullDominator(BB, DT)
656  && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
657 }
658 
659 
660 // Returns true iff From->To is a backedge.
661 // A twist here is that we treat From->To as a backedge if
662 // * To dominates From or
663 // * To->UniqueSuccessor dominates From
665  const DominatorTree *DT) {
666  if (DT->dominates(To, From))
667  return true;
668  if (auto Next = To->getUniqueSuccessor())
669  if (DT->dominates(Next, From))
670  return true;
671  return false;
672 }
673 
674 // Prunes uninteresting Cmp instrumentation:
675 // * CMP instructions that feed into loop backedge branch.
676 //
677 // Note that Cmp pruning is controlled by the same flag as the
678 // BB pruning.
679 static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT,
680  const SanitizerCoverageOptions &Options) {
681  if (!Options.NoPrune)
682  if (CMP->hasOneUse())
683  if (auto BR = dyn_cast<BranchInst>(CMP->user_back()))
684  for (BasicBlock *B : BR->successors())
685  if (IsBackEdge(BR->getParent(), B, DT))
686  return false;
687  return true;
688 }
689 
690 bool SanitizerCoverage::instrumentFunction(Function &F, const DominatorTree *DT,
691  const PostDominatorTree *PDT) {
693  return false;
694  if (!canInstrumentWithSancov(F))
695  return false;
697  SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
699  SmallVector<BasicBlock *, 16> BlocksToInstrument;
700  SmallVector<Instruction *, 8> CmpTraceTargets;
701  SmallVector<Instruction *, 8> SwitchTraceTargets;
702  SmallVector<BinaryOperator *, 8> DivTraceTargets;
703  SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
704 
705  bool IsLeafFunc = true;
706 
707  for (auto &BB : F) {
708  if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
709  BlocksToInstrument.push_back(&BB);
710  for (auto &Inst : BB) {
711  if (Options.IndirectCalls) {
712  CallSite CS(&Inst);
713  if (CS && !CS.getCalledFunction())
714  IndirCalls.push_back(&Inst);
715  }
716  if (Options.TraceCmp) {
717  if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
718  if (IsInterestingCmp(CMP, DT, Options))
719  CmpTraceTargets.push_back(&Inst);
720  if (isa<SwitchInst>(&Inst))
721  SwitchTraceTargets.push_back(&Inst);
722  }
723  if (Options.TraceDiv)
724  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
725  if (BO->getOpcode() == Instruction::SDiv ||
726  BO->getOpcode() == Instruction::UDiv)
727  DivTraceTargets.push_back(BO);
728  if (Options.TraceGep)
729  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
730  GepTraceTargets.push_back(GEP);
731  if (Options.StackDepth)
732  if (isa<InvokeInst>(Inst) ||
733  (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
734  IsLeafFunc = false;
735  }
736  }
737 
738  InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
739  InjectCoverageForIndirectCalls(F, IndirCalls);
740  InjectTraceForCmp(F, CmpTraceTargets);
741  InjectTraceForSwitch(F, SwitchTraceTargets);
742  InjectTraceForDiv(F, DivTraceTargets);
743  InjectTraceForGep(F, GepTraceTargets);
744  return true;
745 }
746 
747 GlobalVariable *SanitizerCoverage::CreateFunctionLocalArrayInSection(
748  size_t NumElements, Function &F, Type *Ty, const char *Section) {
749  ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
750  auto Array = new GlobalVariable(
751  *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
752  Constant::getNullValue(ArrayTy), "__sancov_gen_");
753 
754  if (TargetTriple.supportsCOMDAT() && !F.isInterposable())
755  if (auto Comdat =
756  GetOrCreateFunctionComdat(F, TargetTriple, CurModuleUniqueId))
757  Array->setComdat(Comdat);
758  Array->setSection(getSectionName(Section));
759  Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
760  : Ty->getPrimitiveSizeInBits() / 8);
761  GlobalsToAppendToUsed.push_back(Array);
762  GlobalsToAppendToCompilerUsed.push_back(Array);
764  Array->addMetadata(LLVMContext::MD_associated, *MD);
765 
766  return Array;
767 }
768 
770 SanitizerCoverage::CreatePCArray(Function &F,
771  ArrayRef<BasicBlock *> AllBlocks) {
772  size_t N = AllBlocks.size();
773  assert(N);
776  for (size_t i = 0; i < N; i++) {
777  if (&F.getEntryBlock() == AllBlocks[i]) {
778  PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
779  PCs.push_back((Constant *)IRB.CreateIntToPtr(
780  ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
781  } else {
782  PCs.push_back((Constant *)IRB.CreatePointerCast(
783  BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
784  PCs.push_back((Constant *)IRB.CreateIntToPtr(
785  ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
786  }
787  }
788  auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
789  SanCovPCsSectionName);
790  PCArray->setInitializer(
791  ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
792  PCArray->setConstant(true);
793 
794  return PCArray;
795 }
796 
797 void SanitizerCoverage::CreateFunctionLocalArrays(
798  Function &F, ArrayRef<BasicBlock *> AllBlocks) {
799  if (Options.TracePCGuard)
800  FunctionGuardArray = CreateFunctionLocalArrayInSection(
801  AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
802 
803  if (Options.Inline8bitCounters)
804  Function8bitCounterArray = CreateFunctionLocalArrayInSection(
805  AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
806 
807  if (Options.PCTable)
808  FunctionPCsArray = CreatePCArray(F, AllBlocks);
809 }
810 
811 bool SanitizerCoverage::InjectCoverage(Function &F,
812  ArrayRef<BasicBlock *> AllBlocks,
813  bool IsLeafFunc) {
814  if (AllBlocks.empty()) return false;
815  CreateFunctionLocalArrays(F, AllBlocks);
816  for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
817  InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
818  return true;
819 }
820 
821 // On every indirect call we call a run-time function
822 // __sanitizer_cov_indir_call* with two parameters:
823 // - callee address,
824 // - global cache array that contains CacheSize pointers (zero-initialized).
825 // The cache is used to speed up recording the caller-callee pairs.
826 // The address of the caller is passed implicitly via caller PC.
827 // CacheSize is encoded in the name of the run-time function.
828 void SanitizerCoverage::InjectCoverageForIndirectCalls(
829  Function &F, ArrayRef<Instruction *> IndirCalls) {
830  if (IndirCalls.empty())
831  return;
832  assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
833  for (auto I : IndirCalls) {
834  IRBuilder<> IRB(I);
835  CallSite CS(I);
836  Value *Callee = CS.getCalledValue();
837  if (isa<InlineAsm>(Callee))
838  continue;
839  IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
840  }
841 }
842 
843 // For every switch statement we insert a call:
844 // __sanitizer_cov_trace_switch(CondValue,
845 // {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
846 
847 void SanitizerCoverage::InjectTraceForSwitch(
848  Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
849  for (auto I : SwitchTraceTargets) {
850  if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
851  IRBuilder<> IRB(I);
852  SmallVector<Constant *, 16> Initializers;
853  Value *Cond = SI->getCondition();
854  if (Cond->getType()->getScalarSizeInBits() >
855  Int64Ty->getScalarSizeInBits())
856  continue;
857  Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
858  Initializers.push_back(
859  ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
860  if (Cond->getType()->getScalarSizeInBits() <
861  Int64Ty->getScalarSizeInBits())
862  Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
863  for (auto It : SI->cases()) {
864  Constant *C = It.getCaseValue();
865  if (C->getType()->getScalarSizeInBits() <
866  Int64Ty->getScalarSizeInBits())
867  C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
868  Initializers.push_back(C);
869  }
870  llvm::sort(Initializers.begin() + 2, Initializers.end(),
871  [](const Constant *A, const Constant *B) {
872  return cast<ConstantInt>(A)->getLimitedValue() <
873  cast<ConstantInt>(B)->getLimitedValue();
874  });
875  ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
876  GlobalVariable *GV = new GlobalVariable(
877  *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
878  ConstantArray::get(ArrayOfInt64Ty, Initializers),
879  "__sancov_gen_cov_switch_values");
880  IRB.CreateCall(SanCovTraceSwitchFunction,
881  {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
882  }
883  }
884 }
885 
886 void SanitizerCoverage::InjectTraceForDiv(
887  Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
888  for (auto BO : DivTraceTargets) {
889  IRBuilder<> IRB(BO);
890  Value *A1 = BO->getOperand(1);
891  if (isa<ConstantInt>(A1)) continue;
892  if (!A1->getType()->isIntegerTy())
893  continue;
894  uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
895  int CallbackIdx = TypeSize == 32 ? 0 :
896  TypeSize == 64 ? 1 : -1;
897  if (CallbackIdx < 0) continue;
898  auto Ty = Type::getIntNTy(*C, TypeSize);
899  IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
900  {IRB.CreateIntCast(A1, Ty, true)});
901  }
902 }
903 
904 void SanitizerCoverage::InjectTraceForGep(
905  Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
906  for (auto GEP : GepTraceTargets) {
907  IRBuilder<> IRB(GEP);
908  for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
909  if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
910  IRB.CreateCall(SanCovTraceGepFunction,
911  {IRB.CreateIntCast(*I, IntptrTy, true)});
912  }
913 }
914 
915 void SanitizerCoverage::InjectTraceForCmp(
916  Function &, ArrayRef<Instruction *> CmpTraceTargets) {
917  for (auto I : CmpTraceTargets) {
918  if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
919  IRBuilder<> IRB(ICMP);
920  Value *A0 = ICMP->getOperand(0);
921  Value *A1 = ICMP->getOperand(1);
922  if (!A0->getType()->isIntegerTy())
923  continue;
924  uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
925  int CallbackIdx = TypeSize == 8 ? 0 :
926  TypeSize == 16 ? 1 :
927  TypeSize == 32 ? 2 :
928  TypeSize == 64 ? 3 : -1;
929  if (CallbackIdx < 0) continue;
930  // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
931  auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
932  bool FirstIsConst = isa<ConstantInt>(A0);
933  bool SecondIsConst = isa<ConstantInt>(A1);
934  // If both are const, then we don't need such a comparison.
935  if (FirstIsConst && SecondIsConst) continue;
936  // If only one is const, then make it the first callback argument.
937  if (FirstIsConst || SecondIsConst) {
938  CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
939  if (SecondIsConst)
940  std::swap(A0, A1);
941  }
942 
943  auto Ty = Type::getIntNTy(*C, TypeSize);
944  IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
945  IRB.CreateIntCast(A1, Ty, true)});
946  }
947  }
948 }
949 
950 void SanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
951  size_t Idx, bool IsLeafFunc) {
953  bool IsEntryBB = &BB == &F.getEntryBlock();
954  DebugLoc EntryLoc;
955  if (IsEntryBB) {
956  if (auto SP = F.getSubprogram())
957  EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
958  // Keep static allocas and llvm.localescape calls in the entry block. Even
959  // if we aren't splitting the block, it's nice for allocas to be before
960  // calls.
961  IP = PrepareToSplitEntryBlock(BB, IP);
962  } else {
963  EntryLoc = IP->getDebugLoc();
964  }
965 
966  IRBuilder<> IRB(&*IP);
967  IRB.SetCurrentDebugLocation(EntryLoc);
968  if (Options.TracePC) {
969  IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
970  IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
971  }
972  if (Options.TracePCGuard) {
973  auto GuardPtr = IRB.CreateIntToPtr(
974  IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
975  ConstantInt::get(IntptrTy, Idx * 4)),
976  Int32PtrTy);
977  IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
978  IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
979  }
980  if (Options.Inline8bitCounters) {
981  auto CounterPtr = IRB.CreateGEP(
982  Function8bitCounterArray->getValueType(), Function8bitCounterArray,
983  {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
984  auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
985  auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
986  auto Store = IRB.CreateStore(Inc, CounterPtr);
987  SetNoSanitizeMetadata(Load);
988  SetNoSanitizeMetadata(Store);
989  }
990  if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
991  // Check stack depth. If it's the deepest so far, record it.
992  Module *M = F.getParent();
993  Function *GetFrameAddr = Intrinsic::getDeclaration(
994  M, Intrinsic::frameaddress,
996  auto FrameAddrPtr =
997  IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
998  auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
999  auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
1000  auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
1001  auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
1002  IRBuilder<> ThenIRB(ThenTerm);
1003  auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
1004  SetNoSanitizeMetadata(LowestStack);
1005  SetNoSanitizeMetadata(Store);
1006  }
1007 }
1008 
1009 std::string
1010 SanitizerCoverage::getSectionName(const std::string &Section) const {
1011  if (TargetTriple.isOSBinFormatCOFF()) {
1012  if (Section == SanCovCountersSectionName)
1013  return ".SCOV$CM";
1014  if (Section == SanCovPCsSectionName)
1015  return ".SCOVP$M";
1016  return ".SCOV$GM"; // For SanCovGuardsSectionName.
1017  }
1018  if (TargetTriple.isOSBinFormatMachO())
1019  return "__DATA,__" + Section;
1020  return "__" + Section;
1021 }
1022 
1023 INITIALIZE_PASS(ModuleSanitizerCoverageLegacyPass, "module-sancov",
1024  "Pass for inserting sancov top-level initialization calls",
1025  false, false)
1026 
1028 INITIALIZE_PASS_BEGIN(SanitizerCoverageLegacyPass, "sancov",
1029  "Pass for instrumenting coverage on functions", false,
1030  false)
1031 INITIALIZE_PASS_DEPENDENCY(ModuleSanitizerCoverageLegacyPass)
1034 INITIALIZE_PASS_END(SanitizerCoverageLegacyPass, "sancov",
1035  "Pass for instrumenting coverage on functions", false,
1036  false)
1038  const SanitizerCoverageOptions &Options) {
1039  return new SanitizerCoverageLegacyPass(Options);
1040 }
1042  const SanitizerCoverageOptions &Options) {
1043  return new ModuleSanitizerCoverageLegacyPass(Options);
1044 }
IntegerType * getInt16Ty()
Fetch the type representing a 16-bit integer.
Definition: IRBuilder.h:378
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:242
static const char *const SanCovPCsSectionName
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:80
uint64_t CallInst * C
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue *> Values)
Adds global values to the llvm.compiler.used list.
INITIALIZE_PASS(ModuleSanitizerCoverageLegacyPass, "module-sancov", "Pass for inserting sancov top-level initialization calls", false, false) char SanitizerCoverageLegacyPass Pass for instrumenting coverage on functions
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
uint64_t getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
Definition: DataLayout.h:453
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:240
bool empty() const
Definition: Function.h:686
static const uint64_t SanCtorAndDtorPriority
DILocation * get() const
Get the underlying DILocation.
Definition: DebugLoc.cpp:21
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
static const char *const SanCovModuleCtor8bitCountersName
bool supportsCOMDAT() const
Tests whether the target supports comdat.
Definition: Triple.h:734
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:776
This class represents lattice values for constants.
Definition: AllocatorList.h:23
static const char *const SanCovTraceConstCmp1
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2104
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve &#39;CreateLoad(Ty, Ptr, "...")&#39; correctly, instead of converting the string to &#39;bool...
Definition: IRBuilder.h:1576
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:53
static const char *const SanCovPCsInitName
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:165
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:256
Available for inspection, not emission.
Definition: GlobalValue.h:49
static bool isFullPostDominator(const BasicBlock *BB, const PostDominatorTree *PDT)
static const char *const SanCovGuardsSectionName
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:56
Externally visible function.
Definition: GlobalValue.h:48
bool isInterposable() const
Return true if this global&#39;s definition can be substituted with an arbitrary definition at link time...
Definition: GlobalValue.h:429
static cl::opt< bool > ClStackDepth("sanitizer-coverage-stack-depth", cl::desc("max stack depth tracing"), cl::Hidden, cl::init(false))
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
Definition: DataLayout.h:389
A debug info location.
Definition: DebugLoc.h:33
Metadata node.
Definition: Metadata.h:863
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:230
F(f)
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it&#39;s an indirect...
Definition: CallSite.h:111
unsigned SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
Loop over all of the edges in the CFG, breaking critical edges as they are found. ...
static const char *const SanCovTracePCName
Hexagon Common GEP
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:137
static const char *const SanCovTraceSwitchName
static const char *const SanCovTraceConstCmp2
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:1014
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:289
static const char *const SanCov8bitCountersInitName
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:383
unsigned getAllocaAddrSpace() const
Definition: DataLayout.h:270
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
Option class for critical edge splitting.
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition: IRBuilder.h:388
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:388
static const char *const SanCovTraceCmp2
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:244
ValTy * getCalledValue() const
Return the pointer to function that is being called.
Definition: CallSite.h:104
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:196
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:779
void setThreadLocalMode(ThreadLocalMode Val)
Definition: GlobalValue.h:254
static const char *const SanCovLowestStackName
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1118
static cl::opt< int > ClCoverageLevel("sanitizer-coverage-level", cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, " "3: all blocks and critical edges"), cl::Hidden, cl::init(0))
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Type * getVoidTy()
Fetch the type representing void.
Definition: IRBuilder.h:416
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:102
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1605
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1953
void emitError(unsigned LocCookie, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
static const char *const SanCovTraceGep
const Instruction * getFirstNonPHIOrDbgOrLifetime() const
Returns a pointer to the first instruction in this block that is not a PHINode, a debug intrinsic...
Definition: BasicBlock.cpp:203
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
void appendToUsed(Module &M, ArrayRef< GlobalValue *> Values)
Adds global values to the llvm.used list.
static cl::opt< bool > ClDIVTracing("sanitizer-coverage-trace-divs", cl::desc("Tracing of DIV instructions"), cl::Hidden, cl::init(false))
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:296
Class to represent array types.
Definition: DerivedTypes.h:403
void setComdat(Comdat *C)
Definition: GlobalObject.h:107
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
static cl::opt< bool > ClCMPTracing("sanitizer-coverage-trace-compares", cl::desc("Tracing of CMP and similar instructions"), cl::Hidden, cl::init(false))
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:732
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition: IRBuilder.h:156
LinkageTypes getLinkage() const
Definition: GlobalValue.h:460
static const char *const SanCovTracePCGuardName
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1043
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:156
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:105
FunctionPass * createSanitizerCoverageLegacyPassPass(const SanitizerCoverageOptions &Options=SanitizerCoverageOptions())
const BasicBlock & getEntryBlock() const
Definition: Function.h:664
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Definition: Instructions.h:875
static const char *const SanCovTracePCIndirName
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1165
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:432
Control flow instructions. These all have token chains.
Definition: ISDOpcodes.h:657
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:216
static const char *const SanCovTraceCmp1
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:233
ModulePass * createModuleSanitizerCoverageLegacyPassPass(const SanitizerCoverageOptions &Options=SanitizerCoverageOptions())
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
LLVM_NODISCARD AttributeList addParamAttribute(LLVMContext &C, unsigned ArgNo, Attribute::AttrKind Kind) const
Add an argument attribute to the list.
Definition: Attributes.h:413
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition: Triple.h:628
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:64
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1504
static cl::opt< bool > ClCreatePCTable("sanitizer-coverage-pc-table", cl::desc("create a static PC table"), cl::Hidden, cl::init(false))
static const char *const SanCovTraceDiv4
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1465
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:148
This is an important base class in LLVM.
Definition: Constant.h:41
unsigned getPointerSize(unsigned AS=0) const
Layout pointer size FIXME: The defaults need to be removed once all of the backends/clients are updat...
Definition: DataLayout.cpp:651
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:223
static const char *const SanCovTraceConstCmp8
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:112
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:285
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:160
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1172
This instruction compares its operands according to the predicate given to the constructor.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:296
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:115
static cl::opt< bool > ClPruneBlocks("sanitizer-coverage-prune-blocks", cl::desc("Reduce the number of instrumented blocks"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClTracePCGuard("sanitizer-coverage-trace-pc-guard", cl::desc("pc tracing with a guard"), cl::Hidden, cl::init(false))
INITIALIZE_PASS(ModuleSanitizerCoverageLegacyPass, "module-sancov", "Pass for inserting sancov top-level initialization calls", false, false) char SanitizerCoverageLegacyPass INITIALIZE_PASS_BEGIN(SanitizerCoverageLegacyPass, "sancov", "Pass for instrumenting coverage on functions", false, false) INITIALIZE_PASS_END(SanitizerCoverageLegacyPass
static const char *const SanCovTraceCmp4
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition: Triple.h:633
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:343
std::string getUniqueModuleId(Module *M)
Produce a unique identifier for this module by taking the MD5 sum of the names of the module&#39;s strong...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:205
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition: Module.cpp:482
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
static const char *const SanCovTraceCmp8
size_t size() const
Definition: SmallVector.h:52
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
Definition: IRBuilder.h:421
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1222
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:33
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1095
static const char *const SanCovModuleCtorTracePcGuardName
void initializeSanitizerCoverageLegacyPassPass(PassRegistry &)
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Definition: IRBuilder.h:1677
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Iterator for intrusive lists based on ilist_node.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
Definition: DerivedTypes.h:559
BlockVerifier::State From
iterator end()
Definition: BasicBlock.h:270
static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Definition: Type.cpp:129
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:2027
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:348
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:248
Analysis pass which computes a PostDominatorTree.
Module.h This file contains the declarations for the Module class.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
Definition: Instruction.h:63
static const char *const SanCovCountersSectionName
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition: Type.cpp:179
enum llvm::SanitizerCoverageOptions::Type CoverageType
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:653
void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
Definition: ModuleUtils.cpp:63
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:143
static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB, const DominatorTree *DT, const PostDominatorTree *PDT, const SanitizerCoverageOptions &Options)
BasicBlock::iterator PrepareToSplitEntryBlock(BasicBlock &BB, BasicBlock::iterator IP)
Instrumentation passes often insert conditional checks into entry blocks.
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:454
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:940
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:55
amdgpu Simplify well known AMD library false FunctionCallee Callee
Comdat * GetOrCreateFunctionComdat(Function &F, Triple &T, const std::string &ModuleId)
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition: IRBuilder.h:373
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1561
void initializeModuleSanitizerCoverageLegacyPassPass(PassRegistry &)
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
static cl::opt< bool > ClTracePC("sanitizer-coverage-trace-pc", cl::desc("Experimental pc tracing"), cl::Hidden, cl::init(false))
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2004
FunctionCallee declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type *> InitArgTypes)
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT, const SanitizerCoverageOptions &Options)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Constant * getOrInsertGlobal(StringRef Name, Type *Ty, function_ref< GlobalVariable *()> CreateGlobalCallback)
Look up the specified global in the module symbol table.
Definition: Module.cpp:204
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static cl::opt< bool > ClGEPTracing("sanitizer-coverage-trace-geps", cl::desc("Tracing of GEP instructions"), cl::Hidden, cl::init(false))
static const char *const SanCovTraceDiv8
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
static bool IsBackEdge(BasicBlock *From, BasicBlock *To, const DominatorTree *DT)
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:224
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:582
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
Rename collisions when linking (static functions).
Definition: GlobalValue.h:55
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2223
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition: InlineAsm.cpp:42
static cl::opt< bool > ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters", cl::desc("increments 8-bit counter for every edge"), cl::Hidden, cl::init(false))
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1948
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:231
Multiway switch.
unsigned getMDKindID(StringRef Name) const
Return a unique non-zero ID for the specified metadata kind.
Definition: Module.cpp:119
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
aarch64 promote const
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:114
static const char *const SanCovTracePCGuardInitName
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:575
LLVM Value Representation.
Definition: Value.h:73
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1384
INITIALIZE_PASS(ModuleSanitizerCoverageLegacyPass, "module-sancov", "Pass for inserting sancov top-level initialization calls", false, false) char SanitizerCoverageLegacyPass sancov
static const Function * getParent(const Value *V)
bool hasOneUse() const
Return true if there is exactly one user of this value.
Definition: Value.h:432
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:259
std::pair< Function *, FunctionCallee > createSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type *> InitArgTypes, ArrayRef< Value *> InitArgs, StringRef VersionCheckName=StringRef())
Creates sanitizer constructor function, and calls sanitizer&#39;s init function from it.
for(unsigned i=Desc.getNumOperands(), e=OldMI.getNumOperands();i !=e;++i)
static const char *const SanCovTraceConstCmp4
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:173
Instruction * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:143
IntegerType * Int32Ty
const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
Definition: BasicBlock.cpp:276