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