LLVM 24.0.0git
SanitizerCoverage.cpp
Go to the documentation of this file.
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
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/ScopeExit.h"
20#include "llvm/IR/Constant.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Dominators.h"
25#include "llvm/IR/Function.h"
27#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/MDBuilder.h"
32#include "llvm/IR/Module.h"
33#include "llvm/IR/Type.h"
41
42using namespace llvm;
43
44#define DEBUG_TYPE "sancov"
45
46const char SanCovTracePCIndirName[] = "__sanitizer_cov_trace_pc_indir";
47const char SanCovTracePCName[] = "__sanitizer_cov_trace_pc";
48const char SanCovTracePCEntryName[] = "__sanitizer_cov_trace_pc_entry";
49const char SanCovTracePCExitName[] = "__sanitizer_cov_trace_pc_exit";
50const char SanCovTraceCmp1[] = "__sanitizer_cov_trace_cmp1";
51const char SanCovTraceCmp2[] = "__sanitizer_cov_trace_cmp2";
52const char SanCovTraceCmp4[] = "__sanitizer_cov_trace_cmp4";
53const char SanCovTraceCmp8[] = "__sanitizer_cov_trace_cmp8";
54const char SanCovTraceConstCmp1[] = "__sanitizer_cov_trace_const_cmp1";
55const char SanCovTraceConstCmp2[] = "__sanitizer_cov_trace_const_cmp2";
56const char SanCovTraceConstCmp4[] = "__sanitizer_cov_trace_const_cmp4";
57const char SanCovTraceConstCmp8[] = "__sanitizer_cov_trace_const_cmp8";
58const char SanCovLoad1[] = "__sanitizer_cov_load1";
59const char SanCovLoad2[] = "__sanitizer_cov_load2";
60const char SanCovLoad4[] = "__sanitizer_cov_load4";
61const char SanCovLoad8[] = "__sanitizer_cov_load8";
62const char SanCovLoad16[] = "__sanitizer_cov_load16";
63const char SanCovStore1[] = "__sanitizer_cov_store1";
64const char SanCovStore2[] = "__sanitizer_cov_store2";
65const char SanCovStore4[] = "__sanitizer_cov_store4";
66const char SanCovStore8[] = "__sanitizer_cov_store8";
67const char SanCovStore16[] = "__sanitizer_cov_store16";
68const char SanCovTraceDiv4[] = "__sanitizer_cov_trace_div4";
69const char SanCovTraceDiv8[] = "__sanitizer_cov_trace_div8";
70const char SanCovTraceGep[] = "__sanitizer_cov_trace_gep";
71const char SanCovTraceSwitchName[] = "__sanitizer_cov_trace_switch";
73 "sancov.module_ctor_trace_pc_guard";
75 "sancov.module_ctor_8bit_counters";
76const char SanCovModuleCtorBoolFlagName[] = "sancov.module_ctor_bool_flag";
78
79const char SanCovTracePCGuardName[] = "__sanitizer_cov_trace_pc_guard";
80const char SanCovTracePCGuardInitName[] = "__sanitizer_cov_trace_pc_guard_init";
81const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init";
82const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init";
83const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init";
84const char SanCovCFsInitName[] = "__sanitizer_cov_cfs_init";
85
86const char SanCovGuardsSectionName[] = "sancov_guards";
87const char SanCovCountersSectionName[] = "sancov_cntrs";
88const char SanCovBoolFlagSectionName[] = "sancov_bools";
89const char SanCovPCsSectionName[] = "sancov_pcs";
90const char SanCovCFsSectionName[] = "sancov_cfs";
91const char SanCovCallbackGateSectionName[] = "sancov_gate";
92
93const char SanCovStackDepthCallbackName[] = "__sanitizer_cov_stack_depth";
94const char SanCovLowestStackName[] = "__sancov_lowest_stack";
95const char SanCovCallbackGateName[] = "__sancov_should_track";
96
97namespace {
98
99SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
101 switch (LegacyCoverageLevel) {
102 case 0:
104 break;
105 case 1:
107 break;
108 case 2:
110 break;
111 case 3:
113 break;
114 case 4:
116 Res.IndirectCalls = true;
117 break;
118 }
119 return Res;
120}
121
122SanitizerCoverageOptions overrideFromCL(const InstrumentationOptions &Opts,
124 // Sets CoverageType and IndirectCalls.
125 SanitizerCoverageOptions CLOpts = getOptions(Opts.sanitizer_coverage_level);
126 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
127 Options.IndirectCalls |= CLOpts.IndirectCalls;
128 Options.TraceCmp |= Opts.sanitizer_coverage_trace_compares;
129 Options.TraceDiv |= Opts.sanitizer_coverage_trace_divs;
130 Options.TraceGep |= Opts.sanitizer_coverage_trace_geps;
131 Options.TracePC |= Opts.sanitizer_coverage_trace_pc;
132 Options.TracePCEntryExit |= Opts.sanitizer_coverage_trace_pc_entry_exit;
133 Options.TracePCGuard |= Opts.sanitizer_coverage_trace_pc_guard;
134 Options.Inline8bitCounters |= Opts.sanitizer_coverage_inline_8bit_counters;
135 Options.InlineBoolFlag |= Opts.sanitizer_coverage_inline_bool_flag;
136 Options.PCTable |= Opts.sanitizer_coverage_pc_table;
137 Options.NoPrune |= !Opts.sanitizer_coverage_prune_blocks;
138 Options.StackDepth |= Opts.sanitizer_coverage_stack_depth;
139 Options.StackDepthCallbackMin =
140 std::max(Options.StackDepthCallbackMin,
141 Opts.sanitizer_coverage_stack_depth_callback_min);
142 Options.TraceLoads |= Opts.sanitizer_coverage_trace_loads;
143 Options.TraceStores |= Opts.sanitizer_coverage_trace_stores;
144 Options.GatedCallbacks |= Opts.sanitizer_coverage_gated_trace_callbacks;
145 if (!Options.TracePCGuard && !Options.TracePC && !Options.TracePCEntryExit &&
146 !Options.Inline8bitCounters && !Options.StackDepth &&
147 !Options.InlineBoolFlag && !Options.TraceLoads && !Options.TraceStores)
148 Options.TracePCGuard = true; // TracePCGuard is default.
149 Options.CollectControlFlow |= Opts.sanitizer_coverage_control_flow;
150 return Options;
151}
152
153class ModuleSanitizerCoverage {
154public:
155 using DomTreeCallback = function_ref<const DominatorTree &(Function &F)>;
156 using PostDomTreeCallback =
158
159 ModuleSanitizerCoverage(const InstrumentationOptions &Opts, Module &M,
160 DomTreeCallback DTCallback,
161 PostDomTreeCallback PDTCallback,
163 const SpecialCaseList *Allowlist,
164 const SpecialCaseList *Blocklist)
165 : Opts(Opts), M(M), DTCallback(DTCallback), PDTCallback(PDTCallback),
166 Options(Options), Allowlist(Allowlist), Blocklist(Blocklist) {}
167
168 bool instrumentModule();
169
170private:
171 void createFunctionControlFlow(Function &F);
172 void instrumentFunction(Function &F);
173 void InjectCoverageForIndirectCalls(Function &F,
174 ArrayRef<Instruction *> IndirCalls);
175 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets,
176 Value *&FunctionGateCmp);
177 void InjectTraceForDiv(Function &F,
178 ArrayRef<BinaryOperator *> DivTraceTargets);
179 void InjectTraceForGep(Function &F,
180 ArrayRef<GetElementPtrInst *> GepTraceTargets);
181 void InjectTraceForLoadsAndStores(Function &F, ArrayRef<LoadInst *> Loads,
182 ArrayRef<StoreInst *> Stores);
183 void InjectTraceForExits(Function &F);
184 void InjectTraceForSwitch(Function &F,
185 ArrayRef<Instruction *> SwitchTraceTargets,
186 Value *&FunctionGateCmp);
187 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
188 Value *&FunctionGateCmp, bool IsLeafFunc);
189 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
190 Function &F, Type *Ty,
191 const char *Section);
192 void CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
193 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
194 Instruction *CreateGateBranch(Function &F, Value *&FunctionGateCmp,
195 Instruction *I);
196 Value *CreateFunctionLocalGateCmp(IRBuilder<> &IRB);
197 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
198 Value *&FunctionGateCmp, bool IsLeafFunc);
199 CallInst *createRuntimeCall(IRBuilder<> &IRB, FunctionCallee Callee,
200 ArrayRef<Value *> Args = {});
201 void addFuncletBundles(Function &F);
202 Function *CreateInitCallsForSections(Module &M, const char *CtorName,
203 const char *InitFunctionName, Type *Ty,
204 const char *Section);
205 std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
206 Type *Ty);
207
208 std::string getSectionName(const std::string &Section) const;
209 std::string getSectionStart(const std::string &Section) const;
210 std::string getSectionEnd(const std::string &Section) const;
211
212 const InstrumentationOptions &Opts;
213 Module &M;
214 DomTreeCallback DTCallback;
215 PostDomTreeCallback PDTCallback;
216
217 FunctionCallee SanCovStackDepthCallback;
218 FunctionCallee SanCovTracePCIndir;
219 FunctionCallee SanCovTracePC, SanCovTracePCGuard;
220 FunctionCallee SanCovTracePCEntry, SanCovTracePCExit;
221 std::array<FunctionCallee, 4> SanCovTraceCmpFunction;
222 std::array<FunctionCallee, 4> SanCovTraceConstCmpFunction;
223 std::array<FunctionCallee, 5> SanCovLoadFunction;
224 std::array<FunctionCallee, 5> SanCovStoreFunction;
225 std::array<FunctionCallee, 2> SanCovTraceDivFunction;
226 FunctionCallee SanCovTraceGepFunction;
227 FunctionCallee SanCovTraceSwitchFunction;
228 GlobalVariable *SanCovLowestStack;
229 GlobalVariable *SanCovCallbackGate;
230 Type *PtrTy, *IntptrTy, *Int64Ty, *Int32Ty, *Int16Ty, *Int8Ty, *Int1Ty;
231 Module *CurModule;
232 Triple TargetTriple;
233 LLVMContext *C;
234 const DataLayout *DL;
235
236 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
237 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
238 GlobalVariable *FunctionBoolArray; // for inline-bool-flag.
239 GlobalVariable *FunctionCFsArray; // for control flow table
240 // Runtime calls inserted into the current function, for
241 // addFuncletBundles().
242 SmallVector<CallInst *, 16> RuntimeCalls;
243 SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
244 SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
245
247
248 const SpecialCaseList *Allowlist;
249 const SpecialCaseList *Blocklist;
250};
251} // namespace
252
255 const std::vector<std::string> &AllowlistFiles,
256 const std::vector<std::string> &BlocklistFiles)
257 : Options(std::move(Options)),
258 VFS(VFS ? std::move(VFS) : vfs::getRealFileSystem()) {
259 if (AllowlistFiles.size() > 0)
260 Allowlist = SpecialCaseList::createOrDie(AllowlistFiles, *this->VFS);
261 if (BlocklistFiles.size() > 0)
262 Blocklist = SpecialCaseList::createOrDie(BlocklistFiles, *this->VFS);
263}
264
267 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
268 auto DTCallback = [&FAM](Function &F) -> const DominatorTree & {
269 return FAM.getResult<DominatorTreeAnalysis>(F);
270 };
271 auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree & {
272 return FAM.getResult<PostDominatorTreeAnalysis>(F);
273 };
274 const InstrumentationOptions &Opts = getInstrumentationOptions(M);
275 ModuleSanitizerCoverage ModuleSancov(Opts, M, DTCallback, PDTCallback,
276 overrideFromCL(Opts, Options),
277 Allowlist.get(), Blocklist.get());
278 if (!ModuleSancov.instrumentModule())
279 return PreservedAnalyses::all();
280
282 // GlobalsAA is considered stateless and does not get invalidated unless
283 // explicitly invalidated; PreservedAnalyses::none() is not enough. Sanitizers
284 // make changes that require GlobalsAA to be invalidated.
285 PA.abandon<GlobalsAA>();
286 return PA;
287}
288
289std::pair<Value *, Value *>
290ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section,
291 Type *Ty) {
292 // Use ExternalWeak so that if all sections are discarded due to section
293 // garbage collection, the linker will not report undefined symbol errors.
294 // Windows defines the start/stop symbols in compiler-rt so no need for
295 // ExternalWeak.
296 GlobalValue::LinkageTypes Linkage = TargetTriple.isOSBinFormatCOFF()
299 GlobalVariable *SecStart = new GlobalVariable(M, Ty, false, Linkage, nullptr,
300 getSectionStart(Section));
302 GlobalVariable *SecEnd = new GlobalVariable(M, Ty, false, Linkage, nullptr,
303 getSectionEnd(Section));
305 if (!TargetTriple.isOSBinFormatCOFF())
306 return std::make_pair(SecStart, SecEnd);
307
308 // Account for the fact that on windows-msvc __start_* symbols actually
309 // point to a uint64_t before the start of the array.
311 SecStart, ConstantInt::get(IntptrTy, sizeof(uint64_t)));
312 return std::make_pair(GEP, SecEnd);
313}
314
315Function *ModuleSanitizerCoverage::CreateInitCallsForSections(
316 Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
317 const char *Section) {
318 if (Opts.sanitizer_coverage_drop_ctors)
319 return nullptr;
320 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
321 auto SecStart = SecStartEnd.first;
322 auto SecEnd = SecStartEnd.second;
323 Function *CtorFunc;
324 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
325 M, CtorName, InitFunctionName, {PtrTy, PtrTy}, {SecStart, SecEnd});
326 assert(CtorFunc->getName() == CtorName);
327
328 if (TargetTriple.supportsCOMDAT()) {
329 // Use comdat to dedup CtorFunc.
330 CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
331 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
332 } else {
334 }
335
336 if (TargetTriple.isOSBinFormatCOFF()) {
337 // In COFF files, if the contructors are set as COMDAT (they are because
338 // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
339 // functions and data) is used, the constructors get stripped. To prevent
340 // this, give the constructors weak ODR linkage and ensure the linker knows
341 // to include the sancov constructor. This way the linker can deduplicate
342 // the constructors but always leave one copy.
344 }
345 return CtorFunc;
346}
347
348bool ModuleSanitizerCoverage::instrumentModule() {
350 return false;
351 if (Allowlist &&
352 !Allowlist->inSection("coverage", "src", M.getSourceFileName()))
353 return false;
354 if (Blocklist &&
355 Blocklist->inSection("coverage", "src", M.getSourceFileName()))
356 return false;
357 C = &(M.getContext());
358 DL = &M.getDataLayout();
359 CurModule = &M;
360 TargetTriple = M.getTargetTriple();
361 FunctionGuardArray = nullptr;
362 Function8bitCounterArray = nullptr;
363 FunctionBoolArray = nullptr;
364 FunctionCFsArray = nullptr;
365 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
366 PtrTy = PointerType::getUnqual(*C);
367 Type *VoidTy = Type::getVoidTy(*C);
368 IRBuilder<> IRB(M);
369 Int64Ty = IRB.getInt64Ty();
370 Int32Ty = IRB.getInt32Ty();
371 Int16Ty = IRB.getInt16Ty();
372 Int8Ty = IRB.getInt8Ty();
373 Int1Ty = IRB.getInt1Ty();
374
375 SanCovTracePCIndir =
376 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
377 // Make sure smaller parameters are zero-extended to i64 if required by the
378 // target ABI.
379 AttributeList SanCovTraceCmpZeroExtAL;
380 SanCovTraceCmpZeroExtAL =
381 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
382 SanCovTraceCmpZeroExtAL =
383 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
384
385 SanCovTraceCmpFunction[0] =
386 M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
387 IRB.getInt8Ty(), IRB.getInt8Ty());
388 SanCovTraceCmpFunction[1] =
389 M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
390 IRB.getInt16Ty(), IRB.getInt16Ty());
391 SanCovTraceCmpFunction[2] =
392 M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
393 IRB.getInt32Ty(), IRB.getInt32Ty());
394 SanCovTraceCmpFunction[3] =
395 M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
396
397 SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
398 SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
399 SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
400 SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
401 SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
402 SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
403 SanCovTraceConstCmpFunction[3] =
404 M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
405
406 // Loads.
407 SanCovLoadFunction[0] = M.getOrInsertFunction(SanCovLoad1, VoidTy, PtrTy);
408 SanCovLoadFunction[1] = M.getOrInsertFunction(SanCovLoad2, VoidTy, PtrTy);
409 SanCovLoadFunction[2] = M.getOrInsertFunction(SanCovLoad4, VoidTy, PtrTy);
410 SanCovLoadFunction[3] = M.getOrInsertFunction(SanCovLoad8, VoidTy, PtrTy);
411 SanCovLoadFunction[4] = M.getOrInsertFunction(SanCovLoad16, VoidTy, PtrTy);
412 // Stores.
413 SanCovStoreFunction[0] = M.getOrInsertFunction(SanCovStore1, VoidTy, PtrTy);
414 SanCovStoreFunction[1] = M.getOrInsertFunction(SanCovStore2, VoidTy, PtrTy);
415 SanCovStoreFunction[2] = M.getOrInsertFunction(SanCovStore4, VoidTy, PtrTy);
416 SanCovStoreFunction[3] = M.getOrInsertFunction(SanCovStore8, VoidTy, PtrTy);
417 SanCovStoreFunction[4] = M.getOrInsertFunction(SanCovStore16, VoidTy, PtrTy);
418
419 {
420 AttributeList AL;
421 AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
422 SanCovTraceDivFunction[0] =
423 M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
424 }
425 SanCovTraceDivFunction[1] =
426 M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
427 SanCovTraceGepFunction =
428 M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
429 SanCovTraceSwitchFunction =
430 M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, PtrTy);
431
432 SanCovLowestStack = M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
433 if (SanCovLowestStack->getValueType() != IntptrTy) {
434 C->emitError(StringRef("'") + SanCovLowestStackName +
435 "' should not be declared by the user");
436 return true;
437 }
438 SanCovLowestStack->setThreadLocalMode(
440 if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
441 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
442
443 if (Options.GatedCallbacks) {
444 if (!Options.TracePCGuard && !Options.TraceCmp) {
445 C->emitError("'sanitizer-coverage-gated-trace-callbacks' is only "
446 "supported with trace-pc-guard or trace-cmp");
447 return true;
448 }
449
450 SanCovCallbackGate = cast<GlobalVariable>(
451 M.getOrInsertGlobal(SanCovCallbackGateName, Int64Ty));
452 SanCovCallbackGate->setSection(
454 SanCovCallbackGate->setInitializer(Constant::getNullValue(Int64Ty));
455 SanCovCallbackGate->setLinkage(GlobalVariable::LinkOnceAnyLinkage);
456 SanCovCallbackGate->setVisibility(GlobalVariable::HiddenVisibility);
457 appendToCompilerUsed(M, SanCovCallbackGate);
458 }
459
460 SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
461 SanCovTracePCEntry = M.getOrInsertFunction(SanCovTracePCEntryName, VoidTy);
462 SanCovTracePCExit = M.getOrInsertFunction(SanCovTracePCExitName, VoidTy);
463 SanCovTracePCGuard =
464 M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, PtrTy);
465
466 SanCovStackDepthCallback =
467 M.getOrInsertFunction(SanCovStackDepthCallbackName, VoidTy);
468
469 for (auto &F : M)
470 instrumentFunction(F);
471
472 Function *Ctor = nullptr;
473
474 if (FunctionGuardArray)
475 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
478 if (Function8bitCounterArray)
479 Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
482 if (FunctionBoolArray) {
483 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName,
486 }
487 if (Ctor && Options.PCTable) {
488 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrTy);
489 FunctionCallee InitFunction =
491 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
492 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
493 }
494
495 if (Ctor && Options.CollectControlFlow) {
496 auto SecStartEnd = CreateSecStartEnd(M, SanCovCFsSectionName, IntptrTy);
497 FunctionCallee InitFunction =
499 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
500 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
501 }
502
503 appendToUsed(M, GlobalsToAppendToUsed);
504 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
505 return true;
506}
507
508// True if block has successors and it dominates all of them.
509static bool isFullDominator(const BasicBlock *BB, const DominatorTree &DT) {
510 if (succ_empty(BB))
511 return false;
512
513 return llvm::all_of(successors(BB), [&](const BasicBlock *SUCC) {
514 return DT.dominates(BB, SUCC);
515 });
516}
517
518// True if block has predecessors and it postdominates all of them.
519static bool isFullPostDominator(const BasicBlock *BB,
520 const PostDominatorTree &PDT) {
521 if (pred_empty(BB))
522 return false;
523
524 return llvm::all_of(predecessors(BB), [&](const BasicBlock *PRED) {
525 return PDT.dominates(BB, PRED);
526 });
527}
528
529static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
530 const DominatorTree &DT,
531 const PostDominatorTree &PDT,
533 // Don't insert coverage for blocks containing nothing but unreachable: we
534 // will never call __sanitizer_cov() for them, so counting them in
535 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
536 // percentage. Also, unreachable instructions frequently have no debug
537 // locations.
539 return false;
540
541 // Don't insert coverage into blocks without a valid insertion point
542 // (catchswitch blocks).
543 if (BB->getFirstInsertionPt() == BB->end())
544 return false;
545
546 if (Options.NoPrune || &F.getEntryBlock() == BB)
547 return true;
548
550 &F.getEntryBlock() != BB)
551 return false;
552
553 // Do not instrument full dominators, or full post-dominators with multiple
554 // predecessors.
555 return !isFullDominator(BB, DT) &&
556 !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
557}
558
559// Returns true iff From->To is a backedge.
560// A twist here is that we treat From->To as a backedge if
561// * To dominates From or
562// * To->UniqueSuccessor dominates From
563static bool IsBackEdge(BasicBlock *From, BasicBlock *To,
564 const DominatorTree &DT) {
565 if (DT.dominates(To, From))
566 return true;
567 if (auto Next = To->getUniqueSuccessor())
568 if (DT.dominates(Next, From))
569 return true;
570 return false;
571}
572
573// Prunes uninteresting Cmp instrumentation:
574// * CMP instructions that feed into loop backedge branch.
575//
576// Note that Cmp pruning is controlled by the same flag as the
577// BB pruning.
578static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree &DT,
580 if (!Options.NoPrune)
581 if (CMP->hasOneUse())
582 if (auto BR = dyn_cast<CondBrInst>(CMP->user_back()))
583 for (BasicBlock *B : BR->successors())
584 if (IsBackEdge(BR->getParent(), B, DT))
585 return false;
586 return true;
587}
588
589void ModuleSanitizerCoverage::instrumentFunction(Function &F) {
590 if (F.empty())
591 return;
592 if (F.getName().contains(".module_ctor"))
593 return; // Should not instrument sanitizer init functions.
594 if (F.getName().starts_with("__sanitizer_"))
595 return; // Don't instrument __sanitizer_* callbacks.
596 // Don't touch available_externally functions, their actual body is elewhere.
597 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
598 return;
599 // Don't instrument MSVC CRT configuration helpers. They may run before normal
600 // initialization.
601 if (F.getName() == "__local_stdio_printf_options" ||
602 F.getName() == "__local_stdio_scanf_options")
603 return;
604 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
605 return;
606 // Don't instrument functions using SEH for now. Splitting basic blocks like
607 // we do for coverage breaks WinEHPrepare.
608 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
609 if (F.hasPersonalityFn() &&
611 return;
612 if (Allowlist && !Allowlist->inSection("coverage", "fun", F.getName()))
613 return;
614 if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName()))
615 return;
616 // Do not apply any instrumentation for naked functions.
617 if (F.hasFnAttribute(Attribute::Naked))
618 return;
619 if (F.hasFnAttribute(Attribute::NoSanitizeCoverage))
620 return;
621 if (F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation))
622 return;
623 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge) {
625 F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
626 }
628 SmallVector<BasicBlock *, 16> BlocksToInstrument;
629 SmallVector<Instruction *, 8> CmpTraceTargets;
630 SmallVector<Instruction *, 8> SwitchTraceTargets;
631 SmallVector<BinaryOperator *, 8> DivTraceTargets;
635
636 const DominatorTree &DT = DTCallback(F);
637 const PostDominatorTree &PDT = PDTCallback(F);
638 bool IsLeafFunc = true;
639
640 for (auto &BB : F) {
641 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
642 BlocksToInstrument.push_back(&BB);
643 for (auto &Inst : BB) {
644 if (Options.IndirectCalls) {
645 CallBase *CB = dyn_cast<CallBase>(&Inst);
646 if (CB && CB->isIndirectCall())
647 IndirCalls.push_back(&Inst);
648 }
649 if (Options.TraceCmp) {
650 if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
651 if (IsInterestingCmp(CMP, DT, Options))
652 CmpTraceTargets.push_back(&Inst);
653 if (isa<SwitchInst>(&Inst))
654 SwitchTraceTargets.push_back(&Inst);
655 }
656 if (Options.TraceDiv)
658 if (BO->getOpcode() == Instruction::SDiv ||
659 BO->getOpcode() == Instruction::UDiv)
660 DivTraceTargets.push_back(BO);
661 if (Options.TraceGep)
663 GepTraceTargets.push_back(GEP);
664 if (Options.TraceLoads)
665 if (LoadInst *LI = dyn_cast<LoadInst>(&Inst))
666 Loads.push_back(LI);
667 if (Options.TraceStores)
668 if (StoreInst *SI = dyn_cast<StoreInst>(&Inst))
669 Stores.push_back(SI);
670 if (Options.StackDepth)
671 if (isa<InvokeInst>(Inst) ||
672 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
673 IsLeafFunc = false;
674 }
675 }
676
677 if (Options.CollectControlFlow)
678 createFunctionControlFlow(F);
679
680 Value *FunctionGateCmp = nullptr;
681 InjectCoverage(F, BlocksToInstrument, FunctionGateCmp, IsLeafFunc);
682 InjectCoverageForIndirectCalls(F, IndirCalls);
683 InjectTraceForCmp(F, CmpTraceTargets, FunctionGateCmp);
684 InjectTraceForSwitch(F, SwitchTraceTargets, FunctionGateCmp);
685 InjectTraceForDiv(F, DivTraceTargets);
686 InjectTraceForGep(F, GepTraceTargets);
687 InjectTraceForLoadsAndStores(F, Loads, Stores);
688 // Before InjectTraceForExits(), whose EscapeEnumerator may turn the calls
689 // into invokes. The calls it inserts precede returns and resumes, which are
690 // never in a funclet.
691 addFuncletBundles(F);
692
693 if (Options.TracePCEntryExit)
694 InjectTraceForExits(F);
695}
696
697CallInst *ModuleSanitizerCoverage::createRuntimeCall(IRBuilder<> &IRB,
698 FunctionCallee Callee,
699 ArrayRef<Value *> Args) {
700 CallInst *CI = IRB.CreateCall(Callee, Args);
701 RuntimeCalls.push_back(CI);
702 return CI;
703}
704
705// With scoped EH (MSVC C++), a call inside a funclet must name the funclet's
706// pad in a "funclet" operand bundle. WinEHPrepare takes a call without one for
707// a call that does not belong to the funclet and replaces it, and all that
708// follows it in its block, with unreachable: a catch handler that compares an
709// integer or makes an indirect call would lose its body. Give each runtime
710// call the bundle of the funclet it is in.
711void ModuleSanitizerCoverage::addFuncletBundles(Function &F) {
712 if (RuntimeCalls.empty())
713 return;
714 llvm::scope_exit ClearCalls([&] { RuntimeCalls.clear(); });
715 if (!F.hasPersonalityFn() ||
716 !isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
717 return;
718
720 for (CallInst *CI : RuntimeCalls) {
721 const ColorVector &Colors = BlockColors[CI->getParent()];
722 // Unreachable blocks have no color; they are deleted later.
723 if (Colors.empty())
724 continue;
725 // A bundle names one pad.
726 if (Colors.size() != 1) {
727 F.getContext().emitError("Instruction's BasicBlock is not monochromatic");
728 continue;
729 }
730 BasicBlock *Color = Colors.front();
731 BasicBlock::iterator Pad = Color->getFirstNonPHIIt();
732 if (Pad == Color->end() || !isa<FuncletPadInst>(Pad))
733 continue;
734 OperandBundleDef OB("funclet", &*Pad);
736 OB, CI->getIterator());
737 NewCall->copyMetadata(*CI);
738 CI->replaceAllUsesWith(NewCall);
739 CI->eraseFromParent();
740 }
741}
742
743GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection(
744 size_t NumElements, Function &F, Type *Ty, const char *Section) {
745 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
746 auto Array = new GlobalVariable(
747 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
748 Constant::getNullValue(ArrayTy), "__sancov_gen_");
749
750 // sancov_pcs parallels the other arrays, so they must be retained or
751 // discarded together. Put them in F's comdat to tie them to F for linker GC
752 // benefit. Outside ELF (nodeduplicate), a new comdat for an interposable F
753 // could prevail over a strong definition (COFF: the weak external becomes a
754 // COMDAT definition; Wasm: comdats deduplicate first). noipa doesn't affect
755 // symbol resolution.
756 if (TargetTriple.supportsCOMDAT() &&
757 (F.hasComdat() || TargetTriple.isOSBinFormatELF() ||
758 !F.isInterposable(/*CheckNoIPA=*/false)))
759 if (auto Comdat = getOrCreateFunctionComdat(F, TargetTriple))
760 Array->setComdat(Comdat);
761 Array->setSection(getSectionName(Section));
762 Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedValue()));
763
764 // Optimizers (e.g. GlobalOpt/ConstantMerge) may not discard the arrays as a
765 // unit, so retain them in the compiler; without a comdat, in the linker too.
766 if (Array->hasComdat())
767 GlobalsToAppendToCompilerUsed.push_back(Array);
768 else
769 GlobalsToAppendToUsed.push_back(Array);
770
771 return Array;
772}
773
774void ModuleSanitizerCoverage::CreatePCArray(Function &F,
775 ArrayRef<BasicBlock *> AllBlocks) {
776 size_t N = AllBlocks.size();
777 assert(N);
779 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
780 for (size_t i = 0; i < N; i++) {
781 if (&F.getEntryBlock() == AllBlocks[i]) {
782 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, PtrTy));
783 PCs.push_back(
784 (Constant *)IRB.CreateIntToPtr(ConstantInt::get(IntptrTy, 1), PtrTy));
785 } else {
787 BlockAddress::get(AllBlocks[i]), PtrTy));
789 }
790 }
791 auto *PCArray =
792 CreateFunctionLocalArrayInSection(N * 2, F, PtrTy, SanCovPCsSectionName);
793 PCArray->setInitializer(
794 ConstantArray::get(ArrayType::get(PtrTy, N * 2), PCs));
795 PCArray->setConstant(true);
796}
797
798void ModuleSanitizerCoverage::CreateFunctionLocalArrays(
799 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
800 if (Options.TracePCGuard)
801 FunctionGuardArray = CreateFunctionLocalArrayInSection(
802 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
803
804 if (Options.Inline8bitCounters)
805 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
806 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
807 if (Options.InlineBoolFlag)
808 FunctionBoolArray = CreateFunctionLocalArrayInSection(
809 AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName);
810
811 if (Options.PCTable)
812 CreatePCArray(F, AllBlocks);
813}
814
815Value *ModuleSanitizerCoverage::CreateFunctionLocalGateCmp(IRBuilder<> &IRB) {
816 auto Load = IRB.CreateLoad(Int64Ty, SanCovCallbackGate);
817 Load->setNoSanitizeMetadata();
818 auto Cmp = IRB.CreateIsNotNull(Load);
819 Cmp->setName("sancov gate cmp");
820 return Cmp;
821}
822
823Instruction *ModuleSanitizerCoverage::CreateGateBranch(Function &F,
824 Value *&FunctionGateCmp,
825 Instruction *IP) {
826 if (!FunctionGateCmp) {
827 // Create this in the entry block
828 BasicBlock &BB = F.getEntryBlock();
830 IP = PrepareToSplitEntryBlock(BB, IP);
831 IRBuilder<> EntryIRB(&*IP);
832 FunctionGateCmp = CreateFunctionLocalGateCmp(EntryIRB);
833 }
834 // Set the branch weights in order to minimize the price paid when the
835 // gate is turned off, allowing the default enablement of this
836 // instrumentation with as little of a performance cost as possible
837 auto Weights = MDBuilder(*C).createBranchWeights(1, 100000);
838 return SplitBlockAndInsertIfThen(FunctionGateCmp, IP, false, Weights);
839}
840
841bool ModuleSanitizerCoverage::InjectCoverage(Function &F,
842 ArrayRef<BasicBlock *> AllBlocks,
843 Value *&FunctionGateCmp,
844 bool IsLeafFunc) {
845 if (AllBlocks.empty())
846 return false;
847 CreateFunctionLocalArrays(F, AllBlocks);
848 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
849 InjectCoverageAtBlock(F, *AllBlocks[i], i, FunctionGateCmp, IsLeafFunc);
850
851 return true;
852}
853
854// On every indirect call we call a run-time function
855// __sanitizer_cov_indir_call* with two parameters:
856// - callee address,
857// - global cache array that contains CacheSize pointers (zero-initialized).
858// The cache is used to speed up recording the caller-callee pairs.
859// The address of the caller is passed implicitly via caller PC.
860// CacheSize is encoded in the name of the run-time function.
861void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls(
862 Function &F, ArrayRef<Instruction *> IndirCalls) {
863 if (IndirCalls.empty())
864 return;
865 assert(Options.TracePC || Options.TracePCEntryExit || Options.TracePCGuard ||
866 Options.Inline8bitCounters || Options.InlineBoolFlag);
867 for (auto *I : IndirCalls) {
869 CallBase &CB = cast<CallBase>(*I);
871 if (isa<InlineAsm>(Callee))
872 continue;
873 createRuntimeCall(IRB, SanCovTracePCIndir,
874 IRB.CreatePointerCast(Callee, IntptrTy));
875 }
876}
877
878// For every switch statement we insert a call:
879// __sanitizer_cov_trace_switch(CondValue,
880// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
881
882void ModuleSanitizerCoverage::InjectTraceForSwitch(
883 Function &F, ArrayRef<Instruction *> SwitchTraceTargets,
884 Value *&FunctionGateCmp) {
885 for (auto *I : SwitchTraceTargets) {
888 SmallVector<Constant *, 16> Initializers;
889 Value *Cond = SI->getCondition();
890 if (Cond->getType()->getScalarSizeInBits() >
891 Int64Ty->getScalarSizeInBits())
892 continue;
893 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
894 Initializers.push_back(
895 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
896 if (Cond->getType()->getScalarSizeInBits() <
897 Int64Ty->getScalarSizeInBits())
898 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
899 for (auto It : SI->cases()) {
900 ConstantInt *C = It.getCaseValue();
901 if (C->getType()->getScalarSizeInBits() < 64)
902 C = ConstantInt::get(C->getContext(), C->getValue().zext(64));
903 Initializers.push_back(C);
904 }
905 llvm::sort(drop_begin(Initializers, 2),
906 [](const Constant *A, const Constant *B) {
907 return cast<ConstantInt>(A)->getLimitedValue() <
908 cast<ConstantInt>(B)->getLimitedValue();
909 });
910 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
912 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
913 ConstantArray::get(ArrayOfInt64Ty, Initializers),
914 "__sancov_gen_cov_switch_values");
915 if (Options.GatedCallbacks) {
916 auto GateBranch = CreateGateBranch(F, FunctionGateCmp, I);
917 IRBuilder<> GateIRB(GateBranch);
918 createRuntimeCall(GateIRB, SanCovTraceSwitchFunction, {Cond, GV});
919 } else {
920 createRuntimeCall(IRB, SanCovTraceSwitchFunction, {Cond, GV});
921 }
922 }
923 }
924}
925
926void ModuleSanitizerCoverage::InjectTraceForDiv(
927 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
928 for (auto *BO : DivTraceTargets) {
930 Value *A1 = BO->getOperand(1);
931 if (isa<ConstantInt>(A1))
932 continue;
933 if (!A1->getType()->isIntegerTy())
934 continue;
935 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
936 int CallbackIdx = TypeSize == 32 ? 0 : TypeSize == 64 ? 1 : -1;
937 if (CallbackIdx < 0)
938 continue;
939 auto Ty = Type::getIntNTy(*C, TypeSize);
940 createRuntimeCall(IRB, SanCovTraceDivFunction[CallbackIdx],
941 {IRB.CreateIntCast(A1, Ty, true)});
942 }
943}
944
945void ModuleSanitizerCoverage::InjectTraceForGep(
946 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
947 for (auto *GEP : GepTraceTargets) {
949 for (Use &Idx : GEP->indices())
950 if (!isa<ConstantInt>(Idx) && Idx->getType()->isIntegerTy())
951 createRuntimeCall(IRB, SanCovTraceGepFunction,
952 {IRB.CreateIntCast(Idx, IntptrTy, true)});
953 }
954}
955
956void ModuleSanitizerCoverage::InjectTraceForLoadsAndStores(
958 auto CallbackIdx = [&](Type *ElementTy) -> int {
959 uint64_t TypeSize = DL->getTypeStoreSizeInBits(ElementTy);
960 return TypeSize == 8 ? 0
961 : TypeSize == 16 ? 1
962 : TypeSize == 32 ? 2
963 : TypeSize == 64 ? 3
964 : TypeSize == 128 ? 4
965 : -1;
966 };
967 for (auto *LI : Loads) {
969 auto Ptr = LI->getPointerOperand();
970 int Idx = CallbackIdx(LI->getType());
971 if (Idx < 0)
972 continue;
973 createRuntimeCall(IRB, SanCovLoadFunction[Idx], Ptr);
974 }
975 for (auto *SI : Stores) {
977 auto Ptr = SI->getPointerOperand();
978 int Idx = CallbackIdx(SI->getValueOperand()->getType());
979 if (Idx < 0)
980 continue;
981 createRuntimeCall(IRB, SanCovStoreFunction[Idx], Ptr);
982 }
983}
984
985void ModuleSanitizerCoverage::InjectTraceForExits(Function &F) {
986 EscapeEnumerator EE(F, "sancov_exit");
987 while (IRBuilder<> *AtExit = EE.Next()) {
989 AtExit->CreateCall(SanCovTracePCExit, {})
990 ->setTailCallKind(CallInst::TCK_NoTail);
991 }
992}
993
994void ModuleSanitizerCoverage::InjectTraceForCmp(
995 Function &F, ArrayRef<Instruction *> CmpTraceTargets,
996 Value *&FunctionGateCmp) {
997 for (auto *I : CmpTraceTargets) {
998 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
999 InstrumentationIRBuilder IRB(ICMP);
1000 Value *A0 = ICMP->getOperand(0);
1001 Value *A1 = ICMP->getOperand(1);
1002 if (!A0->getType()->isIntegerTy())
1003 continue;
1004 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
1005 int CallbackIdx = TypeSize == 8 ? 0
1006 : TypeSize == 16 ? 1
1007 : TypeSize == 32 ? 2
1008 : TypeSize == 64 ? 3
1009 : -1;
1010 if (CallbackIdx < 0)
1011 continue;
1012 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
1013 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
1014 bool FirstIsConst = isa<ConstantInt>(A0);
1015 bool SecondIsConst = isa<ConstantInt>(A1);
1016 // If both are const, then we don't need such a comparison.
1017 if (FirstIsConst && SecondIsConst)
1018 continue;
1019 // If only one is const, then make it the first callback argument.
1020 if (FirstIsConst || SecondIsConst) {
1021 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
1022 if (SecondIsConst)
1023 std::swap(A0, A1);
1024 }
1025
1026 auto Ty = Type::getIntNTy(*C, TypeSize);
1027 if (Options.GatedCallbacks) {
1028 auto GateBranch = CreateGateBranch(F, FunctionGateCmp, I);
1029 IRBuilder<> GateIRB(GateBranch);
1030 createRuntimeCall(GateIRB, CallbackFunc,
1031 {GateIRB.CreateIntCast(A0, Ty, true),
1032 GateIRB.CreateIntCast(A1, Ty, true)});
1033 } else {
1034 createRuntimeCall(
1035 IRB, CallbackFunc,
1036 {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
1037 }
1038 }
1039 }
1040}
1041
1042void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
1043 size_t Idx,
1044 Value *&FunctionGateCmp,
1045 bool IsLeafFunc) {
1047 bool IsEntryBB = &BB == &F.getEntryBlock();
1048 DebugLoc EntryLoc;
1049 if (IsEntryBB) {
1050 if (auto SP = F.getSubprogram())
1051 EntryLoc = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
1052 // Keep static allocas and llvm.localescape calls in the entry block. Even
1053 // if we aren't splitting the block, it's nice for allocas to be before
1054 // calls.
1055 IP = PrepareToSplitEntryBlock(BB, IP);
1056 }
1057
1058 InstrumentationIRBuilder IRB(&*IP);
1059 if (EntryLoc)
1060 IRB.SetCurrentDebugLocation(EntryLoc);
1061 if (Options.TracePC || (IsEntryBB && Options.TracePCEntryExit)) {
1062 FunctionCallee Callee = IsEntryBB && Options.TracePCEntryExit
1063 ? SanCovTracePCEntry
1064 : SanCovTracePC;
1065 createRuntimeCall(IRB, Callee)
1066 ->setCannotMerge(); // gets the PC using GET_CALLER_PC.
1067 }
1068 if (Options.TracePCGuard) {
1069 auto GuardPtr = IRB.CreateConstInBoundsGEP2_64(
1070 FunctionGuardArray->getValueType(), FunctionGuardArray, 0, Idx);
1071 if (Options.GatedCallbacks) {
1072 Instruction *I = &*IP;
1073 auto GateBranch = CreateGateBranch(F, FunctionGateCmp, I);
1074 IRBuilder<> GateIRB(GateBranch);
1075 createRuntimeCall(GateIRB, SanCovTracePCGuard, GuardPtr)
1076 ->setCannotMerge();
1077 } else {
1078 createRuntimeCall(IRB, SanCovTracePCGuard, GuardPtr)->setCannotMerge();
1079 }
1080 }
1081 if (Options.Inline8bitCounters) {
1082 auto CounterPtr = IRB.CreateGEP(
1083 Function8bitCounterArray->getValueType(), Function8bitCounterArray,
1084 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
1085 auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
1086 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
1087 auto Store = IRB.CreateStore(Inc, CounterPtr);
1088 Load->setNoSanitizeMetadata();
1089 Store->setNoSanitizeMetadata();
1090 }
1091 if (Options.InlineBoolFlag) {
1092 auto FlagPtr = IRB.CreateGEP(
1093 FunctionBoolArray->getValueType(), FunctionBoolArray,
1094 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
1095 auto Load = IRB.CreateLoad(Int1Ty, FlagPtr);
1096 auto ThenTerm = SplitBlockAndInsertIfThen(
1097 IRB.CreateIsNull(Load), &*IP, false,
1099 InstrumentationIRBuilder ThenIRB(ThenTerm);
1100 auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr);
1101 if (EntryLoc)
1102 Store->setDebugLoc(EntryLoc);
1103 Load->setNoSanitizeMetadata();
1104 Store->setNoSanitizeMetadata();
1105 }
1106 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
1107 Module *M = F.getParent();
1108 const DataLayout &DL = M->getDataLayout();
1109
1110 if (Options.StackDepthCallbackMin) {
1111 // In callback mode, only add call when stack depth reaches minimum.
1112 int EstimatedStackSize = 0;
1113 // If dynamic alloca found, always add call.
1114 bool HasDynamicAlloc = false;
1115 // Find an insertion point after last "alloca".
1116 llvm::Instruction *InsertBefore = nullptr;
1117
1118 // Examine all allocas in the basic block. since we're too early
1119 // to have results from Intrinsic::frameaddress, we have to manually
1120 // estimate the stack size.
1121 for (auto &I : BB) {
1122 if (auto *AI = dyn_cast<AllocaInst>(&I)) {
1123 // Move potential insertion point past the "alloca".
1124 InsertBefore = AI->getNextNode();
1125
1126 // Make an estimate on the stack usage.
1127 if (auto AllocaSize = AI->getAllocationSize(DL)) {
1128 if (AllocaSize->isFixed())
1129 EstimatedStackSize += AllocaSize->getFixedValue();
1130 else
1131 HasDynamicAlloc = true;
1132 } else {
1133 HasDynamicAlloc = true;
1134 }
1135 }
1136 }
1137
1138 if (HasDynamicAlloc ||
1139 EstimatedStackSize >= Options.StackDepthCallbackMin) {
1140 if (InsertBefore)
1141 IRB.SetInsertPoint(InsertBefore);
1142 auto Call = createRuntimeCall(IRB, SanCovStackDepthCallback);
1143 if (EntryLoc)
1144 Call->setDebugLoc(EntryLoc);
1146 }
1147 } else {
1148 // Check stack depth. If it's the deepest so far, record it.
1149 auto FrameAddrPtr = IRB.CreateIntrinsic(
1150 Intrinsic::frameaddress, IRB.getPtrTy(DL.getAllocaAddrSpace()),
1151 {Constant::getNullValue(Int32Ty)});
1152 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
1153 auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
1154 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
1155 auto ThenTerm = SplitBlockAndInsertIfThen(
1156 IsStackLower, &*IP, false,
1158 InstrumentationIRBuilder ThenIRB(ThenTerm);
1159 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
1160 if (EntryLoc)
1161 Store->setDebugLoc(EntryLoc);
1162 LowestStack->setNoSanitizeMetadata();
1163 Store->setNoSanitizeMetadata();
1164 }
1165 }
1166}
1167
1168std::string
1169ModuleSanitizerCoverage::getSectionName(const std::string &Section) const {
1170 if (TargetTriple.isOSBinFormatCOFF()) {
1171 if (Section == SanCovCountersSectionName)
1172 return ".SCOV$CM";
1173 if (Section == SanCovBoolFlagSectionName)
1174 return ".SCOV$BM";
1175 if (Section == SanCovPCsSectionName)
1176 return ".SCOVP$M";
1177 return ".SCOV$GM"; // For SanCovGuardsSectionName.
1178 }
1179 if (TargetTriple.isOSBinFormatMachO())
1180 return "__DATA,__" + Section;
1181 return "__" + Section;
1182}
1183
1184std::string
1185ModuleSanitizerCoverage::getSectionStart(const std::string &Section) const {
1186 if (TargetTriple.isOSBinFormatMachO())
1187 return "\1section$start$__DATA$__" + Section;
1188 return "__start___" + Section;
1189}
1190
1191std::string
1192ModuleSanitizerCoverage::getSectionEnd(const std::string &Section) const {
1193 if (TargetTriple.isOSBinFormatMachO())
1194 return "\1section$end$__DATA$__" + Section;
1195 return "__stop___" + Section;
1196}
1197
1198void ModuleSanitizerCoverage::createFunctionControlFlow(Function &F) {
1200 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
1201
1202 for (auto &BB : F) {
1203 // blockaddress can not be used on function's entry block.
1204 if (&BB == &F.getEntryBlock())
1205 CFs.push_back((Constant *)IRB.CreatePointerCast(&F, PtrTy));
1206 else
1207 CFs.push_back(
1208 (Constant *)IRB.CreatePointerCast(BlockAddress::get(&BB), PtrTy));
1209
1210 for (auto SuccBB : successors(&BB)) {
1211 assert(SuccBB != &F.getEntryBlock());
1212 CFs.push_back(
1213 (Constant *)IRB.CreatePointerCast(BlockAddress::get(SuccBB), PtrTy));
1214 }
1215
1217
1218 for (auto &Inst : BB) {
1219 if (CallBase *CB = dyn_cast<CallBase>(&Inst)) {
1220 if (CB->isIndirectCall()) {
1221 // TODO(navidem): handle indirect calls, for now mark its existence.
1223 ConstantInt::getAllOnesValue(IntptrTy), PtrTy));
1224 } else {
1225 auto CalledF = CB->getCalledFunction();
1226 if (CalledF && !CalledF->isIntrinsic())
1227 CFs.push_back((Constant *)IRB.CreatePointerCast(CalledF, PtrTy));
1228 }
1229 }
1230 }
1231
1233 }
1234
1235 FunctionCFsArray = CreateFunctionLocalArrayInSection(CFs.size(), F, PtrTy,
1237 FunctionCFsArray->setInitializer(
1238 ConstantArray::get(ArrayType::get(PtrTy, CFs.size()), CFs));
1239 FunctionCFsArray->setConstant(true);
1240}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const IROptions & getOptions(const Module *M)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
if(PassOpts->AAPipeline)
SmallVector< MachineOperand, 4 > Cond
const char SanCovCFsSectionName[]
static bool isFullPostDominator(const BasicBlock *BB, const PostDominatorTree &PDT)
const char SanCovTraceConstCmp4[]
const char SanCovBoolFlagSectionName[]
const char SanCov8bitCountersInitName[]
const char SanCovTracePCEntryName[]
const char SanCovLoad8[]
const char SanCovTraceSwitchName[]
const char SanCovTraceCmp1[]
const char SanCovModuleCtorTracePcGuardName[]
const char SanCovCountersSectionName[]
const char SanCovPCsInitName[]
const char SanCovTracePCGuardName[]
const char SanCovModuleCtor8bitCountersName[]
const char SanCovTracePCGuardInitName[]
const char SanCovTraceDiv4[]
static const uint64_t SanCtorAndDtorPriority
const char SanCovBoolFlagInitName[]
const char SanCovTraceGep[]
const char SanCovLoad16[]
const char SanCovTraceConstCmp8[]
const char SanCovGuardsSectionName[]
const char SanCovStore1[]
const char SanCovTraceConstCmp2[]
const char SanCovTraceConstCmp1[]
static bool IsBackEdge(BasicBlock *From, BasicBlock *To, const DominatorTree &DT)
const char SanCovCallbackGateName[]
const char SanCovTraceDiv8[]
const char SanCovLoad4[]
const char SanCovStackDepthCallbackName[]
const char SanCovCFsInitName[]
const char SanCovStore2[]
const char SanCovPCsSectionName[]
const char SanCovLoad1[]
const char SanCovTracePCExitName[]
static bool isFullDominator(const BasicBlock *BB, const DominatorTree &DT)
const char SanCovTraceCmp8[]
const char SanCovCallbackGateSectionName[]
const char SanCovStore16[]
static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree &DT, const SanitizerCoverageOptions &Options)
static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB, const DominatorTree &DT, const PostDominatorTree &PDT, const SanitizerCoverageOptions &Options)
const char SanCovModuleCtorBoolFlagName[]
const char SanCovTraceCmp2[]
const char SanCovStore8[]
const char SanCovTracePCName[]
const char SanCovStore4[]
const char SanCovLoad2[]
const char SanCovTraceCmp4[]
const char SanCovLowestStackName[]
const char SanCovTracePCIndirName[]
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallVector class.
Defines the virtual file system interface vfs::FileSystem.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrLifetime() const
Returns an iterator to the first instruction in this block that is not a PHINode, a lifetime intrinsi...
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
void setCannotMerge()
static LLVM_ABI CallBase * addOperandBundle(CallBase *CB, uint32_t ID, OperandBundleDef OB, InsertPosition InsertPt=nullptr)
Create a clone of CB with operand bundle OB added.
Value * getCalledOperand() const
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h:1518
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:127
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
EscapeEnumerator - This is a little algorithm to find all escape points from a function so that "fina...
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
const BasicBlock & getEntryBlock() const
Definition Function.h:803
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
void setLinkage(LinkageTypes LT)
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
void setVisibility(VisibilityTypes V)
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
Analysis pass providing a never-invalidated alias analysis result.
This instruction compares its operands according to the predicate given to the constructor.
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2474
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2373
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2314
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:229
LLVM_ABI Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1913
LLVMContext & getContext() const
Definition IRBuilder.h:178
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
Value * CreateConstInBoundsGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0, uint64_t Idx1, const Twine &Name="")
Definition IRBuilder.h:2078
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1931
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1424
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2309
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition IRBuilder.h:2842
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2640
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:571
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition IRBuilder.h:2399
Value * CreateIsNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg == 0.
Definition IRBuilder.h:2837
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
LLVM_ABI MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
Definition MDBuilder.cpp:48
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
LLVM_ABI bool dominates(const Instruction *I1, const Instruction *I2) const
Return true if I1 dominates I2.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & abandon()
Mark an analysis as abandoned.
Definition Analysis.h:172
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI SanitizerCoveragePass(SanitizerCoverageOptions Options=SanitizerCoverageOptions(), IntrusiveRefCntPtr< vfs::FileSystem > VFS=nullptr, const std::vector< std::string > &AllowlistFiles={}, const std::vector< std::string > &BlocklistFiles={})
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This is a utility class used to parse user-provided text files with "special case lists" for code san...
static LLVM_ABI std::unique_ptr< SpecialCaseList > createOrDie(const std::vector< std::string > &Paths, llvm::vfs::FileSystem &FS)
Parses the special case list entries from files.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Multiway switch.
EltTy front() const
unsigned size() const
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
CallInst * Call
constexpr MCPhysReg SP
@ OB
OB - OneByte - Set if this instruction has a one byte opcode.
static constexpr const StringLiteral & getSectionName(DebugSectionKind SectionKind)
Return the name of the section.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
const InstrumentationOptions & getInstrumentationOptions(const LLVMContext &C)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
bool succ_empty(const Instruction *I)
Definition CFG.h:141
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
LLVM_ABI DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
LLVM_ABI FunctionCallee declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type * > InitArgTypes, bool Weak=false)
LLVM_ABI std::pair< Function *, FunctionCallee > createSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs, StringRef VersionCheckName=StringRef(), bool Weak=false)
Creates sanitizer constructor function, and calls sanitizer's init function from it.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
LLVM_ABI Comdat * getOrCreateFunctionComdat(Function &F, Triple &T)
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
OperandBundleDefT< Value * > OperandBundleDef
Definition AutoUpgrade.h:35
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
LLVM_ABI unsigned SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
Loop over all of the edges in the CFG, breaking critical edges as they are found.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
TinyPtrVector< BasicBlock * > ColorVector
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI BasicBlock::iterator PrepareToSplitEntryBlock(BasicBlock &BB, BasicBlock::iterator IP)
Instrumentation passes often insert conditional checks into entry blocks.
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
LLVM_ABI void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Option class for critical edge splitting.
static void ensureDebugInfo(IRBuilder<> &IRB, const Function &F)
enum llvm::SanitizerCoverageOptions::Type CoverageType