xref: /llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp (revision 9558456b5370e64560e76f6580b979fccadd4744)
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/Constant.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/DebugInfo.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/InlineAsm.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/MDBuilder.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/InitializePasses.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/SpecialCaseList.h"
38 #include "llvm/Support/VirtualFileSystem.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/Instrumentation.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include "llvm/Transforms/Utils/ModuleUtils.h"
43 
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "sancov"
47 
48 const char SanCovTracePCIndirName[] = "__sanitizer_cov_trace_pc_indir";
49 const char SanCovTracePCName[] = "__sanitizer_cov_trace_pc";
50 const char SanCovTraceCmp1[] = "__sanitizer_cov_trace_cmp1";
51 const char SanCovTraceCmp2[] = "__sanitizer_cov_trace_cmp2";
52 const char SanCovTraceCmp4[] = "__sanitizer_cov_trace_cmp4";
53 const char SanCovTraceCmp8[] = "__sanitizer_cov_trace_cmp8";
54 const char SanCovTraceConstCmp1[] = "__sanitizer_cov_trace_const_cmp1";
55 const char SanCovTraceConstCmp2[] = "__sanitizer_cov_trace_const_cmp2";
56 const char SanCovTraceConstCmp4[] = "__sanitizer_cov_trace_const_cmp4";
57 const char SanCovTraceConstCmp8[] = "__sanitizer_cov_trace_const_cmp8";
58 const char SanCovTraceDiv4[] = "__sanitizer_cov_trace_div4";
59 const char SanCovTraceDiv8[] = "__sanitizer_cov_trace_div8";
60 const char SanCovTraceGep[] = "__sanitizer_cov_trace_gep";
61 const char SanCovTraceSwitchName[] = "__sanitizer_cov_trace_switch";
62 const char SanCovModuleCtorTracePcGuardName[] =
63     "sancov.module_ctor_trace_pc_guard";
64 const char SanCovModuleCtor8bitCountersName[] =
65     "sancov.module_ctor_8bit_counters";
66 const char SanCovModuleCtorBoolFlagName[] = "sancov.module_ctor_bool_flag";
67 static const uint64_t SanCtorAndDtorPriority = 2;
68 
69 const char SanCovTracePCGuardName[] = "__sanitizer_cov_trace_pc_guard";
70 const char SanCovTracePCGuardInitName[] = "__sanitizer_cov_trace_pc_guard_init";
71 const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init";
72 const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init";
73 const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init";
74 
75 const char SanCovGuardsSectionName[] = "sancov_guards";
76 const char SanCovCountersSectionName[] = "sancov_cntrs";
77 const char SanCovBoolFlagSectionName[] = "sancov_bools";
78 const char SanCovPCsSectionName[] = "sancov_pcs";
79 
80 const char SanCovLowestStackName[] = "__sancov_lowest_stack";
81 
82 static cl::opt<int> ClCoverageLevel(
83     "sanitizer-coverage-level",
84     cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
85              "3: all blocks and critical edges"),
86     cl::Hidden, cl::init(0));
87 
88 static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
89                                cl::desc("Experimental pc tracing"), cl::Hidden,
90                                cl::init(false));
91 
92 static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
93                                     cl::desc("pc tracing with a guard"),
94                                     cl::Hidden, cl::init(false));
95 
96 // If true, we create a global variable that contains PCs of all instrumented
97 // BBs, put this global into a named section, and pass this section's bounds
98 // to __sanitizer_cov_pcs_init.
99 // This way the coverage instrumentation does not need to acquire the PCs
100 // at run-time. Works with trace-pc-guard, inline-8bit-counters, and
101 // inline-bool-flag.
102 static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
103                                      cl::desc("create a static PC table"),
104                                      cl::Hidden, cl::init(false));
105 
106 static cl::opt<bool>
107     ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
108                          cl::desc("increments 8-bit counter for every edge"),
109                          cl::Hidden, cl::init(false));
110 
111 static cl::opt<bool>
112     ClInlineBoolFlag("sanitizer-coverage-inline-bool-flag",
113                      cl::desc("sets a boolean flag for every edge"), cl::Hidden,
114                      cl::init(false));
115 
116 static cl::opt<bool>
117     ClCMPTracing("sanitizer-coverage-trace-compares",
118                  cl::desc("Tracing of CMP and similar instructions"),
119                  cl::Hidden, cl::init(false));
120 
121 static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
122                                   cl::desc("Tracing of DIV instructions"),
123                                   cl::Hidden, cl::init(false));
124 
125 static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
126                                   cl::desc("Tracing of GEP instructions"),
127                                   cl::Hidden, cl::init(false));
128 
129 static cl::opt<bool>
130     ClPruneBlocks("sanitizer-coverage-prune-blocks",
131                   cl::desc("Reduce the number of instrumented blocks"),
132                   cl::Hidden, cl::init(true));
133 
134 static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
135                                   cl::desc("max stack depth tracing"),
136                                   cl::Hidden, cl::init(false));
137 
138 namespace {
139 
140 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
141   SanitizerCoverageOptions Res;
142   switch (LegacyCoverageLevel) {
143   case 0:
144     Res.CoverageType = SanitizerCoverageOptions::SCK_None;
145     break;
146   case 1:
147     Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
148     break;
149   case 2:
150     Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
151     break;
152   case 3:
153     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
154     break;
155   case 4:
156     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
157     Res.IndirectCalls = true;
158     break;
159   }
160   return Res;
161 }
162 
163 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
164   // Sets CoverageType and IndirectCalls.
165   SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
166   Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
167   Options.IndirectCalls |= CLOpts.IndirectCalls;
168   Options.TraceCmp |= ClCMPTracing;
169   Options.TraceDiv |= ClDIVTracing;
170   Options.TraceGep |= ClGEPTracing;
171   Options.TracePC |= ClTracePC;
172   Options.TracePCGuard |= ClTracePCGuard;
173   Options.Inline8bitCounters |= ClInline8bitCounters;
174   Options.InlineBoolFlag |= ClInlineBoolFlag;
175   Options.PCTable |= ClCreatePCTable;
176   Options.NoPrune |= !ClPruneBlocks;
177   Options.StackDepth |= ClStackDepth;
178   if (!Options.TracePCGuard && !Options.TracePC &&
179       !Options.Inline8bitCounters && !Options.StackDepth &&
180       !Options.InlineBoolFlag)
181     Options.TracePCGuard = true; // TracePCGuard is default.
182   return Options;
183 }
184 
185 using DomTreeCallback = function_ref<const DominatorTree *(Function &F)>;
186 using PostDomTreeCallback =
187     function_ref<const PostDominatorTree *(Function &F)>;
188 
189 class ModuleSanitizerCoverage {
190 public:
191   ModuleSanitizerCoverage(
192       const SanitizerCoverageOptions &Options = SanitizerCoverageOptions(),
193       const SpecialCaseList *Allowlist = nullptr,
194       const SpecialCaseList *Blocklist = nullptr)
195       : Options(OverrideFromCL(Options)), Allowlist(Allowlist),
196         Blocklist(Blocklist) {}
197   bool instrumentModule(Module &M, DomTreeCallback DTCallback,
198                         PostDomTreeCallback PDTCallback);
199 
200 private:
201   void instrumentFunction(Function &F, DomTreeCallback DTCallback,
202                           PostDomTreeCallback PDTCallback);
203   void InjectCoverageForIndirectCalls(Function &F,
204                                       ArrayRef<Instruction *> IndirCalls);
205   void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
206   void InjectTraceForDiv(Function &F,
207                          ArrayRef<BinaryOperator *> DivTraceTargets);
208   void InjectTraceForGep(Function &F,
209                          ArrayRef<GetElementPtrInst *> GepTraceTargets);
210   void InjectTraceForSwitch(Function &F,
211                             ArrayRef<Instruction *> SwitchTraceTargets);
212   bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
213                       bool IsLeafFunc = true);
214   GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
215                                                     Function &F, Type *Ty,
216                                                     const char *Section);
217   GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
218   void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
219   void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
220                              bool IsLeafFunc = true);
221   Function *CreateInitCallsForSections(Module &M, const char *CtorName,
222                                        const char *InitFunctionName, Type *Ty,
223                                        const char *Section);
224   std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
225                                                 Type *Ty);
226 
227   void SetNoSanitizeMetadata(Instruction *I) {
228     I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
229                    MDNode::get(*C, None));
230   }
231 
232   std::string getSectionName(const std::string &Section) const;
233   std::string getSectionStart(const std::string &Section) const;
234   std::string getSectionEnd(const std::string &Section) const;
235   FunctionCallee SanCovTracePCIndir;
236   FunctionCallee SanCovTracePC, SanCovTracePCGuard;
237   FunctionCallee SanCovTraceCmpFunction[4];
238   FunctionCallee SanCovTraceConstCmpFunction[4];
239   FunctionCallee SanCovTraceDivFunction[2];
240   FunctionCallee SanCovTraceGepFunction;
241   FunctionCallee SanCovTraceSwitchFunction;
242   GlobalVariable *SanCovLowestStack;
243   Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
244       *Int16Ty, *Int8Ty, *Int8PtrTy, *Int1Ty, *Int1PtrTy;
245   Module *CurModule;
246   std::string CurModuleUniqueId;
247   Triple TargetTriple;
248   LLVMContext *C;
249   const DataLayout *DL;
250 
251   GlobalVariable *FunctionGuardArray;  // for trace-pc-guard.
252   GlobalVariable *Function8bitCounterArray;  // for inline-8bit-counters.
253   GlobalVariable *FunctionBoolArray;         // for inline-bool-flag.
254   GlobalVariable *FunctionPCsArray;  // for pc-table.
255   SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
256   SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
257 
258   SanitizerCoverageOptions Options;
259 
260   const SpecialCaseList *Allowlist;
261   const SpecialCaseList *Blocklist;
262 };
263 
264 class ModuleSanitizerCoverageLegacyPass : public ModulePass {
265 public:
266   ModuleSanitizerCoverageLegacyPass(
267       const SanitizerCoverageOptions &Options = SanitizerCoverageOptions(),
268       const std::vector<std::string> &AllowlistFiles =
269           std::vector<std::string>(),
270       const std::vector<std::string> &BlocklistFiles =
271           std::vector<std::string>())
272       : ModulePass(ID), Options(Options) {
273     if (AllowlistFiles.size() > 0)
274       Allowlist = SpecialCaseList::createOrDie(AllowlistFiles,
275                                                *vfs::getRealFileSystem());
276     if (BlocklistFiles.size() > 0)
277       Blocklist = SpecialCaseList::createOrDie(BlocklistFiles,
278                                                *vfs::getRealFileSystem());
279     initializeModuleSanitizerCoverageLegacyPassPass(
280         *PassRegistry::getPassRegistry());
281   }
282   bool runOnModule(Module &M) override {
283     ModuleSanitizerCoverage ModuleSancov(Options, Allowlist.get(),
284                                          Blocklist.get());
285     auto DTCallback = [this](Function &F) -> const DominatorTree * {
286       return &this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
287     };
288     auto PDTCallback = [this](Function &F) -> const PostDominatorTree * {
289       return &this->getAnalysis<PostDominatorTreeWrapperPass>(F)
290                   .getPostDomTree();
291     };
292     return ModuleSancov.instrumentModule(M, DTCallback, PDTCallback);
293   }
294 
295   static char ID; // Pass identification, replacement for typeid
296   StringRef getPassName() const override { return "ModuleSanitizerCoverage"; }
297 
298   void getAnalysisUsage(AnalysisUsage &AU) const override {
299     AU.addRequired<DominatorTreeWrapperPass>();
300     AU.addRequired<PostDominatorTreeWrapperPass>();
301   }
302 
303 private:
304   SanitizerCoverageOptions Options;
305 
306   std::unique_ptr<SpecialCaseList> Allowlist;
307   std::unique_ptr<SpecialCaseList> Blocklist;
308 };
309 
310 } // namespace
311 
312 PreservedAnalyses ModuleSanitizerCoveragePass::run(Module &M,
313                                                    ModuleAnalysisManager &MAM) {
314   ModuleSanitizerCoverage ModuleSancov(Options, Allowlist.get(),
315                                        Blocklist.get());
316   auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
317   auto DTCallback = [&FAM](Function &F) -> const DominatorTree * {
318     return &FAM.getResult<DominatorTreeAnalysis>(F);
319   };
320   auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree * {
321     return &FAM.getResult<PostDominatorTreeAnalysis>(F);
322   };
323   if (ModuleSancov.instrumentModule(M, DTCallback, PDTCallback))
324     return PreservedAnalyses::none();
325   return PreservedAnalyses::all();
326 }
327 
328 std::pair<Value *, Value *>
329 ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section,
330                                            Type *Ty) {
331   // Use ExternalWeak so that if all sections are discarded due to section
332   // garbage collection, the linker will not report undefined symbol errors.
333   GlobalVariable *SecStart = new GlobalVariable(
334       M, Ty->getPointerElementType(), false,
335       GlobalVariable::ExternalWeakLinkage, nullptr, getSectionStart(Section));
336   SecStart->setVisibility(GlobalValue::HiddenVisibility);
337   GlobalVariable *SecEnd = new GlobalVariable(
338       M, Ty->getPointerElementType(), false,
339       GlobalVariable::ExternalWeakLinkage, nullptr, getSectionEnd(Section));
340   SecEnd->setVisibility(GlobalValue::HiddenVisibility);
341   IRBuilder<> IRB(M.getContext());
342   if (!TargetTriple.isOSBinFormatCOFF())
343     return std::make_pair(SecStart, SecEnd);
344 
345   // Account for the fact that on windows-msvc __start_* symbols actually
346   // point to a uint64_t before the start of the array.
347   auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
348   auto GEP = IRB.CreateGEP(Int8Ty, SecStartI8Ptr,
349                            ConstantInt::get(IntptrTy, sizeof(uint64_t)));
350   return std::make_pair(IRB.CreatePointerCast(GEP, Ty), SecEnd);
351 }
352 
353 Function *ModuleSanitizerCoverage::CreateInitCallsForSections(
354     Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
355     const char *Section) {
356   auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
357   auto SecStart = SecStartEnd.first;
358   auto SecEnd = SecStartEnd.second;
359   Function *CtorFunc;
360   std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
361       M, CtorName, InitFunctionName, {Ty, Ty}, {SecStart, SecEnd});
362   assert(CtorFunc->getName() == CtorName);
363 
364   if (TargetTriple.supportsCOMDAT()) {
365     // Use comdat to dedup CtorFunc.
366     CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
367     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
368   } else {
369     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
370   }
371 
372   if (TargetTriple.isOSBinFormatCOFF()) {
373     // In COFF files, if the contructors are set as COMDAT (they are because
374     // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
375     // functions and data) is used, the constructors get stripped. To prevent
376     // this, give the constructors weak ODR linkage and ensure the linker knows
377     // to include the sancov constructor. This way the linker can deduplicate
378     // the constructors but always leave one copy.
379     CtorFunc->setLinkage(GlobalValue::WeakODRLinkage);
380     appendToUsed(M, CtorFunc);
381   }
382   return CtorFunc;
383 }
384 
385 bool ModuleSanitizerCoverage::instrumentModule(
386     Module &M, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) {
387   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
388     return false;
389   if (Allowlist &&
390       !Allowlist->inSection("coverage", "src", M.getSourceFileName()))
391     return false;
392   if (Blocklist &&
393       Blocklist->inSection("coverage", "src", M.getSourceFileName()))
394     return false;
395   C = &(M.getContext());
396   DL = &M.getDataLayout();
397   CurModule = &M;
398   CurModuleUniqueId = getUniqueModuleId(CurModule);
399   TargetTriple = Triple(M.getTargetTriple());
400   FunctionGuardArray = nullptr;
401   Function8bitCounterArray = nullptr;
402   FunctionBoolArray = nullptr;
403   FunctionPCsArray = nullptr;
404   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
405   IntptrPtrTy = PointerType::getUnqual(IntptrTy);
406   Type *VoidTy = Type::getVoidTy(*C);
407   IRBuilder<> IRB(*C);
408   Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
409   Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
410   Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
411   Int1PtrTy = PointerType::getUnqual(IRB.getInt1Ty());
412   Int64Ty = IRB.getInt64Ty();
413   Int32Ty = IRB.getInt32Ty();
414   Int16Ty = IRB.getInt16Ty();
415   Int8Ty = IRB.getInt8Ty();
416   Int1Ty = IRB.getInt1Ty();
417 
418   SanCovTracePCIndir =
419       M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
420   // Make sure smaller parameters are zero-extended to i64 if required by the
421   // target ABI.
422   AttributeList SanCovTraceCmpZeroExtAL;
423   SanCovTraceCmpZeroExtAL =
424       SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
425   SanCovTraceCmpZeroExtAL =
426       SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
427 
428   SanCovTraceCmpFunction[0] =
429       M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
430                             IRB.getInt8Ty(), IRB.getInt8Ty());
431   SanCovTraceCmpFunction[1] =
432       M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
433                             IRB.getInt16Ty(), IRB.getInt16Ty());
434   SanCovTraceCmpFunction[2] =
435       M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
436                             IRB.getInt32Ty(), IRB.getInt32Ty());
437   SanCovTraceCmpFunction[3] =
438       M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
439 
440   SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
441       SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
442   SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
443       SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
444   SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
445       SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
446   SanCovTraceConstCmpFunction[3] =
447       M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
448 
449   {
450     AttributeList AL;
451     AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
452     SanCovTraceDivFunction[0] =
453         M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
454   }
455   SanCovTraceDivFunction[1] =
456       M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
457   SanCovTraceGepFunction =
458       M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
459   SanCovTraceSwitchFunction =
460       M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy);
461 
462   Constant *SanCovLowestStackConstant =
463       M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
464   SanCovLowestStack = dyn_cast<GlobalVariable>(SanCovLowestStackConstant);
465   if (!SanCovLowestStack) {
466     C->emitError(StringRef("'") + SanCovLowestStackName +
467                  "' should not be declared by the user");
468     return true;
469   }
470   SanCovLowestStack->setThreadLocalMode(
471       GlobalValue::ThreadLocalMode::InitialExecTLSModel);
472   if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
473     SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
474 
475   SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
476   SanCovTracePCGuard =
477       M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy);
478 
479   for (auto &F : M)
480     instrumentFunction(F, DTCallback, PDTCallback);
481 
482   Function *Ctor = nullptr;
483 
484   if (FunctionGuardArray)
485     Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
486                                       SanCovTracePCGuardInitName, Int32PtrTy,
487                                       SanCovGuardsSectionName);
488   if (Function8bitCounterArray)
489     Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
490                                       SanCov8bitCountersInitName, Int8PtrTy,
491                                       SanCovCountersSectionName);
492   if (FunctionBoolArray) {
493     Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName,
494                                       SanCovBoolFlagInitName, Int1PtrTy,
495                                       SanCovBoolFlagSectionName);
496   }
497   if (Ctor && Options.PCTable) {
498     auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
499     FunctionCallee InitFunction = declareSanitizerInitFunction(
500         M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
501     IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
502     IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
503   }
504   appendToUsed(M, GlobalsToAppendToUsed);
505   appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
506   return true;
507 }
508 
509 // True if block has successors and it dominates all of them.
510 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
511   if (succ_empty(BB))
512     return false;
513 
514   return llvm::all_of(successors(BB), [&](const BasicBlock *SUCC) {
515     return DT->dominates(BB, SUCC);
516   });
517 }
518 
519 // True if block has predecessors and it postdominates all of them.
520 static bool isFullPostDominator(const BasicBlock *BB,
521                                 const PostDominatorTree *PDT) {
522   if (pred_empty(BB))
523     return false;
524 
525   return llvm::all_of(predecessors(BB), [&](const BasicBlock *PRED) {
526     return PDT->dominates(BB, PRED);
527   });
528 }
529 
530 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
531                                   const DominatorTree *DT,
532                                   const PostDominatorTree *PDT,
533                                   const SanitizerCoverageOptions &Options) {
534   // Don't insert coverage for blocks containing nothing but unreachable: we
535   // will never call __sanitizer_cov() for them, so counting them in
536   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
537   // percentage. Also, unreachable instructions frequently have no debug
538   // locations.
539   if (isa<UnreachableInst>(BB->getFirstNonPHIOrDbgOrLifetime()))
540     return false;
541 
542   // Don't insert coverage into blocks without a valid insertion point
543   // (catchswitch blocks).
544   if (BB->getFirstInsertionPt() == BB->end())
545     return false;
546 
547   if (Options.NoPrune || &F.getEntryBlock() == BB)
548     return true;
549 
550   if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
551       &F.getEntryBlock() != BB)
552     return false;
553 
554   // Do not instrument full dominators, or full post-dominators with multiple
555   // predecessors.
556   return !isFullDominator(BB, DT)
557     && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
558 }
559 
560 
561 // Returns true iff From->To is a backedge.
562 // A twist here is that we treat From->To as a backedge if
563 //   * To dominates From or
564 //   * To->UniqueSuccessor dominates From
565 static bool IsBackEdge(BasicBlock *From, BasicBlock *To,
566                        const DominatorTree *DT) {
567   if (DT->dominates(To, From))
568     return true;
569   if (auto Next = To->getUniqueSuccessor())
570     if (DT->dominates(Next, From))
571       return true;
572   return false;
573 }
574 
575 // Prunes uninteresting Cmp instrumentation:
576 //   * CMP instructions that feed into loop backedge branch.
577 //
578 // Note that Cmp pruning is controlled by the same flag as the
579 // BB pruning.
580 static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT,
581                              const SanitizerCoverageOptions &Options) {
582   if (!Options.NoPrune)
583     if (CMP->hasOneUse())
584       if (auto BR = dyn_cast<BranchInst>(CMP->user_back()))
585         for (BasicBlock *B : BR->successors())
586           if (IsBackEdge(BR->getParent(), B, DT))
587             return false;
588   return true;
589 }
590 
591 void ModuleSanitizerCoverage::instrumentFunction(
592     Function &F, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) {
593   if (F.empty())
594     return;
595   if (F.getName().find(".module_ctor") != std::string::npos)
596     return; // Should not instrument sanitizer init functions.
597   if (F.getName().startswith("__sanitizer_"))
598     return; // Don't instrument __sanitizer_* callbacks.
599   // Don't touch available_externally functions, their actual body is elewhere.
600   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
601     return;
602   // Don't instrument MSVC CRT configuration helpers. They may run before normal
603   // initialization.
604   if (F.getName() == "__local_stdio_printf_options" ||
605       F.getName() == "__local_stdio_scanf_options")
606     return;
607   if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
608     return;
609   // Don't instrument functions using SEH for now. Splitting basic blocks like
610   // we do for coverage breaks WinEHPrepare.
611   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
612   if (F.hasPersonalityFn() &&
613       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
614     return;
615   if (Allowlist && !Allowlist->inSection("coverage", "fun", F.getName()))
616     return;
617   if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName()))
618     return;
619   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
620     SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
621   SmallVector<Instruction *, 8> IndirCalls;
622   SmallVector<BasicBlock *, 16> BlocksToInstrument;
623   SmallVector<Instruction *, 8> CmpTraceTargets;
624   SmallVector<Instruction *, 8> SwitchTraceTargets;
625   SmallVector<BinaryOperator *, 8> DivTraceTargets;
626   SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
627 
628   const DominatorTree *DT = DTCallback(F);
629   const PostDominatorTree *PDT = PDTCallback(F);
630   bool IsLeafFunc = true;
631 
632   for (auto &BB : F) {
633     if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
634       BlocksToInstrument.push_back(&BB);
635     for (auto &Inst : BB) {
636       if (Options.IndirectCalls) {
637         CallBase *CB = dyn_cast<CallBase>(&Inst);
638         if (CB && !CB->getCalledFunction())
639           IndirCalls.push_back(&Inst);
640       }
641       if (Options.TraceCmp) {
642         if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
643           if (IsInterestingCmp(CMP, DT, Options))
644             CmpTraceTargets.push_back(&Inst);
645         if (isa<SwitchInst>(&Inst))
646           SwitchTraceTargets.push_back(&Inst);
647       }
648       if (Options.TraceDiv)
649         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
650           if (BO->getOpcode() == Instruction::SDiv ||
651               BO->getOpcode() == Instruction::UDiv)
652             DivTraceTargets.push_back(BO);
653       if (Options.TraceGep)
654         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
655           GepTraceTargets.push_back(GEP);
656       if (Options.StackDepth)
657         if (isa<InvokeInst>(Inst) ||
658             (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
659           IsLeafFunc = false;
660     }
661   }
662 
663   InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
664   InjectCoverageForIndirectCalls(F, IndirCalls);
665   InjectTraceForCmp(F, CmpTraceTargets);
666   InjectTraceForSwitch(F, SwitchTraceTargets);
667   InjectTraceForDiv(F, DivTraceTargets);
668   InjectTraceForGep(F, GepTraceTargets);
669 }
670 
671 GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection(
672     size_t NumElements, Function &F, Type *Ty, const char *Section) {
673   ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
674   auto Array = new GlobalVariable(
675       *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
676       Constant::getNullValue(ArrayTy), "__sancov_gen_");
677 
678   if (TargetTriple.supportsCOMDAT() &&
679       (TargetTriple.isOSBinFormatELF() || !F.isInterposable()))
680     if (auto Comdat = getOrCreateFunctionComdat(F, TargetTriple))
681       Array->setComdat(Comdat);
682   Array->setSection(getSectionName(Section));
683   Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedSize()));
684 
685   // sancov_pcs parallels the other metadata section(s). Optimizers (e.g.
686   // GlobalOpt/ConstantMerge) may not discard sancov_pcs and the other
687   // section(s) as a unit, so we conservatively retain all unconditionally in
688   // the compiler.
689   //
690   // With comdat (COFF/ELF), the linker can guarantee the associated sections
691   // will be retained or discarded as a unit, so llvm.compiler.used is
692   // sufficient. Otherwise, conservatively make all of them retained by the
693   // linker.
694   if (Array->hasComdat())
695     GlobalsToAppendToCompilerUsed.push_back(Array);
696   else
697     GlobalsToAppendToUsed.push_back(Array);
698 
699   return Array;
700 }
701 
702 GlobalVariable *
703 ModuleSanitizerCoverage::CreatePCArray(Function &F,
704                                        ArrayRef<BasicBlock *> AllBlocks) {
705   size_t N = AllBlocks.size();
706   assert(N);
707   SmallVector<Constant *, 32> PCs;
708   IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
709   for (size_t i = 0; i < N; i++) {
710     if (&F.getEntryBlock() == AllBlocks[i]) {
711       PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
712       PCs.push_back((Constant *)IRB.CreateIntToPtr(
713           ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
714     } else {
715       PCs.push_back((Constant *)IRB.CreatePointerCast(
716           BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
717       PCs.push_back((Constant *)IRB.CreateIntToPtr(
718           ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
719     }
720   }
721   auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
722                                                     SanCovPCsSectionName);
723   PCArray->setInitializer(
724       ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
725   PCArray->setConstant(true);
726 
727   return PCArray;
728 }
729 
730 void ModuleSanitizerCoverage::CreateFunctionLocalArrays(
731     Function &F, ArrayRef<BasicBlock *> AllBlocks) {
732   if (Options.TracePCGuard)
733     FunctionGuardArray = CreateFunctionLocalArrayInSection(
734         AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
735 
736   if (Options.Inline8bitCounters)
737     Function8bitCounterArray = CreateFunctionLocalArrayInSection(
738         AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
739   if (Options.InlineBoolFlag)
740     FunctionBoolArray = CreateFunctionLocalArrayInSection(
741         AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName);
742 
743   if (Options.PCTable)
744     FunctionPCsArray = CreatePCArray(F, AllBlocks);
745 }
746 
747 bool ModuleSanitizerCoverage::InjectCoverage(Function &F,
748                                              ArrayRef<BasicBlock *> AllBlocks,
749                                              bool IsLeafFunc) {
750   if (AllBlocks.empty()) return false;
751   CreateFunctionLocalArrays(F, AllBlocks);
752   for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
753     InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
754   return true;
755 }
756 
757 // On every indirect call we call a run-time function
758 // __sanitizer_cov_indir_call* with two parameters:
759 //   - callee address,
760 //   - global cache array that contains CacheSize pointers (zero-initialized).
761 //     The cache is used to speed up recording the caller-callee pairs.
762 // The address of the caller is passed implicitly via caller PC.
763 // CacheSize is encoded in the name of the run-time function.
764 void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls(
765     Function &F, ArrayRef<Instruction *> IndirCalls) {
766   if (IndirCalls.empty())
767     return;
768   assert(Options.TracePC || Options.TracePCGuard ||
769          Options.Inline8bitCounters || Options.InlineBoolFlag);
770   for (auto I : IndirCalls) {
771     IRBuilder<> IRB(I);
772     CallBase &CB = cast<CallBase>(*I);
773     Value *Callee = CB.getCalledOperand();
774     if (isa<InlineAsm>(Callee))
775       continue;
776     IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
777   }
778 }
779 
780 // For every switch statement we insert a call:
781 // __sanitizer_cov_trace_switch(CondValue,
782 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
783 
784 void ModuleSanitizerCoverage::InjectTraceForSwitch(
785     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
786   for (auto I : SwitchTraceTargets) {
787     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
788       IRBuilder<> IRB(I);
789       SmallVector<Constant *, 16> Initializers;
790       Value *Cond = SI->getCondition();
791       if (Cond->getType()->getScalarSizeInBits() >
792           Int64Ty->getScalarSizeInBits())
793         continue;
794       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
795       Initializers.push_back(
796           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
797       if (Cond->getType()->getScalarSizeInBits() <
798           Int64Ty->getScalarSizeInBits())
799         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
800       for (auto It : SI->cases()) {
801         Constant *C = It.getCaseValue();
802         if (C->getType()->getScalarSizeInBits() <
803             Int64Ty->getScalarSizeInBits())
804           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
805         Initializers.push_back(C);
806       }
807       llvm::sort(drop_begin(Initializers, 2),
808                  [](const Constant *A, const Constant *B) {
809                    return cast<ConstantInt>(A)->getLimitedValue() <
810                           cast<ConstantInt>(B)->getLimitedValue();
811                  });
812       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
813       GlobalVariable *GV = new GlobalVariable(
814           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
815           ConstantArray::get(ArrayOfInt64Ty, Initializers),
816           "__sancov_gen_cov_switch_values");
817       IRB.CreateCall(SanCovTraceSwitchFunction,
818                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
819     }
820   }
821 }
822 
823 void ModuleSanitizerCoverage::InjectTraceForDiv(
824     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
825   for (auto BO : DivTraceTargets) {
826     IRBuilder<> IRB(BO);
827     Value *A1 = BO->getOperand(1);
828     if (isa<ConstantInt>(A1)) continue;
829     if (!A1->getType()->isIntegerTy())
830       continue;
831     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
832     int CallbackIdx = TypeSize == 32 ? 0 :
833         TypeSize == 64 ? 1 : -1;
834     if (CallbackIdx < 0) continue;
835     auto Ty = Type::getIntNTy(*C, TypeSize);
836     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
837                    {IRB.CreateIntCast(A1, Ty, true)});
838   }
839 }
840 
841 void ModuleSanitizerCoverage::InjectTraceForGep(
842     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
843   for (auto GEP : GepTraceTargets) {
844     IRBuilder<> IRB(GEP);
845     for (Use &Idx : GEP->indices())
846       if (!isa<ConstantInt>(Idx) && Idx->getType()->isIntegerTy())
847         IRB.CreateCall(SanCovTraceGepFunction,
848                        {IRB.CreateIntCast(Idx, IntptrTy, true)});
849   }
850 }
851 
852 void ModuleSanitizerCoverage::InjectTraceForCmp(
853     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
854   for (auto I : CmpTraceTargets) {
855     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
856       IRBuilder<> IRB(ICMP);
857       Value *A0 = ICMP->getOperand(0);
858       Value *A1 = ICMP->getOperand(1);
859       if (!A0->getType()->isIntegerTy())
860         continue;
861       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
862       int CallbackIdx = TypeSize == 8 ? 0 :
863                         TypeSize == 16 ? 1 :
864                         TypeSize == 32 ? 2 :
865                         TypeSize == 64 ? 3 : -1;
866       if (CallbackIdx < 0) continue;
867       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
868       auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
869       bool FirstIsConst = isa<ConstantInt>(A0);
870       bool SecondIsConst = isa<ConstantInt>(A1);
871       // If both are const, then we don't need such a comparison.
872       if (FirstIsConst && SecondIsConst) continue;
873       // If only one is const, then make it the first callback argument.
874       if (FirstIsConst || SecondIsConst) {
875         CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
876         if (SecondIsConst)
877           std::swap(A0, A1);
878       }
879 
880       auto Ty = Type::getIntNTy(*C, TypeSize);
881       IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
882               IRB.CreateIntCast(A1, Ty, true)});
883     }
884   }
885 }
886 
887 void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
888                                                     size_t Idx,
889                                                     bool IsLeafFunc) {
890   BasicBlock::iterator IP = BB.getFirstInsertionPt();
891   bool IsEntryBB = &BB == &F.getEntryBlock();
892   DebugLoc EntryLoc;
893   if (IsEntryBB) {
894     if (auto SP = F.getSubprogram())
895       EntryLoc = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
896     // Keep static allocas and llvm.localescape calls in the entry block.  Even
897     // if we aren't splitting the block, it's nice for allocas to be before
898     // calls.
899     IP = PrepareToSplitEntryBlock(BB, IP);
900   } else {
901     EntryLoc = IP->getDebugLoc();
902   }
903 
904   IRBuilder<> IRB(&*IP);
905   IRB.SetCurrentDebugLocation(EntryLoc);
906   if (Options.TracePC) {
907     IRB.CreateCall(SanCovTracePC)
908         ->setCannotMerge(); // gets the PC using GET_CALLER_PC.
909   }
910   if (Options.TracePCGuard) {
911     auto GuardPtr = IRB.CreateIntToPtr(
912         IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
913                       ConstantInt::get(IntptrTy, Idx * 4)),
914         Int32PtrTy);
915     IRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge();
916   }
917   if (Options.Inline8bitCounters) {
918     auto CounterPtr = IRB.CreateGEP(
919         Function8bitCounterArray->getValueType(), Function8bitCounterArray,
920         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
921     auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
922     auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
923     auto Store = IRB.CreateStore(Inc, CounterPtr);
924     SetNoSanitizeMetadata(Load);
925     SetNoSanitizeMetadata(Store);
926   }
927   if (Options.InlineBoolFlag) {
928     auto FlagPtr = IRB.CreateGEP(
929         FunctionBoolArray->getValueType(), FunctionBoolArray,
930         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
931     auto Load = IRB.CreateLoad(Int1Ty, FlagPtr);
932     auto ThenTerm =
933         SplitBlockAndInsertIfThen(IRB.CreateIsNull(Load), &*IP, false);
934     IRBuilder<> ThenIRB(ThenTerm);
935     auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr);
936     SetNoSanitizeMetadata(Load);
937     SetNoSanitizeMetadata(Store);
938   }
939   if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
940     // Check stack depth.  If it's the deepest so far, record it.
941     Module *M = F.getParent();
942     Function *GetFrameAddr = Intrinsic::getDeclaration(
943         M, Intrinsic::frameaddress,
944         IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace()));
945     auto FrameAddrPtr =
946         IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
947     auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
948     auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
949     auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
950     auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
951     IRBuilder<> ThenIRB(ThenTerm);
952     auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
953     SetNoSanitizeMetadata(LowestStack);
954     SetNoSanitizeMetadata(Store);
955   }
956 }
957 
958 std::string
959 ModuleSanitizerCoverage::getSectionName(const std::string &Section) const {
960   if (TargetTriple.isOSBinFormatCOFF()) {
961     if (Section == SanCovCountersSectionName)
962       return ".SCOV$CM";
963     if (Section == SanCovBoolFlagSectionName)
964       return ".SCOV$BM";
965     if (Section == SanCovPCsSectionName)
966       return ".SCOVP$M";
967     return ".SCOV$GM"; // For SanCovGuardsSectionName.
968   }
969   if (TargetTriple.isOSBinFormatMachO())
970     return "__DATA,__" + Section;
971   return "__" + Section;
972 }
973 
974 std::string
975 ModuleSanitizerCoverage::getSectionStart(const std::string &Section) const {
976   if (TargetTriple.isOSBinFormatMachO())
977     return "\1section$start$__DATA$__" + Section;
978   return "__start___" + Section;
979 }
980 
981 std::string
982 ModuleSanitizerCoverage::getSectionEnd(const std::string &Section) const {
983   if (TargetTriple.isOSBinFormatMachO())
984     return "\1section$end$__DATA$__" + Section;
985   return "__stop___" + Section;
986 }
987 
988 char ModuleSanitizerCoverageLegacyPass::ID = 0;
989 INITIALIZE_PASS_BEGIN(ModuleSanitizerCoverageLegacyPass, "sancov",
990                       "Pass for instrumenting coverage on functions", false,
991                       false)
992 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
993 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
994 INITIALIZE_PASS_END(ModuleSanitizerCoverageLegacyPass, "sancov",
995                     "Pass for instrumenting coverage on functions", false,
996                     false)
997 ModulePass *llvm::createModuleSanitizerCoverageLegacyPassPass(
998     const SanitizerCoverageOptions &Options,
999     const std::vector<std::string> &AllowlistFiles,
1000     const std::vector<std::string> &BlocklistFiles) {
1001   return new ModuleSanitizerCoverageLegacyPass(Options, AllowlistFiles,
1002                                                BlocklistFiles);
1003 }
1004