xref: /llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp (revision 223573c8ba446f8c8efe27187fdcaee0ffdbc747)
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 
13 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/Analysis/EHPersonalities.h"
17 #include "llvm/Analysis/PostDominators.h"
18 #include "llvm/IR/CFG.h"
19 #include "llvm/IR/CallSite.h"
20 #include "llvm/IR/Constant.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DebugInfo.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/MDBuilder.h"
32 #include "llvm/IR/Mangler.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Transforms/Instrumentation.h"
39 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40 #include "llvm/Transforms/Utils/ModuleUtils.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "sancov"
45 
46 static const char *const SanCovTracePCIndirName =
47     "__sanitizer_cov_trace_pc_indir";
48 static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
49 static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
50 static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
51 static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
52 static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
53 static const char *const SanCovTraceConstCmp1 =
54     "__sanitizer_cov_trace_const_cmp1";
55 static const char *const SanCovTraceConstCmp2 =
56     "__sanitizer_cov_trace_const_cmp2";
57 static const char *const SanCovTraceConstCmp4 =
58     "__sanitizer_cov_trace_const_cmp4";
59 static const char *const SanCovTraceConstCmp8 =
60     "__sanitizer_cov_trace_const_cmp8";
61 static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
62 static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
63 static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
64 static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
65 static const char *const 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 
85 static cl::opt<int> ClCoverageLevel(
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) {
138   SanitizerCoverageOptions Res;
139   switch (LegacyCoverageLevel) {
140   case 0:
141     Res.CoverageType = SanitizerCoverageOptions::SCK_None;
142     break;
143   case 1:
144     Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
145     break;
146   case 2:
147     Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
148     break;
149   case 3:
150     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
151     break;
152   case 4:
153     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
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;
170   Options.Inline8bitCounters |= ClInline8bitCounters;
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.
188   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
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() &&
201       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
202     return false;
203   return true;
204 }
205 
206 /// This is a class for instrumenting the module to add calls to initializing
207 /// the trace PC guards and 8bit counter globals. This should only be done
208 /// though if there is at least one function that can be instrumented with
209 /// Sancov.
210 class ModuleSanitizerCoverage {
211 public:
212   ModuleSanitizerCoverage(const SanitizerCoverageOptions &Options)
213       : Options(OverrideFromCL(Options)) {}
214 
215   bool instrumentModule(Module &M) {
216     if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
217       return false;
218 
219     Function *Ctor = nullptr;
220     LLVMContext *C = &(M.getContext());
221     const DataLayout *DL = &M.getDataLayout();
222     TargetTriple = Triple(M.getTargetTriple());
223     IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
224     Type *IntptrPtrTy = PointerType::getUnqual(IntptrTy);
225     IRBuilder<> IRB(*C);
226     Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
227     Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
228     Int8Ty = IRB.getInt8Ty();
229 
230     // Check that the __sancov_lowest_stack marker does not already exist.
231     Constant *SanCovLowestStackConstant =
232         M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
233     GlobalVariable *SanCovLowestStack =
234         dyn_cast<GlobalVariable>(SanCovLowestStackConstant);
235     if (!SanCovLowestStack) {
236       C->emitError(StringRef("'") + SanCovLowestStackName +
237                    "' should not be declared by the user");
238       return true;
239     }
240 
241     // We want to emit guard init calls if the module contains a function that
242     // we can instrument with SanitizerCoverage. We ignore any functions that
243     // were inserted by SanitizerCoverage and get the result from the analysis
244     // that checks for a valid function that the analysis may have run over.
245     if (!llvm::any_of(
246             M, [](const Function &F) { return canInstrumentWithSancov(F); }))
247       return false;
248 
249     // Emit the init calls.
250     if (Options.TracePCGuard)
251       Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
252                                         SanCovTracePCGuardInitName, Int32PtrTy,
253                                         SanCovGuardsSectionName);
254     if (Options.Inline8bitCounters)
255       Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
256                                         SanCov8bitCountersInitName, Int8PtrTy,
257                                         SanCovCountersSectionName);
258     if (Ctor && Options.PCTable) {
259       auto SecStartEnd =
260           CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
261       FunctionCallee InitFunction = declareSanitizerInitFunction(
262           M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
263       IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
264       IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
265     }
266     return Ctor;
267   }
268 
269 private:
270   Function *CreateInitCallsForSections(Module &M, const char *CtorName,
271                                        const char *InitFunctionName, Type *Ty,
272                                        const char *Section);
273   std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
274                                                 Type *Ty);
275   std::string getSectionStart(const std::string &Section) const {
276     if (TargetTriple.isOSBinFormatMachO())
277       return "\1section$start$__DATA$__" + Section;
278     return "__start___" + Section;
279   }
280   std::string getSectionEnd(const std::string &Section) const {
281     if (TargetTriple.isOSBinFormatMachO())
282       return "\1section$end$__DATA$__" + Section;
283     return "__stop___" + Section;
284   }
285 
286   SanitizerCoverageOptions Options;
287   Triple TargetTriple;
288   Type *IntptrTy, *Int8PtrTy, *Int8Ty;
289 };
290 
291 class ModuleSanitizerCoverageLegacyPass : public ModulePass {
292 public:
293   static char ID;
294 
295   ModuleSanitizerCoverageLegacyPass(
296       SanitizerCoverageOptions Options = SanitizerCoverageOptions())
297       : ModulePass(ID), Options(Options) {
298     initializeModuleSanitizerCoverageLegacyPassPass(
299         *PassRegistry::getPassRegistry());
300   }
301 
302   bool runOnModule(Module &M) override {
303     ModuleSanitizerCoverage ModuleSancov(Options);
304     return ModuleSancov.instrumentModule(M);
305   };
306 
307   StringRef getPassName() const override {
308     return "ModuleSanitizerCoverageLegacyPass";
309   }
310 
311 private:
312   SanitizerCoverageOptions Options;
313 };
314 
315 char ModuleSanitizerCoverageLegacyPass::ID = 0;
316 
317 class SanitizerCoverage {
318 public:
319   SanitizerCoverage(Function &F, const SanitizerCoverageOptions &Options)
320       : CurModule(F.getParent()), Options(OverrideFromCL(Options)) {
321     initializeModule(*F.getParent());
322   }
323 
324   ~SanitizerCoverage() { finalizeModule(*CurModule); }
325 
326   bool instrumentFunction(Function &F, const DominatorTree *DT,
327                           const PostDominatorTree *PDT);
328 
329 private:
330   void initializeModule(Module &M);
331   void finalizeModule(Module &M);
332   void InjectCoverageForIndirectCalls(Function &F,
333                                       ArrayRef<Instruction *> IndirCalls);
334   void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
335   void InjectTraceForDiv(Function &F,
336                          ArrayRef<BinaryOperator *> DivTraceTargets);
337   void InjectTraceForGep(Function &F,
338                          ArrayRef<GetElementPtrInst *> GepTraceTargets);
339   void InjectTraceForSwitch(Function &F,
340                             ArrayRef<Instruction *> SwitchTraceTargets);
341   bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
342                       bool IsLeafFunc = true);
343   GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
344                                                     Function &F, Type *Ty,
345                                                     const char *Section);
346   GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
347   void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
348   void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
349                              bool IsLeafFunc = true);
350 
351   void SetNoSanitizeMetadata(Instruction *I) {
352     I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
353                    MDNode::get(*C, None));
354   }
355 
356   std::string getSectionName(const std::string &Section) const;
357   FunctionCallee SanCovTracePCIndir;
358   FunctionCallee SanCovTracePC, SanCovTracePCGuard;
359   FunctionCallee SanCovTraceCmpFunction[4];
360   FunctionCallee SanCovTraceConstCmpFunction[4];
361   FunctionCallee SanCovTraceDivFunction[2];
362   FunctionCallee SanCovTraceGepFunction;
363   FunctionCallee SanCovTraceSwitchFunction;
364   GlobalVariable *SanCovLowestStack;
365   InlineAsm *EmptyAsm;
366   Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
367       *Int16Ty, *Int8Ty, *Int8PtrTy;
368   Module *CurModule;
369   std::string CurModuleUniqueId;
370   Triple TargetTriple;
371   LLVMContext *C;
372   const DataLayout *DL;
373 
374   GlobalVariable *FunctionGuardArray;  // for trace-pc-guard.
375   GlobalVariable *Function8bitCounterArray;  // for inline-8bit-counters.
376   GlobalVariable *FunctionPCsArray;  // for pc-table.
377   SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
378   SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
379 
380   SanitizerCoverageOptions Options;
381 };
382 
383 class SanitizerCoverageLegacyPass : public FunctionPass {
384 public:
385   static char ID; // Pass identification, replacement for typeid
386 
387   SanitizerCoverageLegacyPass(
388       SanitizerCoverageOptions Options = SanitizerCoverageOptions())
389       : FunctionPass(ID), Options(Options) {
390     initializeSanitizerCoverageLegacyPassPass(*PassRegistry::getPassRegistry());
391   }
392 
393   bool runOnFunction(Function &F) override {
394     const DominatorTree *DT =
395         &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
396     const PostDominatorTree *PDT =
397         &getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
398     SanitizerCoverage Sancov(F, Options);
399     return Sancov.instrumentFunction(F, DT, PDT);
400   }
401 
402   StringRef getPassName() const override {
403     return "SanitizerCoverageLegacyPass";
404   }
405 
406   void getAnalysisUsage(AnalysisUsage &AU) const override {
407     // Make the module sancov pass required by this pass so that it runs when
408     // -sancov is passed.
409     AU.addRequired<ModuleSanitizerCoverageLegacyPass>();
410     AU.addRequired<DominatorTreeWrapperPass>();
411     AU.addRequired<PostDominatorTreeWrapperPass>();
412   }
413 
414 private:
415   SanitizerCoverageOptions Options;
416 };
417 
418 } // namespace
419 
420 PreservedAnalyses SanitizerCoveragePass::run(Function &F,
421                                              FunctionAnalysisManager &AM) {
422   const DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(F);
423   const PostDominatorTree *PDT = &AM.getResult<PostDominatorTreeAnalysis>(F);
424   SanitizerCoverage Sancov(F, Options);
425   if (Sancov.instrumentFunction(F, DT, PDT))
426     return PreservedAnalyses::none();
427   return PreservedAnalyses::all();
428 }
429 
430 PreservedAnalyses ModuleSanitizerCoveragePass::run(Module &M,
431                                                    ModuleAnalysisManager &AM) {
432   ModuleSanitizerCoverage ModuleSancov(Options);
433   if (ModuleSancov.instrumentModule(M))
434     return PreservedAnalyses::none();
435   return PreservedAnalyses::all();
436 }
437 
438 std::pair<Value *, Value *>
439 ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section,
440                                            Type *Ty) {
441   GlobalVariable *SecStart =
442       new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
443                          getSectionStart(Section));
444   SecStart->setVisibility(GlobalValue::HiddenVisibility);
445   GlobalVariable *SecEnd =
446       new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
447                          nullptr, getSectionEnd(Section));
448   SecEnd->setVisibility(GlobalValue::HiddenVisibility);
449 
450   IRBuilder<> IRB(M.getContext());
451   Value *SecEndPtr = IRB.CreatePointerCast(SecEnd, Ty);
452   if (!TargetTriple.isOSBinFormatCOFF())
453     return std::make_pair(IRB.CreatePointerCast(SecStart, Ty), SecEndPtr);
454 
455   // Account for the fact that on windows-msvc __start_* symbols actually
456   // point to a uint64_t before the start of the array.
457   auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
458   auto GEP = IRB.CreateGEP(Int8Ty, SecStartI8Ptr,
459                            ConstantInt::get(IntptrTy, sizeof(uint64_t)));
460   return std::make_pair(IRB.CreatePointerCast(GEP, Ty), SecEndPtr);
461 }
462 
463 Function *ModuleSanitizerCoverage::CreateInitCallsForSections(
464     Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
465     const char *Section) {
466   auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
467   auto SecStart = SecStartEnd.first;
468   auto SecEnd = SecStartEnd.second;
469   Function *CtorFunc;
470   std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
471       M, CtorName, InitFunctionName, {Ty, Ty}, {SecStart, SecEnd});
472   assert(CtorFunc->getName() == CtorName);
473 
474   if (TargetTriple.supportsCOMDAT()) {
475     // Use comdat to dedup CtorFunc.
476     CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
477     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
478   } else {
479     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
480   }
481 
482   if (TargetTriple.isOSBinFormatCOFF()) {
483     // In COFF files, if the contructors are set as COMDAT (they are because
484     // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
485     // functions and data) is used, the constructors get stripped. To prevent
486     // this, give the constructors weak ODR linkage and ensure the linker knows
487     // to include the sancov constructor. This way the linker can deduplicate
488     // the constructors but always leave one copy.
489     CtorFunc->setLinkage(GlobalValue::WeakODRLinkage);
490     appendToUsed(M, CtorFunc);
491   }
492   return CtorFunc;
493 }
494 
495 void SanitizerCoverage::initializeModule(Module &M) {
496   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
497     return;
498   C = &(M.getContext());
499   DL = &M.getDataLayout();
500   CurModuleUniqueId = getUniqueModuleId(CurModule);
501   TargetTriple = Triple(M.getTargetTriple());
502   FunctionGuardArray = nullptr;
503   Function8bitCounterArray = nullptr;
504   FunctionPCsArray = nullptr;
505   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
506   IntptrPtrTy = PointerType::getUnqual(IntptrTy);
507   Type *VoidTy = Type::getVoidTy(*C);
508   IRBuilder<> IRB(*C);
509   Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
510   Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
511   Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
512   Int64Ty = IRB.getInt64Ty();
513   Int32Ty = IRB.getInt32Ty();
514   Int16Ty = IRB.getInt16Ty();
515   Int8Ty = IRB.getInt8Ty();
516 
517   SanCovTracePCIndir =
518       M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
519   // Make sure smaller parameters are zero-extended to i64 as required by the
520   // x86_64 ABI.
521   AttributeList SanCovTraceCmpZeroExtAL;
522   if (TargetTriple.getArch() == Triple::x86_64) {
523     SanCovTraceCmpZeroExtAL =
524         SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
525     SanCovTraceCmpZeroExtAL =
526         SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
527   }
528 
529   SanCovTraceCmpFunction[0] =
530       M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
531                             IRB.getInt8Ty(), IRB.getInt8Ty());
532   SanCovTraceCmpFunction[1] =
533       M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
534                             IRB.getInt16Ty(), IRB.getInt16Ty());
535   SanCovTraceCmpFunction[2] =
536       M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
537                             IRB.getInt32Ty(), IRB.getInt32Ty());
538   SanCovTraceCmpFunction[3] =
539       M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
540 
541   SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
542       SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
543   SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
544       SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
545   SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
546       SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
547   SanCovTraceConstCmpFunction[3] =
548       M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
549 
550   {
551     AttributeList AL;
552     if (TargetTriple.getArch() == Triple::x86_64)
553       AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
554     SanCovTraceDivFunction[0] =
555         M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
556   }
557   SanCovTraceDivFunction[1] =
558       M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
559   SanCovTraceGepFunction =
560       M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
561   SanCovTraceSwitchFunction =
562       M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy);
563 
564   Constant *SanCovLowestStackConstant =
565       M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
566   SanCovLowestStack = dyn_cast<GlobalVariable>(SanCovLowestStackConstant);
567   SanCovLowestStack->setThreadLocalMode(
568       GlobalValue::ThreadLocalMode::InitialExecTLSModel);
569   if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
570     SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
571 
572   // We insert an empty inline asm after cov callbacks to avoid callback merge.
573   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
574                             StringRef(""), StringRef(""),
575                             /*hasSideEffects=*/true);
576 
577   SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
578   SanCovTracePCGuard =
579       M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy);
580 }
581 
582 void SanitizerCoverage::finalizeModule(Module &M) {
583   // We don't reference these arrays directly in any of our runtime functions,
584   // so we need to prevent them from being dead stripped.
585   if (TargetTriple.isOSBinFormatMachO())
586     appendToUsed(M, GlobalsToAppendToUsed);
587   appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
588 }
589 
590 // True if block has successors and it dominates all of them.
591 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
592   if (succ_begin(BB) == succ_end(BB))
593     return false;
594 
595   for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
596     if (!DT->dominates(BB, SUCC))
597       return false;
598   }
599 
600   return true;
601 }
602 
603 // True if block has predecessors and it postdominates all of them.
604 static bool isFullPostDominator(const BasicBlock *BB,
605                                 const PostDominatorTree *PDT) {
606   if (pred_begin(BB) == pred_end(BB))
607     return false;
608 
609   for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
610     if (!PDT->dominates(BB, PRED))
611       return false;
612   }
613 
614   return true;
615 }
616 
617 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
618                                   const DominatorTree *DT,
619                                   const PostDominatorTree *PDT,
620                                   const SanitizerCoverageOptions &Options) {
621   // Don't insert coverage for blocks containing nothing but unreachable: we
622   // will never call __sanitizer_cov() for them, so counting them in
623   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
624   // percentage. Also, unreachable instructions frequently have no debug
625   // locations.
626   if (isa<UnreachableInst>(BB->getFirstNonPHIOrDbgOrLifetime()))
627     return false;
628 
629   // Don't insert coverage into blocks without a valid insertion point
630   // (catchswitch blocks).
631   if (BB->getFirstInsertionPt() == BB->end())
632     return false;
633 
634   if (Options.NoPrune || &F.getEntryBlock() == BB)
635     return true;
636 
637   if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
638       &F.getEntryBlock() != BB)
639     return false;
640 
641   // Do not instrument full dominators, or full post-dominators with multiple
642   // predecessors.
643   return !isFullDominator(BB, DT)
644     && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
645 }
646 
647 
648 // Returns true iff From->To is a backedge.
649 // A twist here is that we treat From->To as a backedge if
650 //   * To dominates From or
651 //   * To->UniqueSuccessor dominates From
652 static bool IsBackEdge(BasicBlock *From, BasicBlock *To,
653                        const DominatorTree *DT) {
654   if (DT->dominates(To, From))
655     return true;
656   if (auto Next = To->getUniqueSuccessor())
657     if (DT->dominates(Next, From))
658       return true;
659   return false;
660 }
661 
662 // Prunes uninteresting Cmp instrumentation:
663 //   * CMP instructions that feed into loop backedge branch.
664 //
665 // Note that Cmp pruning is controlled by the same flag as the
666 // BB pruning.
667 static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT,
668                              const SanitizerCoverageOptions &Options) {
669   if (!Options.NoPrune)
670     if (CMP->hasOneUse())
671       if (auto BR = dyn_cast<BranchInst>(CMP->user_back()))
672         for (BasicBlock *B : BR->successors())
673           if (IsBackEdge(BR->getParent(), B, DT))
674             return false;
675   return true;
676 }
677 
678 bool SanitizerCoverage::instrumentFunction(Function &F, const DominatorTree *DT,
679                                            const PostDominatorTree *PDT) {
680   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
681     return false;
682   if (!canInstrumentWithSancov(F))
683     return false;
684   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
685     SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
686   SmallVector<Instruction *, 8> IndirCalls;
687   SmallVector<BasicBlock *, 16> BlocksToInstrument;
688   SmallVector<Instruction *, 8> CmpTraceTargets;
689   SmallVector<Instruction *, 8> SwitchTraceTargets;
690   SmallVector<BinaryOperator *, 8> DivTraceTargets;
691   SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
692 
693   bool IsLeafFunc = true;
694 
695   for (auto &BB : F) {
696     if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
697       BlocksToInstrument.push_back(&BB);
698     for (auto &Inst : BB) {
699       if (Options.IndirectCalls) {
700         CallSite CS(&Inst);
701         if (CS && !CS.getCalledFunction())
702           IndirCalls.push_back(&Inst);
703       }
704       if (Options.TraceCmp) {
705         if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
706           if (IsInterestingCmp(CMP, DT, Options))
707             CmpTraceTargets.push_back(&Inst);
708         if (isa<SwitchInst>(&Inst))
709           SwitchTraceTargets.push_back(&Inst);
710       }
711       if (Options.TraceDiv)
712         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
713           if (BO->getOpcode() == Instruction::SDiv ||
714               BO->getOpcode() == Instruction::UDiv)
715             DivTraceTargets.push_back(BO);
716       if (Options.TraceGep)
717         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
718           GepTraceTargets.push_back(GEP);
719       if (Options.StackDepth)
720         if (isa<InvokeInst>(Inst) ||
721             (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
722           IsLeafFunc = false;
723     }
724   }
725 
726   InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
727   InjectCoverageForIndirectCalls(F, IndirCalls);
728   InjectTraceForCmp(F, CmpTraceTargets);
729   InjectTraceForSwitch(F, SwitchTraceTargets);
730   InjectTraceForDiv(F, DivTraceTargets);
731   InjectTraceForGep(F, GepTraceTargets);
732   return true;
733 }
734 
735 GlobalVariable *SanitizerCoverage::CreateFunctionLocalArrayInSection(
736     size_t NumElements, Function &F, Type *Ty, const char *Section) {
737   ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
738   auto Array = new GlobalVariable(
739       *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
740       Constant::getNullValue(ArrayTy), "__sancov_gen_");
741 
742   if (TargetTriple.supportsCOMDAT() && !F.isInterposable())
743     if (auto Comdat =
744             GetOrCreateFunctionComdat(F, TargetTriple, CurModuleUniqueId))
745       Array->setComdat(Comdat);
746   Array->setSection(getSectionName(Section));
747   Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
748                                         : Ty->getPrimitiveSizeInBits() / 8);
749   GlobalsToAppendToUsed.push_back(Array);
750   GlobalsToAppendToCompilerUsed.push_back(Array);
751   MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F));
752   Array->addMetadata(LLVMContext::MD_associated, *MD);
753 
754   return Array;
755 }
756 
757 GlobalVariable *
758 SanitizerCoverage::CreatePCArray(Function &F,
759                                  ArrayRef<BasicBlock *> AllBlocks) {
760   size_t N = AllBlocks.size();
761   assert(N);
762   SmallVector<Constant *, 32> PCs;
763   IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
764   for (size_t i = 0; i < N; i++) {
765     if (&F.getEntryBlock() == AllBlocks[i]) {
766       PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
767       PCs.push_back((Constant *)IRB.CreateIntToPtr(
768           ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
769     } else {
770       PCs.push_back((Constant *)IRB.CreatePointerCast(
771           BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
772       PCs.push_back((Constant *)IRB.CreateIntToPtr(
773           ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
774     }
775   }
776   auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
777                                                     SanCovPCsSectionName);
778   PCArray->setInitializer(
779       ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
780   PCArray->setConstant(true);
781 
782   return PCArray;
783 }
784 
785 void SanitizerCoverage::CreateFunctionLocalArrays(
786     Function &F, ArrayRef<BasicBlock *> AllBlocks) {
787   if (Options.TracePCGuard)
788     FunctionGuardArray = CreateFunctionLocalArrayInSection(
789         AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
790 
791   if (Options.Inline8bitCounters)
792     Function8bitCounterArray = CreateFunctionLocalArrayInSection(
793         AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
794 
795   if (Options.PCTable)
796     FunctionPCsArray = CreatePCArray(F, AllBlocks);
797 }
798 
799 bool SanitizerCoverage::InjectCoverage(Function &F,
800                                        ArrayRef<BasicBlock *> AllBlocks,
801                                        bool IsLeafFunc) {
802   if (AllBlocks.empty()) return false;
803   CreateFunctionLocalArrays(F, AllBlocks);
804   for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
805     InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
806   return true;
807 }
808 
809 // On every indirect call we call a run-time function
810 // __sanitizer_cov_indir_call* with two parameters:
811 //   - callee address,
812 //   - global cache array that contains CacheSize pointers (zero-initialized).
813 //     The cache is used to speed up recording the caller-callee pairs.
814 // The address of the caller is passed implicitly via caller PC.
815 // CacheSize is encoded in the name of the run-time function.
816 void SanitizerCoverage::InjectCoverageForIndirectCalls(
817     Function &F, ArrayRef<Instruction *> IndirCalls) {
818   if (IndirCalls.empty())
819     return;
820   assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
821   for (auto I : IndirCalls) {
822     IRBuilder<> IRB(I);
823     CallSite CS(I);
824     Value *Callee = CS.getCalledValue();
825     if (isa<InlineAsm>(Callee))
826       continue;
827     IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
828   }
829 }
830 
831 // For every switch statement we insert a call:
832 // __sanitizer_cov_trace_switch(CondValue,
833 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
834 
835 void SanitizerCoverage::InjectTraceForSwitch(
836     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
837   for (auto I : SwitchTraceTargets) {
838     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
839       IRBuilder<> IRB(I);
840       SmallVector<Constant *, 16> Initializers;
841       Value *Cond = SI->getCondition();
842       if (Cond->getType()->getScalarSizeInBits() >
843           Int64Ty->getScalarSizeInBits())
844         continue;
845       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
846       Initializers.push_back(
847           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
848       if (Cond->getType()->getScalarSizeInBits() <
849           Int64Ty->getScalarSizeInBits())
850         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
851       for (auto It : SI->cases()) {
852         Constant *C = It.getCaseValue();
853         if (C->getType()->getScalarSizeInBits() <
854             Int64Ty->getScalarSizeInBits())
855           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
856         Initializers.push_back(C);
857       }
858       llvm::sort(Initializers.begin() + 2, Initializers.end(),
859                  [](const Constant *A, const Constant *B) {
860                    return cast<ConstantInt>(A)->getLimitedValue() <
861                           cast<ConstantInt>(B)->getLimitedValue();
862                  });
863       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
864       GlobalVariable *GV = new GlobalVariable(
865           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
866           ConstantArray::get(ArrayOfInt64Ty, Initializers),
867           "__sancov_gen_cov_switch_values");
868       IRB.CreateCall(SanCovTraceSwitchFunction,
869                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
870     }
871   }
872 }
873 
874 void SanitizerCoverage::InjectTraceForDiv(
875     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
876   for (auto BO : DivTraceTargets) {
877     IRBuilder<> IRB(BO);
878     Value *A1 = BO->getOperand(1);
879     if (isa<ConstantInt>(A1)) continue;
880     if (!A1->getType()->isIntegerTy())
881       continue;
882     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
883     int CallbackIdx = TypeSize == 32 ? 0 :
884         TypeSize == 64 ? 1 : -1;
885     if (CallbackIdx < 0) continue;
886     auto Ty = Type::getIntNTy(*C, TypeSize);
887     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
888                    {IRB.CreateIntCast(A1, Ty, true)});
889   }
890 }
891 
892 void SanitizerCoverage::InjectTraceForGep(
893     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
894   for (auto GEP : GepTraceTargets) {
895     IRBuilder<> IRB(GEP);
896     for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
897       if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
898         IRB.CreateCall(SanCovTraceGepFunction,
899                        {IRB.CreateIntCast(*I, IntptrTy, true)});
900   }
901 }
902 
903 void SanitizerCoverage::InjectTraceForCmp(
904     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
905   for (auto I : CmpTraceTargets) {
906     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
907       IRBuilder<> IRB(ICMP);
908       Value *A0 = ICMP->getOperand(0);
909       Value *A1 = ICMP->getOperand(1);
910       if (!A0->getType()->isIntegerTy())
911         continue;
912       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
913       int CallbackIdx = TypeSize == 8 ? 0 :
914                         TypeSize == 16 ? 1 :
915                         TypeSize == 32 ? 2 :
916                         TypeSize == 64 ? 3 : -1;
917       if (CallbackIdx < 0) continue;
918       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
919       auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
920       bool FirstIsConst = isa<ConstantInt>(A0);
921       bool SecondIsConst = isa<ConstantInt>(A1);
922       // If both are const, then we don't need such a comparison.
923       if (FirstIsConst && SecondIsConst) continue;
924       // If only one is const, then make it the first callback argument.
925       if (FirstIsConst || SecondIsConst) {
926         CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
927         if (SecondIsConst)
928           std::swap(A0, A1);
929       }
930 
931       auto Ty = Type::getIntNTy(*C, TypeSize);
932       IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
933               IRB.CreateIntCast(A1, Ty, true)});
934     }
935   }
936 }
937 
938 void SanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
939                                               size_t Idx, bool IsLeafFunc) {
940   BasicBlock::iterator IP = BB.getFirstInsertionPt();
941   bool IsEntryBB = &BB == &F.getEntryBlock();
942   DebugLoc EntryLoc;
943   if (IsEntryBB) {
944     if (auto SP = F.getSubprogram())
945       EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
946     // Keep static allocas and llvm.localescape calls in the entry block.  Even
947     // if we aren't splitting the block, it's nice for allocas to be before
948     // calls.
949     IP = PrepareToSplitEntryBlock(BB, IP);
950   } else {
951     EntryLoc = IP->getDebugLoc();
952   }
953 
954   IRBuilder<> IRB(&*IP);
955   IRB.SetCurrentDebugLocation(EntryLoc);
956   if (Options.TracePC) {
957     IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
958     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
959   }
960   if (Options.TracePCGuard) {
961     auto GuardPtr = IRB.CreateIntToPtr(
962         IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
963                       ConstantInt::get(IntptrTy, Idx * 4)),
964         Int32PtrTy);
965     IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
966     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
967   }
968   if (Options.Inline8bitCounters) {
969     auto CounterPtr = IRB.CreateGEP(
970         Function8bitCounterArray->getValueType(), Function8bitCounterArray,
971         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
972     auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
973     auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
974     auto Store = IRB.CreateStore(Inc, CounterPtr);
975     SetNoSanitizeMetadata(Load);
976     SetNoSanitizeMetadata(Store);
977   }
978   if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
979     // Check stack depth.  If it's the deepest so far, record it.
980     Function *GetFrameAddr =
981         Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
982     auto FrameAddrPtr =
983         IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
984     auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
985     auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
986     auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
987     auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
988     IRBuilder<> ThenIRB(ThenTerm);
989     auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
990     SetNoSanitizeMetadata(LowestStack);
991     SetNoSanitizeMetadata(Store);
992   }
993 }
994 
995 std::string
996 SanitizerCoverage::getSectionName(const std::string &Section) const {
997   if (TargetTriple.isOSBinFormatCOFF()) {
998     if (Section == SanCovCountersSectionName)
999       return ".SCOV$CM";
1000     if (Section == SanCovPCsSectionName)
1001       return ".SCOVP$M";
1002     return ".SCOV$GM"; // For SanCovGuardsSectionName.
1003   }
1004   if (TargetTriple.isOSBinFormatMachO())
1005     return "__DATA,__" + Section;
1006   return "__" + Section;
1007 }
1008 
1009 INITIALIZE_PASS(ModuleSanitizerCoverageLegacyPass, "module-sancov",
1010                 "Pass for inserting sancov top-level initialization calls",
1011                 false, false)
1012 
1013 char SanitizerCoverageLegacyPass::ID = 0;
1014 INITIALIZE_PASS_BEGIN(SanitizerCoverageLegacyPass, "sancov",
1015                       "Pass for instrumenting coverage on functions", false,
1016                       false)
1017 INITIALIZE_PASS_DEPENDENCY(ModuleSanitizerCoverageLegacyPass)
1018 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1019 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
1020 INITIALIZE_PASS_END(SanitizerCoverageLegacyPass, "sancov",
1021                     "Pass for instrumenting coverage on functions", false,
1022                     false)
1023 FunctionPass *llvm::createSanitizerCoverageLegacyPassPass(
1024     const SanitizerCoverageOptions &Options) {
1025   return new SanitizerCoverageLegacyPass(Options);
1026 }
1027 ModulePass *llvm::createModuleSanitizerCoverageLegacyPassPass(
1028     const SanitizerCoverageOptions &Options) {
1029   return new ModuleSanitizerCoverageLegacyPass(Options);
1030 }
1031