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 
181 using PostDomTreeCallback =
183 
184 class ModuleSanitizerCoverage {
185 public:
186  ModuleSanitizerCoverage(
188  : Options(OverrideFromCL(Options)) {}
189  bool instrumentModule(Module &M, DomTreeCallback DTCallback,
190  PostDomTreeCallback PDTCallback);
191 
192 private:
193  void instrumentFunction(Function &F, DomTreeCallback DTCallback,
194  PostDomTreeCallback PDTCallback);
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  GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
210  void CreateFunctionLocalArrays(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 *CtorName,
214  const char *InitFunctionName, Type *Ty,
215  const char *Section);
216  std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
217  Type *Ty);
218 
219  void SetNoSanitizeMetadata(Instruction *I) {
220  I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
221  MDNode::get(*C, None));
222  }
223 
224  std::string getSectionName(const std::string &Section) const;
225  std::string getSectionStart(const std::string &Section) const;
226  std::string getSectionEnd(const std::string &Section) const;
227  FunctionCallee SanCovTracePCIndir;
228  FunctionCallee SanCovTracePC, SanCovTracePCGuard;
229  FunctionCallee SanCovTraceCmpFunction[4];
230  FunctionCallee SanCovTraceConstCmpFunction[4];
231  FunctionCallee SanCovTraceDivFunction[2];
232  FunctionCallee SanCovTraceGepFunction;
233  FunctionCallee SanCovTraceSwitchFunction;
234  GlobalVariable *SanCovLowestStack;
235  InlineAsm *EmptyAsm;
236  Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
237  *Int16Ty, *Int8Ty, *Int8PtrTy;
238  Module *CurModule;
239  std::string CurModuleUniqueId;
240  Triple TargetTriple;
241  LLVMContext *C;
242  const DataLayout *DL;
243 
244  GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
245  GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
246  GlobalVariable *FunctionPCsArray; // for pc-table.
247  SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
248  SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
249 
250  SanitizerCoverageOptions Options;
251 };
252 
253 class ModuleSanitizerCoverageLegacyPass : public ModulePass {
254 public:
255  ModuleSanitizerCoverageLegacyPass(
257  : ModulePass(ID), Options(Options) {
260  }
261  bool runOnModule(Module &M) override {
262  ModuleSanitizerCoverage ModuleSancov(Options);
263  auto DTCallback = [this](Function &F) -> const DominatorTree * {
264  return &this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
265  };
266  auto PDTCallback = [this](Function &F) -> const PostDominatorTree * {
267  return &this->getAnalysis<PostDominatorTreeWrapperPass>(F)
268  .getPostDomTree();
269  };
270  return ModuleSancov.instrumentModule(M, DTCallback, PDTCallback);
271  }
272 
273  static char ID; // Pass identification, replacement for typeid
274  StringRef getPassName() const override { return "ModuleSanitizerCoverage"; }
275 
276  void getAnalysisUsage(AnalysisUsage &AU) const override {
279  }
280 
281 private:
282  SanitizerCoverageOptions Options;
283 };
284 
285 } // namespace
286 
288  ModuleAnalysisManager &MAM) {
289  ModuleSanitizerCoverage ModuleSancov(Options);
290  auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
291  auto DTCallback = [&FAM](Function &F) -> const DominatorTree * {
292  return &FAM.getResult<DominatorTreeAnalysis>(F);
293  };
294  auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree * {
295  return &FAM.getResult<PostDominatorTreeAnalysis>(F);
296  };
297  if (ModuleSancov.instrumentModule(M, DTCallback, PDTCallback))
298  return PreservedAnalyses::none();
299  return PreservedAnalyses::all();
300 }
301 
302 std::pair<Value *, Value *>
303 ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section,
304  Type *Ty) {
305  GlobalVariable *SecStart =
306  new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
307  getSectionStart(Section));
309  GlobalVariable *SecEnd =
311  nullptr, getSectionEnd(Section));
313  IRBuilder<> IRB(M.getContext());
314  Value *SecEndPtr = IRB.CreatePointerCast(SecEnd, Ty);
315  if (!TargetTriple.isOSBinFormatCOFF())
316  return std::make_pair(IRB.CreatePointerCast(SecStart, Ty), SecEndPtr);
317 
318  // Account for the fact that on windows-msvc __start_* symbols actually
319  // point to a uint64_t before the start of the array.
320  auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
321  auto GEP = IRB.CreateGEP(Int8Ty, SecStartI8Ptr,
322  ConstantInt::get(IntptrTy, sizeof(uint64_t)));
323  return std::make_pair(IRB.CreatePointerCast(GEP, Ty), SecEndPtr);
324 }
325 
326 Function *ModuleSanitizerCoverage::CreateInitCallsForSections(
327  Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
328  const char *Section) {
329  auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
330  auto SecStart = SecStartEnd.first;
331  auto SecEnd = SecStartEnd.second;
332  Function *CtorFunc;
333  std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
334  M, CtorName, InitFunctionName, {Ty, Ty}, {SecStart, SecEnd});
335  assert(CtorFunc->getName() == CtorName);
336 
337  if (TargetTriple.supportsCOMDAT()) {
338  // Use comdat to dedup CtorFunc.
339  CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
340  appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
341  } else {
343  }
344 
345  if (TargetTriple.isOSBinFormatCOFF()) {
346  // In COFF files, if the contructors are set as COMDAT (they are because
347  // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
348  // functions and data) is used, the constructors get stripped. To prevent
349  // this, give the constructors weak ODR linkage and ensure the linker knows
350  // to include the sancov constructor. This way the linker can deduplicate
351  // the constructors but always leave one copy.
353  appendToUsed(M, CtorFunc);
354  }
355  return CtorFunc;
356 }
357 
358 bool ModuleSanitizerCoverage::instrumentModule(
359  Module &M, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) {
361  return false;
362  C = &(M.getContext());
363  DL = &M.getDataLayout();
364  CurModule = &M;
365  CurModuleUniqueId = getUniqueModuleId(CurModule);
366  TargetTriple = Triple(M.getTargetTriple());
367  FunctionGuardArray = nullptr;
368  Function8bitCounterArray = nullptr;
369  FunctionPCsArray = nullptr;
370  IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
371  IntptrPtrTy = PointerType::getUnqual(IntptrTy);
372  Type *VoidTy = Type::getVoidTy(*C);
373  IRBuilder<> IRB(*C);
374  Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
375  Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
376  Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
377  Int64Ty = IRB.getInt64Ty();
378  Int32Ty = IRB.getInt32Ty();
379  Int16Ty = IRB.getInt16Ty();
380  Int8Ty = IRB.getInt8Ty();
381 
382  SanCovTracePCIndir =
383  M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
384  // Make sure smaller parameters are zero-extended to i64 as required by the
385  // x86_64 ABI.
386  AttributeList SanCovTraceCmpZeroExtAL;
387  if (TargetTriple.getArch() == Triple::x86_64) {
388  SanCovTraceCmpZeroExtAL =
389  SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
390  SanCovTraceCmpZeroExtAL =
391  SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
392  }
393 
394  SanCovTraceCmpFunction[0] =
395  M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
396  IRB.getInt8Ty(), IRB.getInt8Ty());
397  SanCovTraceCmpFunction[1] =
398  M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
399  IRB.getInt16Ty(), IRB.getInt16Ty());
400  SanCovTraceCmpFunction[2] =
401  M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
402  IRB.getInt32Ty(), IRB.getInt32Ty());
403  SanCovTraceCmpFunction[3] =
404  M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
405 
406  SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
407  SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
408  SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
409  SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
410  SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
411  SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
412  SanCovTraceConstCmpFunction[3] =
413  M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
414 
415  {
417  if (TargetTriple.getArch() == Triple::x86_64)
418  AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
419  SanCovTraceDivFunction[0] =
420  M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
421  }
422  SanCovTraceDivFunction[1] =
423  M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
424  SanCovTraceGepFunction =
425  M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
426  SanCovTraceSwitchFunction =
427  M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy);
428 
429  Constant *SanCovLowestStackConstant =
430  M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
431  SanCovLowestStack = dyn_cast<GlobalVariable>(SanCovLowestStackConstant);
432  if (!SanCovLowestStack) {
433  C->emitError(StringRef("'") + SanCovLowestStackName +
434  "' should not be declared by the user");
435  return true;
436  }
437  SanCovLowestStack->setThreadLocalMode(
438  GlobalValue::ThreadLocalMode::InitialExecTLSModel);
439  if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
440  SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
441 
442  // We insert an empty inline asm after cov callbacks to avoid callback merge.
443  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
444  StringRef(""), StringRef(""),
445  /*hasSideEffects=*/true);
446 
447  SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
448  SanCovTracePCGuard =
449  M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy);
450 
451  for (auto &F : M)
452  instrumentFunction(F, DTCallback, PDTCallback);
453 
454  Function *Ctor = nullptr;
455 
456  if (FunctionGuardArray)
457  Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
458  SanCovTracePCGuardInitName, Int32PtrTy,
459  SanCovGuardsSectionName);
460  if (Function8bitCounterArray)
461  Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
462  SanCov8bitCountersInitName, Int8PtrTy,
463  SanCovCountersSectionName);
464  if (Ctor && Options.PCTable) {
465  auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
467  M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
468  IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
469  IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
470  }
471  // We don't reference these arrays directly in any of our runtime functions,
472  // so we need to prevent them from being dead stripped.
473  if (TargetTriple.isOSBinFormatMachO())
474  appendToUsed(M, GlobalsToAppendToUsed);
475  appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
476  return true;
477 }
478 
479 // True if block has successors and it dominates all of them.
480 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
481  if (succ_begin(BB) == succ_end(BB))
482  return false;
483 
484  for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
485  if (!DT->dominates(BB, SUCC))
486  return false;
487  }
488 
489  return true;
490 }
491 
492 // True if block has predecessors and it postdominates all of them.
493 static bool isFullPostDominator(const BasicBlock *BB,
494  const PostDominatorTree *PDT) {
495  if (pred_begin(BB) == pred_end(BB))
496  return false;
497 
498  for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
499  if (!PDT->dominates(BB, PRED))
500  return false;
501  }
502 
503  return true;
504 }
505 
506 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
507  const DominatorTree *DT,
508  const PostDominatorTree *PDT,
509  const SanitizerCoverageOptions &Options) {
510  // Don't insert coverage for blocks containing nothing but unreachable: we
511  // will never call __sanitizer_cov() for them, so counting them in
512  // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
513  // percentage. Also, unreachable instructions frequently have no debug
514  // locations.
515  if (isa<UnreachableInst>(BB->getFirstNonPHIOrDbgOrLifetime()))
516  return false;
517 
518  // Don't insert coverage into blocks without a valid insertion point
519  // (catchswitch blocks).
520  if (BB->getFirstInsertionPt() == BB->end())
521  return false;
522 
523  if (Options.NoPrune || &F.getEntryBlock() == BB)
524  return true;
525 
527  &F.getEntryBlock() != BB)
528  return false;
529 
530  // Do not instrument full dominators, or full post-dominators with multiple
531  // predecessors.
532  return !isFullDominator(BB, DT)
533  && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
534 }
535 
536 
537 // Returns true iff From->To is a backedge.
538 // A twist here is that we treat From->To as a backedge if
539 // * To dominates From or
540 // * To->UniqueSuccessor dominates From
542  const DominatorTree *DT) {
543  if (DT->dominates(To, From))
544  return true;
545  if (auto Next = To->getUniqueSuccessor())
546  if (DT->dominates(Next, From))
547  return true;
548  return false;
549 }
550 
551 // Prunes uninteresting Cmp instrumentation:
552 // * CMP instructions that feed into loop backedge branch.
553 //
554 // Note that Cmp pruning is controlled by the same flag as the
555 // BB pruning.
556 static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT,
557  const SanitizerCoverageOptions &Options) {
558  if (!Options.NoPrune)
559  if (CMP->hasOneUse())
560  if (auto BR = dyn_cast<BranchInst>(CMP->user_back()))
561  for (BasicBlock *B : BR->successors())
562  if (IsBackEdge(BR->getParent(), B, DT))
563  return false;
564  return true;
565 }
566 
567 void ModuleSanitizerCoverage::instrumentFunction(
568  Function &F, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) {
569  if (F.empty())
570  return;
571  if (F.getName().find(".module_ctor") != std::string::npos)
572  return; // Should not instrument sanitizer init functions.
573  if (F.getName().startswith("__sanitizer_"))
574  return; // Don't instrument __sanitizer_* callbacks.
575  // Don't touch available_externally functions, their actual body is elewhere.
577  return;
578  // Don't instrument MSVC CRT configuration helpers. They may run before normal
579  // initialization.
580  if (F.getName() == "__local_stdio_printf_options" ||
581  F.getName() == "__local_stdio_scanf_options")
582  return;
583  if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
584  return;
585  // Don't instrument functions using SEH for now. Splitting basic blocks like
586  // we do for coverage breaks WinEHPrepare.
587  // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
588  if (F.hasPersonalityFn() &&
590  return;
592  SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
594  SmallVector<BasicBlock *, 16> BlocksToInstrument;
595  SmallVector<Instruction *, 8> CmpTraceTargets;
596  SmallVector<Instruction *, 8> SwitchTraceTargets;
597  SmallVector<BinaryOperator *, 8> DivTraceTargets;
598  SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
599 
600  const DominatorTree *DT = DTCallback(F);
601  const PostDominatorTree *PDT = PDTCallback(F);
602  bool IsLeafFunc = true;
603 
604  for (auto &BB : F) {
605  if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
606  BlocksToInstrument.push_back(&BB);
607  for (auto &Inst : BB) {
608  if (Options.IndirectCalls) {
609  CallSite CS(&Inst);
610  if (CS && !CS.getCalledFunction())
611  IndirCalls.push_back(&Inst);
612  }
613  if (Options.TraceCmp) {
614  if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
615  if (IsInterestingCmp(CMP, DT, Options))
616  CmpTraceTargets.push_back(&Inst);
617  if (isa<SwitchInst>(&Inst))
618  SwitchTraceTargets.push_back(&Inst);
619  }
620  if (Options.TraceDiv)
621  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
622  if (BO->getOpcode() == Instruction::SDiv ||
623  BO->getOpcode() == Instruction::UDiv)
624  DivTraceTargets.push_back(BO);
625  if (Options.TraceGep)
626  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
627  GepTraceTargets.push_back(GEP);
628  if (Options.StackDepth)
629  if (isa<InvokeInst>(Inst) ||
630  (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
631  IsLeafFunc = false;
632  }
633  }
634 
635  InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
636  InjectCoverageForIndirectCalls(F, IndirCalls);
637  InjectTraceForCmp(F, CmpTraceTargets);
638  InjectTraceForSwitch(F, SwitchTraceTargets);
639  InjectTraceForDiv(F, DivTraceTargets);
640  InjectTraceForGep(F, GepTraceTargets);
641 }
642 
643 GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection(
644  size_t NumElements, Function &F, Type *Ty, const char *Section) {
645  ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
646  auto Array = new GlobalVariable(
647  *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
648  Constant::getNullValue(ArrayTy), "__sancov_gen_");
649 
650  if (TargetTriple.supportsCOMDAT() && !F.isInterposable())
651  if (auto Comdat =
652  GetOrCreateFunctionComdat(F, TargetTriple, CurModuleUniqueId))
653  Array->setComdat(Comdat);
654  Array->setSection(getSectionName(Section));
655  Array->setAlignment(Align(Ty->isPointerTy()
656  ? DL->getPointerSize()
657  : Ty->getPrimitiveSizeInBits() / 8));
658  GlobalsToAppendToUsed.push_back(Array);
659  GlobalsToAppendToCompilerUsed.push_back(Array);
661  Array->addMetadata(LLVMContext::MD_associated, *MD);
662 
663  return Array;
664 }
665 
667 ModuleSanitizerCoverage::CreatePCArray(Function &F,
668  ArrayRef<BasicBlock *> AllBlocks) {
669  size_t N = AllBlocks.size();
670  assert(N);
673  for (size_t i = 0; i < N; i++) {
674  if (&F.getEntryBlock() == AllBlocks[i]) {
675  PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
676  PCs.push_back((Constant *)IRB.CreateIntToPtr(
677  ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
678  } else {
679  PCs.push_back((Constant *)IRB.CreatePointerCast(
680  BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
681  PCs.push_back((Constant *)IRB.CreateIntToPtr(
682  ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
683  }
684  }
685  auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
686  SanCovPCsSectionName);
687  PCArray->setInitializer(
688  ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
689  PCArray->setConstant(true);
690 
691  return PCArray;
692 }
693 
694 void ModuleSanitizerCoverage::CreateFunctionLocalArrays(
695  Function &F, ArrayRef<BasicBlock *> AllBlocks) {
696  if (Options.TracePCGuard)
697  FunctionGuardArray = CreateFunctionLocalArrayInSection(
698  AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
699 
700  if (Options.Inline8bitCounters)
701  Function8bitCounterArray = CreateFunctionLocalArrayInSection(
702  AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
703 
704  if (Options.PCTable)
705  FunctionPCsArray = CreatePCArray(F, AllBlocks);
706 }
707 
708 bool ModuleSanitizerCoverage::InjectCoverage(Function &F,
709  ArrayRef<BasicBlock *> AllBlocks,
710  bool IsLeafFunc) {
711  if (AllBlocks.empty()) return false;
712  CreateFunctionLocalArrays(F, AllBlocks);
713  for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
714  InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
715  return true;
716 }
717 
718 // On every indirect call we call a run-time function
719 // __sanitizer_cov_indir_call* with two parameters:
720 // - callee address,
721 // - global cache array that contains CacheSize pointers (zero-initialized).
722 // The cache is used to speed up recording the caller-callee pairs.
723 // The address of the caller is passed implicitly via caller PC.
724 // CacheSize is encoded in the name of the run-time function.
725 void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls(
726  Function &F, ArrayRef<Instruction *> IndirCalls) {
727  if (IndirCalls.empty())
728  return;
729  assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
730  for (auto I : IndirCalls) {
731  IRBuilder<> IRB(I);
732  CallSite CS(I);
733  Value *Callee = CS.getCalledValue();
734  if (isa<InlineAsm>(Callee))
735  continue;
736  IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
737  }
738 }
739 
740 // For every switch statement we insert a call:
741 // __sanitizer_cov_trace_switch(CondValue,
742 // {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
743 
744 void ModuleSanitizerCoverage::InjectTraceForSwitch(
745  Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
746  for (auto I : SwitchTraceTargets) {
747  if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
748  IRBuilder<> IRB(I);
749  SmallVector<Constant *, 16> Initializers;
750  Value *Cond = SI->getCondition();
751  if (Cond->getType()->getScalarSizeInBits() >
752  Int64Ty->getScalarSizeInBits())
753  continue;
754  Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
755  Initializers.push_back(
756  ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
757  if (Cond->getType()->getScalarSizeInBits() <
758  Int64Ty->getScalarSizeInBits())
759  Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
760  for (auto It : SI->cases()) {
761  Constant *C = It.getCaseValue();
762  if (C->getType()->getScalarSizeInBits() <
763  Int64Ty->getScalarSizeInBits())
764  C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
765  Initializers.push_back(C);
766  }
767  llvm::sort(Initializers.begin() + 2, Initializers.end(),
768  [](const Constant *A, const Constant *B) {
769  return cast<ConstantInt>(A)->getLimitedValue() <
770  cast<ConstantInt>(B)->getLimitedValue();
771  });
772  ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
773  GlobalVariable *GV = new GlobalVariable(
774  *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
775  ConstantArray::get(ArrayOfInt64Ty, Initializers),
776  "__sancov_gen_cov_switch_values");
777  IRB.CreateCall(SanCovTraceSwitchFunction,
778  {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
779  }
780  }
781 }
782 
783 void ModuleSanitizerCoverage::InjectTraceForDiv(
784  Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
785  for (auto BO : DivTraceTargets) {
786  IRBuilder<> IRB(BO);
787  Value *A1 = BO->getOperand(1);
788  if (isa<ConstantInt>(A1)) continue;
789  if (!A1->getType()->isIntegerTy())
790  continue;
791  uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
792  int CallbackIdx = TypeSize == 32 ? 0 :
793  TypeSize == 64 ? 1 : -1;
794  if (CallbackIdx < 0) continue;
795  auto Ty = Type::getIntNTy(*C, TypeSize);
796  IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
797  {IRB.CreateIntCast(A1, Ty, true)});
798  }
799 }
800 
801 void ModuleSanitizerCoverage::InjectTraceForGep(
802  Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
803  for (auto GEP : GepTraceTargets) {
804  IRBuilder<> IRB(GEP);
805  for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
806  if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
807  IRB.CreateCall(SanCovTraceGepFunction,
808  {IRB.CreateIntCast(*I, IntptrTy, true)});
809  }
810 }
811 
812 void ModuleSanitizerCoverage::InjectTraceForCmp(
813  Function &, ArrayRef<Instruction *> CmpTraceTargets) {
814  for (auto I : CmpTraceTargets) {
815  if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
816  IRBuilder<> IRB(ICMP);
817  Value *A0 = ICMP->getOperand(0);
818  Value *A1 = ICMP->getOperand(1);
819  if (!A0->getType()->isIntegerTy())
820  continue;
821  uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
822  int CallbackIdx = TypeSize == 8 ? 0 :
823  TypeSize == 16 ? 1 :
824  TypeSize == 32 ? 2 :
825  TypeSize == 64 ? 3 : -1;
826  if (CallbackIdx < 0) continue;
827  // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
828  auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
829  bool FirstIsConst = isa<ConstantInt>(A0);
830  bool SecondIsConst = isa<ConstantInt>(A1);
831  // If both are const, then we don't need such a comparison.
832  if (FirstIsConst && SecondIsConst) continue;
833  // If only one is const, then make it the first callback argument.
834  if (FirstIsConst || SecondIsConst) {
835  CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
836  if (SecondIsConst)
837  std::swap(A0, A1);
838  }
839 
840  auto Ty = Type::getIntNTy(*C, TypeSize);
841  IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
842  IRB.CreateIntCast(A1, Ty, true)});
843  }
844  }
845 }
846 
847 void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
848  size_t Idx,
849  bool IsLeafFunc) {
851  bool IsEntryBB = &BB == &F.getEntryBlock();
852  DebugLoc EntryLoc;
853  if (IsEntryBB) {
854  if (auto SP = F.getSubprogram())
855  EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
856  // Keep static allocas and llvm.localescape calls in the entry block. Even
857  // if we aren't splitting the block, it's nice for allocas to be before
858  // calls.
859  IP = PrepareToSplitEntryBlock(BB, IP);
860  } else {
861  EntryLoc = IP->getDebugLoc();
862  }
863 
864  IRBuilder<> IRB(&*IP);
865  IRB.SetCurrentDebugLocation(EntryLoc);
866  if (Options.TracePC) {
867  IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
868  IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
869  }
870  if (Options.TracePCGuard) {
871  auto GuardPtr = IRB.CreateIntToPtr(
872  IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
873  ConstantInt::get(IntptrTy, Idx * 4)),
874  Int32PtrTy);
875  IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
876  IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
877  }
878  if (Options.Inline8bitCounters) {
879  auto CounterPtr = IRB.CreateGEP(
880  Function8bitCounterArray->getValueType(), Function8bitCounterArray,
881  {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
882  auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
883  auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
884  auto Store = IRB.CreateStore(Inc, CounterPtr);
885  SetNoSanitizeMetadata(Load);
886  SetNoSanitizeMetadata(Store);
887  }
888  if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
889  // Check stack depth. If it's the deepest so far, record it.
890  Module *M = F.getParent();
891  Function *GetFrameAddr = Intrinsic::getDeclaration(
892  M, Intrinsic::frameaddress,
894  auto FrameAddrPtr =
895  IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
896  auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
897  auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
898  auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
899  auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
900  IRBuilder<> ThenIRB(ThenTerm);
901  auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
902  SetNoSanitizeMetadata(LowestStack);
903  SetNoSanitizeMetadata(Store);
904  }
905 }
906 
907 std::string
908 ModuleSanitizerCoverage::getSectionName(const std::string &Section) const {
909  if (TargetTriple.isOSBinFormatCOFF()) {
910  if (Section == SanCovCountersSectionName)
911  return ".SCOV$CM";
912  if (Section == SanCovPCsSectionName)
913  return ".SCOVP$M";
914  return ".SCOV$GM"; // For SanCovGuardsSectionName.
915  }
916  if (TargetTriple.isOSBinFormatMachO())
917  return "__DATA,__" + Section;
918  return "__" + Section;
919 }
920 
921 std::string
922 ModuleSanitizerCoverage::getSectionStart(const std::string &Section) const {
923  if (TargetTriple.isOSBinFormatMachO())
924  return "\1section$start$__DATA$__" + Section;
925  return "__start___" + Section;
926 }
927 
928 std::string
929 ModuleSanitizerCoverage::getSectionEnd(const std::string &Section) const {
930  if (TargetTriple.isOSBinFormatMachO())
931  return "\1section$end$__DATA$__" + Section;
932  return "__stop___" + Section;
933 }
934 
936 INITIALIZE_PASS_BEGIN(ModuleSanitizerCoverageLegacyPass, "sancov",
937  "Pass for instrumenting coverage on functions", false,
938  false)
941 INITIALIZE_PASS_END(ModuleSanitizerCoverageLegacyPass, "sancov",
942  "Pass for instrumenting coverage on functions", false,
943  false)
945  const SanitizerCoverageOptions &Options) {
946  return new ModuleSanitizerCoverageLegacyPass(Options);
947 }
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.
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:241
bool empty() const
Definition: Function.h:691
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...
static const char *const SanCovModuleCtor8bitCountersName
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:777
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:2117
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:1575
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
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:170
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:270
Available for inspection, not emission.
Definition: GlobalValue.h:49
static bool isFullPostDominator(const BasicBlock *BB, const PostDominatorTree *PDT)
static const char *const SanCovGuardsSectionName
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:104
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))
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:144
static const char *const SanCovTraceSwitchName
INITIALIZE_PASS_BEGIN(ModuleSanitizerCoverageLegacyPass, "sancov", "Pass for instrumenting coverage on functions", false, false) INITIALIZE_PASS_END(ModuleSanitizerCoverageLegacyPass
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:273
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
static const char *const SanCovTraceCmp2
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:245
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:197
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:779
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:1604
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1958
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:210
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
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))
Class to represent array types.
Definition: DerivedTypes.h:408
void setComdat(Comdat *C)
Definition: GlobalObject.h:122
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:737
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:1093
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:157
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:105
const BasicBlock & getEntryBlock() const
Definition: Function.h:669
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Definition: Instructions.h:881
static const char *const SanCovTracePCIndirName
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1165
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:432
Control flow instructions. These all have token chains.
Definition: ISDOpcodes.h:665
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:154
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:223
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:240
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:115
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:46
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:1522
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
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:224
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:299
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:165
This instruction compares its operands according to the predicate given to the constructor.
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:301
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))
static const char *const SanCovTraceCmp4
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:160
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
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1095
static const char *const SanCovModuleCtorTracePcGuardName
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Definition: IRBuilder.h:1676
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:594
BlockVerifier::State From
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:390
iterator end()
Definition: BasicBlock.h:275
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:134
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:2032
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:184
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:2009
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)
ModulePass * createModuleSanitizerCoverageLegacyPassPass(const SanitizerCoverageOptions &Options=SanitizerCoverageOptions())
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
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:587
Pass for instrumenting coverage on functions
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:2239
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:1953
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
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:74
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1465
bool hasOneUse() const
Return true if there is exactly one user of this value.
Definition: Value.h:433
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
A container for analyses that lazily runs them and caches their results.
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
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
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:1045
const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
Definition: BasicBlock.cpp:283