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