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