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 GlobalVariable *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 *FunctionPCsArray; // for pc-table.
240 GlobalVariable *FunctionCFsArray; // for control flow table
241 // Runtime calls inserted into the current function, for
242 // addFuncletBundles().
243 SmallVector<CallInst *, 16> RuntimeCalls;
244 SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
245 SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
246
248
249 const SpecialCaseList *Allowlist;
250 const SpecialCaseList *Blocklist;
251};
252} // namespace
253
256 const std::vector<std::string> &AllowlistFiles,
257 const std::vector<std::string> &BlocklistFiles)
258 : Options(std::move(Options)),
259 VFS(VFS ? std::move(VFS) : vfs::getRealFileSystem()) {
260 if (AllowlistFiles.size() > 0)
261 Allowlist = SpecialCaseList::createOrDie(AllowlistFiles, *this->VFS);
262 if (BlocklistFiles.size() > 0)
263 Blocklist = SpecialCaseList::createOrDie(BlocklistFiles, *this->VFS);
264}
265
268 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
269 auto DTCallback = [&FAM](Function &F) -> const DominatorTree & {
270 return FAM.getResult<DominatorTreeAnalysis>(F);
271 };
272 auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree & {
273 return FAM.getResult<PostDominatorTreeAnalysis>(F);
274 };
275 const InstrumentationOptions &Opts = getInstrumentationOptions(M);
276 ModuleSanitizerCoverage ModuleSancov(Opts, M, DTCallback, PDTCallback,
277 overrideFromCL(Opts, Options),
278 Allowlist.get(), Blocklist.get());
279 if (!ModuleSancov.instrumentModule())
280 return PreservedAnalyses::all();
281
283 // GlobalsAA is considered stateless and does not get invalidated unless
284 // explicitly invalidated; PreservedAnalyses::none() is not enough. Sanitizers
285 // make changes that require GlobalsAA to be invalidated.
286 PA.abandon<GlobalsAA>();
287 return PA;
288}
289
290std::pair<Value *, Value *>
291ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section,
292 Type *Ty) {
293 // Use ExternalWeak so that if all sections are discarded due to section
294 // garbage collection, the linker will not report undefined symbol errors.
295 // Windows defines the start/stop symbols in compiler-rt so no need for
296 // ExternalWeak.
297 GlobalValue::LinkageTypes Linkage = TargetTriple.isOSBinFormatCOFF()
300 GlobalVariable *SecStart = new GlobalVariable(M, Ty, false, Linkage, nullptr,
301 getSectionStart(Section));
303 GlobalVariable *SecEnd = new GlobalVariable(M, Ty, false, Linkage, nullptr,
304 getSectionEnd(Section));
306 if (!TargetTriple.isOSBinFormatCOFF())
307 return std::make_pair(SecStart, SecEnd);
308
309 // Account for the fact that on windows-msvc __start_* symbols actually
310 // point to a uint64_t before the start of the array.
312 SecStart, ConstantInt::get(IntptrTy, sizeof(uint64_t)));
313 return std::make_pair(GEP, SecEnd);
314}
315
316Function *ModuleSanitizerCoverage::CreateInitCallsForSections(
317 Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
318 const char *Section) {
319 if (Opts.sanitizer_coverage_drop_ctors)
320 return nullptr;
321 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
322 auto SecStart = SecStartEnd.first;
323 auto SecEnd = SecStartEnd.second;
324 Function *CtorFunc;
325 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
326 M, CtorName, InitFunctionName, {PtrTy, PtrTy}, {SecStart, SecEnd});
327 assert(CtorFunc->getName() == CtorName);
328
329 if (TargetTriple.supportsCOMDAT()) {
330 // Use comdat to dedup CtorFunc.
331 CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
332 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
333 } else {
335 }
336
337 if (TargetTriple.isOSBinFormatCOFF()) {
338 // In COFF files, if the contructors are set as COMDAT (they are because
339 // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
340 // functions and data) is used, the constructors get stripped. To prevent
341 // this, give the constructors weak ODR linkage and ensure the linker knows
342 // to include the sancov constructor. This way the linker can deduplicate
343 // the constructors but always leave one copy.
345 }
346 return CtorFunc;
347}
348
349bool ModuleSanitizerCoverage::instrumentModule() {
351 return false;
352 if (Allowlist &&
353 !Allowlist->inSection("coverage", "src", M.getSourceFileName()))
354 return false;
355 if (Blocklist &&
356 Blocklist->inSection("coverage", "src", M.getSourceFileName()))
357 return false;
358 C = &(M.getContext());
359 DL = &M.getDataLayout();
360 CurModule = &M;
361 TargetTriple = M.getTargetTriple();
362 FunctionGuardArray = nullptr;
363 Function8bitCounterArray = nullptr;
364 FunctionBoolArray = nullptr;
365 FunctionPCsArray = nullptr;
366 FunctionCFsArray = nullptr;
367 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
368 PtrTy = PointerType::getUnqual(*C);
369 Type *VoidTy = Type::getVoidTy(*C);
370 IRBuilder<> IRB(M);
371 Int64Ty = IRB.getInt64Ty();
372 Int32Ty = IRB.getInt32Ty();
373 Int16Ty = IRB.getInt16Ty();
374 Int8Ty = IRB.getInt8Ty();
375 Int1Ty = IRB.getInt1Ty();
376
377 SanCovTracePCIndir =
378 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
379 // Make sure smaller parameters are zero-extended to i64 if required by the
380 // target ABI.
381 AttributeList SanCovTraceCmpZeroExtAL;
382 SanCovTraceCmpZeroExtAL =
383 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
384 SanCovTraceCmpZeroExtAL =
385 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
386
387 SanCovTraceCmpFunction[0] =
388 M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
389 IRB.getInt8Ty(), IRB.getInt8Ty());
390 SanCovTraceCmpFunction[1] =
391 M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
392 IRB.getInt16Ty(), IRB.getInt16Ty());
393 SanCovTraceCmpFunction[2] =
394 M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
395 IRB.getInt32Ty(), IRB.getInt32Ty());
396 SanCovTraceCmpFunction[3] =
397 M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
398
399 SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
400 SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
401 SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
402 SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
403 SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
404 SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
405 SanCovTraceConstCmpFunction[3] =
406 M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
407
408 // Loads.
409 SanCovLoadFunction[0] = M.getOrInsertFunction(SanCovLoad1, VoidTy, PtrTy);
410 SanCovLoadFunction[1] = M.getOrInsertFunction(SanCovLoad2, VoidTy, PtrTy);
411 SanCovLoadFunction[2] = M.getOrInsertFunction(SanCovLoad4, VoidTy, PtrTy);
412 SanCovLoadFunction[3] = M.getOrInsertFunction(SanCovLoad8, VoidTy, PtrTy);
413 SanCovLoadFunction[4] = M.getOrInsertFunction(SanCovLoad16, VoidTy, PtrTy);
414 // Stores.
415 SanCovStoreFunction[0] = M.getOrInsertFunction(SanCovStore1, VoidTy, PtrTy);
416 SanCovStoreFunction[1] = M.getOrInsertFunction(SanCovStore2, VoidTy, PtrTy);
417 SanCovStoreFunction[2] = M.getOrInsertFunction(SanCovStore4, VoidTy, PtrTy);
418 SanCovStoreFunction[3] = M.getOrInsertFunction(SanCovStore8, VoidTy, PtrTy);
419 SanCovStoreFunction[4] = M.getOrInsertFunction(SanCovStore16, VoidTy, PtrTy);
420
421 {
422 AttributeList AL;
423 AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
424 SanCovTraceDivFunction[0] =
425 M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
426 }
427 SanCovTraceDivFunction[1] =
428 M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
429 SanCovTraceGepFunction =
430 M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
431 SanCovTraceSwitchFunction =
432 M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, PtrTy);
433
434 SanCovLowestStack = M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
435 if (SanCovLowestStack->getValueType() != IntptrTy) {
436 C->emitError(StringRef("'") + SanCovLowestStackName +
437 "' should not be declared by the user");
438 return true;
439 }
440 SanCovLowestStack->setThreadLocalMode(
442 if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
443 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
444
445 if (Options.GatedCallbacks) {
446 if (!Options.TracePCGuard && !Options.TraceCmp) {
447 C->emitError("'sanitizer-coverage-gated-trace-callbacks' is only "
448 "supported with trace-pc-guard or trace-cmp");
449 return true;
450 }
451
452 SanCovCallbackGate = cast<GlobalVariable>(
453 M.getOrInsertGlobal(SanCovCallbackGateName, Int64Ty));
454 SanCovCallbackGate->setSection(
456 SanCovCallbackGate->setInitializer(Constant::getNullValue(Int64Ty));
457 SanCovCallbackGate->setLinkage(GlobalVariable::LinkOnceAnyLinkage);
458 SanCovCallbackGate->setVisibility(GlobalVariable::HiddenVisibility);
459 appendToCompilerUsed(M, SanCovCallbackGate);
460 }
461
462 SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
463 SanCovTracePCEntry = M.getOrInsertFunction(SanCovTracePCEntryName, VoidTy);
464 SanCovTracePCExit = M.getOrInsertFunction(SanCovTracePCExitName, VoidTy);
465 SanCovTracePCGuard =
466 M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, PtrTy);
467
468 SanCovStackDepthCallback =
469 M.getOrInsertFunction(SanCovStackDepthCallbackName, VoidTy);
470
471 for (auto &F : M)
472 instrumentFunction(F);
473
474 Function *Ctor = nullptr;
475
476 if (FunctionGuardArray)
477 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
480 if (Function8bitCounterArray)
481 Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
484 if (FunctionBoolArray) {
485 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName,
488 }
489 if (Ctor && Options.PCTable) {
490 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrTy);
491 FunctionCallee InitFunction =
493 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
494 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
495 }
496
497 if (Ctor && Options.CollectControlFlow) {
498 auto SecStartEnd = CreateSecStartEnd(M, SanCovCFsSectionName, IntptrTy);
499 FunctionCallee InitFunction =
501 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
502 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
503 }
504
505 appendToUsed(M, GlobalsToAppendToUsed);
506 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
507 return true;
508}
509
510// True if block has successors and it dominates all of them.
511static bool isFullDominator(const BasicBlock *BB, const DominatorTree &DT) {
512 if (succ_empty(BB))
513 return false;
514
515 return llvm::all_of(successors(BB), [&](const BasicBlock *SUCC) {
516 return DT.dominates(BB, SUCC);
517 });
518}
519
520// True if block has predecessors and it postdominates all of them.
521static bool isFullPostDominator(const BasicBlock *BB,
522 const PostDominatorTree &PDT) {
523 if (pred_empty(BB))
524 return false;
525
526 return llvm::all_of(predecessors(BB), [&](const BasicBlock *PRED) {
527 return PDT.dominates(BB, PRED);
528 });
529}
530
531static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
532 const DominatorTree &DT,
533 const PostDominatorTree &PDT,
535 // Don't insert coverage for blocks containing nothing but unreachable: we
536 // will never call __sanitizer_cov() for them, so counting them in
537 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
538 // percentage. Also, unreachable instructions frequently have no debug
539 // locations.
541 return false;
542
543 // Don't insert coverage into blocks without a valid insertion point
544 // (catchswitch blocks).
545 if (BB->getFirstInsertionPt() == BB->end())
546 return false;
547
548 if (Options.NoPrune || &F.getEntryBlock() == BB)
549 return true;
550
552 &F.getEntryBlock() != BB)
553 return false;
554
555 // Do not instrument full dominators, or full post-dominators with multiple
556 // predecessors.
557 return !isFullDominator(BB, DT) &&
558 !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
559}
560
561// Returns true iff From->To is a backedge.
562// A twist here is that we treat From->To as a backedge if
563// * To dominates From or
564// * To->UniqueSuccessor dominates From
565static bool IsBackEdge(BasicBlock *From, BasicBlock *To,
566 const DominatorTree &DT) {
567 if (DT.dominates(To, From))
568 return true;
569 if (auto Next = To->getUniqueSuccessor())
570 if (DT.dominates(Next, From))
571 return true;
572 return false;
573}
574
575// Prunes uninteresting Cmp instrumentation:
576// * CMP instructions that feed into loop backedge branch.
577//
578// Note that Cmp pruning is controlled by the same flag as the
579// BB pruning.
580static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree &DT,
582 if (!Options.NoPrune)
583 if (CMP->hasOneUse())
584 if (auto BR = dyn_cast<CondBrInst>(CMP->user_back()))
585 for (BasicBlock *B : BR->successors())
586 if (IsBackEdge(BR->getParent(), B, DT))
587 return false;
588 return true;
589}
590
591void ModuleSanitizerCoverage::instrumentFunction(Function &F) {
592 if (F.empty())
593 return;
594 if (F.getName().contains(".module_ctor"))
595 return; // Should not instrument sanitizer init functions.
596 if (F.getName().starts_with("__sanitizer_"))
597 return; // Don't instrument __sanitizer_* callbacks.
598 // Don't touch available_externally functions, their actual body is elewhere.
599 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
600 return;
601 // Don't instrument MSVC CRT configuration helpers. They may run before normal
602 // initialization.
603 if (F.getName() == "__local_stdio_printf_options" ||
604 F.getName() == "__local_stdio_scanf_options")
605 return;
606 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
607 return;
608 // Don't instrument functions using SEH for now. Splitting basic blocks like
609 // we do for coverage breaks WinEHPrepare.
610 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
611 if (F.hasPersonalityFn() &&
613 return;
614 if (Allowlist && !Allowlist->inSection("coverage", "fun", F.getName()))
615 return;
616 if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName()))
617 return;
618 // Do not apply any instrumentation for naked functions.
619 if (F.hasFnAttribute(Attribute::Naked))
620 return;
621 if (F.hasFnAttribute(Attribute::NoSanitizeCoverage))
622 return;
623 if (F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation))
624 return;
625 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge) {
627 F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
628 }
630 SmallVector<BasicBlock *, 16> BlocksToInstrument;
631 SmallVector<Instruction *, 8> CmpTraceTargets;
632 SmallVector<Instruction *, 8> SwitchTraceTargets;
633 SmallVector<BinaryOperator *, 8> DivTraceTargets;
637
638 const DominatorTree &DT = DTCallback(F);
639 const PostDominatorTree &PDT = PDTCallback(F);
640 bool IsLeafFunc = true;
641
642 for (auto &BB : F) {
643 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
644 BlocksToInstrument.push_back(&BB);
645 for (auto &Inst : BB) {
646 if (Options.IndirectCalls) {
647 CallBase *CB = dyn_cast<CallBase>(&Inst);
648 if (CB && CB->isIndirectCall())
649 IndirCalls.push_back(&Inst);
650 }
651 if (Options.TraceCmp) {
652 if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
653 if (IsInterestingCmp(CMP, DT, Options))
654 CmpTraceTargets.push_back(&Inst);
655 if (isa<SwitchInst>(&Inst))
656 SwitchTraceTargets.push_back(&Inst);
657 }
658 if (Options.TraceDiv)
660 if (BO->getOpcode() == Instruction::SDiv ||
661 BO->getOpcode() == Instruction::UDiv)
662 DivTraceTargets.push_back(BO);
663 if (Options.TraceGep)
665 GepTraceTargets.push_back(GEP);
666 if (Options.TraceLoads)
667 if (LoadInst *LI = dyn_cast<LoadInst>(&Inst))
668 Loads.push_back(LI);
669 if (Options.TraceStores)
670 if (StoreInst *SI = dyn_cast<StoreInst>(&Inst))
671 Stores.push_back(SI);
672 if (Options.StackDepth)
673 if (isa<InvokeInst>(Inst) ||
674 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
675 IsLeafFunc = false;
676 }
677 }
678
679 if (Options.CollectControlFlow)
680 createFunctionControlFlow(F);
681
682 Value *FunctionGateCmp = nullptr;
683 InjectCoverage(F, BlocksToInstrument, FunctionGateCmp, IsLeafFunc);
684 InjectCoverageForIndirectCalls(F, IndirCalls);
685 InjectTraceForCmp(F, CmpTraceTargets, FunctionGateCmp);
686 InjectTraceForSwitch(F, SwitchTraceTargets, FunctionGateCmp);
687 InjectTraceForDiv(F, DivTraceTargets);
688 InjectTraceForGep(F, GepTraceTargets);
689 InjectTraceForLoadsAndStores(F, Loads, Stores);
690 // Before InjectTraceForExits(), whose EscapeEnumerator may turn the calls
691 // into invokes. The calls it inserts precede returns and resumes, which are
692 // never in a funclet.
693 addFuncletBundles(F);
694
695 if (Options.TracePCEntryExit)
696 InjectTraceForExits(F);
697}
698
699CallInst *ModuleSanitizerCoverage::createRuntimeCall(IRBuilder<> &IRB,
700 FunctionCallee Callee,
701 ArrayRef<Value *> Args) {
702 CallInst *CI = IRB.CreateCall(Callee, Args);
703 RuntimeCalls.push_back(CI);
704 return CI;
705}
706
707// With scoped EH (MSVC C++), a call inside a funclet must name the funclet's
708// pad in a "funclet" operand bundle. WinEHPrepare takes a call without one for
709// a call that does not belong to the funclet and replaces it, and all that
710// follows it in its block, with unreachable: a catch handler that compares an
711// integer or makes an indirect call would lose its body. Give each runtime
712// call the bundle of the funclet it is in.
713void ModuleSanitizerCoverage::addFuncletBundles(Function &F) {
714 if (RuntimeCalls.empty())
715 return;
716 llvm::scope_exit ClearCalls([&] { RuntimeCalls.clear(); });
717 if (!F.hasPersonalityFn() ||
718 !isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
719 return;
720
722 for (CallInst *CI : RuntimeCalls) {
723 const ColorVector &Colors = BlockColors[CI->getParent()];
724 // Unreachable blocks have no color; they are deleted later.
725 if (Colors.empty())
726 continue;
727 // A bundle names one pad.
728 if (Colors.size() != 1) {
729 F.getContext().emitError("Instruction's BasicBlock is not monochromatic");
730 continue;
731 }
732 BasicBlock *Color = Colors.front();
733 BasicBlock::iterator Pad = Color->getFirstNonPHIIt();
734 if (Pad == Color->end() || !isa<FuncletPadInst>(Pad))
735 continue;
736 OperandBundleDef OB("funclet", &*Pad);
738 OB, CI->getIterator());
739 NewCall->copyMetadata(*CI);
740 CI->replaceAllUsesWith(NewCall);
741 CI->eraseFromParent();
742 }
743}
744
745GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection(
746 size_t NumElements, Function &F, Type *Ty, const char *Section) {
747 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
748 auto Array = new GlobalVariable(
749 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
750 Constant::getNullValue(ArrayTy), "__sancov_gen_");
751
752 // sancov_pcs parallels the other arrays, so they must be retained or
753 // discarded together. Put them in F's comdat to tie them to F for linker GC
754 // benefit. Outside ELF (nodeduplicate), a new comdat for an interposable F
755 // could prevail over a strong definition (COFF: the weak external becomes a
756 // COMDAT definition; Wasm: comdats deduplicate first). noipa doesn't affect
757 // symbol resolution.
758 if (TargetTriple.supportsCOMDAT() &&
759 (F.hasComdat() || TargetTriple.isOSBinFormatELF() ||
760 !F.isInterposable(/*CheckNoIPA=*/false)))
761 if (auto Comdat = getOrCreateFunctionComdat(F, TargetTriple))
762 Array->setComdat(Comdat);
763 Array->setSection(getSectionName(Section));
764 Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedValue()));
765
766 // Optimizers (e.g. GlobalOpt/ConstantMerge) may not discard the arrays as a
767 // unit, so retain them in the compiler; without a comdat, in the linker too.
768 if (Array->hasComdat())
769 GlobalsToAppendToCompilerUsed.push_back(Array);
770 else
771 GlobalsToAppendToUsed.push_back(Array);
772
773 return Array;
774}
775
777ModuleSanitizerCoverage::CreatePCArray(Function &F,
778 ArrayRef<BasicBlock *> AllBlocks) {
779 size_t N = AllBlocks.size();
780 assert(N);
782 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
783 for (size_t i = 0; i < N; i++) {
784 if (&F.getEntryBlock() == AllBlocks[i]) {
785 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, PtrTy));
786 PCs.push_back(
787 (Constant *)IRB.CreateIntToPtr(ConstantInt::get(IntptrTy, 1), PtrTy));
788 } else {
790 BlockAddress::get(AllBlocks[i]), PtrTy));
792 }
793 }
794 auto *PCArray =
795 CreateFunctionLocalArrayInSection(N * 2, F, PtrTy, SanCovPCsSectionName);
796 PCArray->setInitializer(
797 ConstantArray::get(ArrayType::get(PtrTy, N * 2), PCs));
798 PCArray->setConstant(true);
799
800 return PCArray;
801}
802
803void ModuleSanitizerCoverage::CreateFunctionLocalArrays(
804 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
805 if (Options.TracePCGuard)
806 FunctionGuardArray = CreateFunctionLocalArrayInSection(
807 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
808
809 if (Options.Inline8bitCounters)
810 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
811 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
812 if (Options.InlineBoolFlag)
813 FunctionBoolArray = CreateFunctionLocalArrayInSection(
814 AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName);
815
816 if (Options.PCTable)
817 FunctionPCsArray = CreatePCArray(F, AllBlocks);
818}
819
820Value *ModuleSanitizerCoverage::CreateFunctionLocalGateCmp(IRBuilder<> &IRB) {
821 auto Load = IRB.CreateLoad(Int64Ty, SanCovCallbackGate);
822 Load->setNoSanitizeMetadata();
823 auto Cmp = IRB.CreateIsNotNull(Load);
824 Cmp->setName("sancov gate cmp");
825 return Cmp;
826}
827
828Instruction *ModuleSanitizerCoverage::CreateGateBranch(Function &F,
829 Value *&FunctionGateCmp,
830 Instruction *IP) {
831 if (!FunctionGateCmp) {
832 // Create this in the entry block
833 BasicBlock &BB = F.getEntryBlock();
835 IP = PrepareToSplitEntryBlock(BB, IP);
836 IRBuilder<> EntryIRB(&*IP);
837 FunctionGateCmp = CreateFunctionLocalGateCmp(EntryIRB);
838 }
839 // Set the branch weights in order to minimize the price paid when the
840 // gate is turned off, allowing the default enablement of this
841 // instrumentation with as little of a performance cost as possible
842 auto Weights = MDBuilder(*C).createBranchWeights(1, 100000);
843 return SplitBlockAndInsertIfThen(FunctionGateCmp, IP, false, Weights);
844}
845
846bool ModuleSanitizerCoverage::InjectCoverage(Function &F,
847 ArrayRef<BasicBlock *> AllBlocks,
848 Value *&FunctionGateCmp,
849 bool IsLeafFunc) {
850 if (AllBlocks.empty())
851 return false;
852 CreateFunctionLocalArrays(F, AllBlocks);
853 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
854 InjectCoverageAtBlock(F, *AllBlocks[i], i, FunctionGateCmp, IsLeafFunc);
855
856 return true;
857}
858
859// On every indirect call we call a run-time function
860// __sanitizer_cov_indir_call* with two parameters:
861// - callee address,
862// - global cache array that contains CacheSize pointers (zero-initialized).
863// The cache is used to speed up recording the caller-callee pairs.
864// The address of the caller is passed implicitly via caller PC.
865// CacheSize is encoded in the name of the run-time function.
866void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls(
867 Function &F, ArrayRef<Instruction *> IndirCalls) {
868 if (IndirCalls.empty())
869 return;
870 assert(Options.TracePC || Options.TracePCEntryExit || Options.TracePCGuard ||
871 Options.Inline8bitCounters || Options.InlineBoolFlag);
872 for (auto *I : IndirCalls) {
874 CallBase &CB = cast<CallBase>(*I);
876 if (isa<InlineAsm>(Callee))
877 continue;
878 createRuntimeCall(IRB, SanCovTracePCIndir,
879 IRB.CreatePointerCast(Callee, IntptrTy));
880 }
881}
882
883// For every switch statement we insert a call:
884// __sanitizer_cov_trace_switch(CondValue,
885// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
886
887void ModuleSanitizerCoverage::InjectTraceForSwitch(
888 Function &F, ArrayRef<Instruction *> SwitchTraceTargets,
889 Value *&FunctionGateCmp) {
890 for (auto *I : SwitchTraceTargets) {
893 SmallVector<Constant *, 16> Initializers;
894 Value *Cond = SI->getCondition();
895 if (Cond->getType()->getScalarSizeInBits() >
896 Int64Ty->getScalarSizeInBits())
897 continue;
898 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
899 Initializers.push_back(
900 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
901 if (Cond->getType()->getScalarSizeInBits() <
902 Int64Ty->getScalarSizeInBits())
903 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
904 for (auto It : SI->cases()) {
905 ConstantInt *C = It.getCaseValue();
906 if (C->getType()->getScalarSizeInBits() < 64)
907 C = ConstantInt::get(C->getContext(), C->getValue().zext(64));
908 Initializers.push_back(C);
909 }
910 llvm::sort(drop_begin(Initializers, 2),
911 [](const Constant *A, const Constant *B) {
912 return cast<ConstantInt>(A)->getLimitedValue() <
913 cast<ConstantInt>(B)->getLimitedValue();
914 });
915 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
917 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
918 ConstantArray::get(ArrayOfInt64Ty, Initializers),
919 "__sancov_gen_cov_switch_values");
920 if (Options.GatedCallbacks) {
921 auto GateBranch = CreateGateBranch(F, FunctionGateCmp, I);
922 IRBuilder<> GateIRB(GateBranch);
923 createRuntimeCall(GateIRB, SanCovTraceSwitchFunction, {Cond, GV});
924 } else {
925 createRuntimeCall(IRB, SanCovTraceSwitchFunction, {Cond, GV});
926 }
927 }
928 }
929}
930
931void ModuleSanitizerCoverage::InjectTraceForDiv(
932 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
933 for (auto *BO : DivTraceTargets) {
935 Value *A1 = BO->getOperand(1);
936 if (isa<ConstantInt>(A1))
937 continue;
938 if (!A1->getType()->isIntegerTy())
939 continue;
940 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
941 int CallbackIdx = TypeSize == 32 ? 0 : TypeSize == 64 ? 1 : -1;
942 if (CallbackIdx < 0)
943 continue;
944 auto Ty = Type::getIntNTy(*C, TypeSize);
945 createRuntimeCall(IRB, SanCovTraceDivFunction[CallbackIdx],
946 {IRB.CreateIntCast(A1, Ty, true)});
947 }
948}
949
950void ModuleSanitizerCoverage::InjectTraceForGep(
951 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
952 for (auto *GEP : GepTraceTargets) {
954 for (Use &Idx : GEP->indices())
955 if (!isa<ConstantInt>(Idx) && Idx->getType()->isIntegerTy())
956 createRuntimeCall(IRB, SanCovTraceGepFunction,
957 {IRB.CreateIntCast(Idx, IntptrTy, true)});
958 }
959}
960
961void ModuleSanitizerCoverage::InjectTraceForLoadsAndStores(
963 auto CallbackIdx = [&](Type *ElementTy) -> int {
964 uint64_t TypeSize = DL->getTypeStoreSizeInBits(ElementTy);
965 return TypeSize == 8 ? 0
966 : TypeSize == 16 ? 1
967 : TypeSize == 32 ? 2
968 : TypeSize == 64 ? 3
969 : TypeSize == 128 ? 4
970 : -1;
971 };
972 for (auto *LI : Loads) {
974 auto Ptr = LI->getPointerOperand();
975 int Idx = CallbackIdx(LI->getType());
976 if (Idx < 0)
977 continue;
978 createRuntimeCall(IRB, SanCovLoadFunction[Idx], Ptr);
979 }
980 for (auto *SI : Stores) {
982 auto Ptr = SI->getPointerOperand();
983 int Idx = CallbackIdx(SI->getValueOperand()->getType());
984 if (Idx < 0)
985 continue;
986 createRuntimeCall(IRB, SanCovStoreFunction[Idx], Ptr);
987 }
988}
989
990void ModuleSanitizerCoverage::InjectTraceForExits(Function &F) {
991 EscapeEnumerator EE(F, "sancov_exit");
992 while (IRBuilder<> *AtExit = EE.Next()) {
994 AtExit->CreateCall(SanCovTracePCExit, {})
995 ->setTailCallKind(CallInst::TCK_NoTail);
996 }
997}
998
999void ModuleSanitizerCoverage::InjectTraceForCmp(
1000 Function &F, ArrayRef<Instruction *> CmpTraceTargets,
1001 Value *&FunctionGateCmp) {
1002 for (auto *I : CmpTraceTargets) {
1003 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
1004 InstrumentationIRBuilder IRB(ICMP);
1005 Value *A0 = ICMP->getOperand(0);
1006 Value *A1 = ICMP->getOperand(1);
1007 if (!A0->getType()->isIntegerTy())
1008 continue;
1009 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
1010 int CallbackIdx = TypeSize == 8 ? 0
1011 : TypeSize == 16 ? 1
1012 : TypeSize == 32 ? 2
1013 : TypeSize == 64 ? 3
1014 : -1;
1015 if (CallbackIdx < 0)
1016 continue;
1017 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
1018 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
1019 bool FirstIsConst = isa<ConstantInt>(A0);
1020 bool SecondIsConst = isa<ConstantInt>(A1);
1021 // If both are const, then we don't need such a comparison.
1022 if (FirstIsConst && SecondIsConst)
1023 continue;
1024 // If only one is const, then make it the first callback argument.
1025 if (FirstIsConst || SecondIsConst) {
1026 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
1027 if (SecondIsConst)
1028 std::swap(A0, A1);
1029 }
1030
1031 auto Ty = Type::getIntNTy(*C, TypeSize);
1032 if (Options.GatedCallbacks) {
1033 auto GateBranch = CreateGateBranch(F, FunctionGateCmp, I);
1034 IRBuilder<> GateIRB(GateBranch);
1035 createRuntimeCall(GateIRB, CallbackFunc,
1036 {GateIRB.CreateIntCast(A0, Ty, true),
1037 GateIRB.CreateIntCast(A1, Ty, true)});
1038 } else {
1039 createRuntimeCall(
1040 IRB, CallbackFunc,
1041 {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
1042 }
1043 }
1044 }
1045}
1046
1047void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
1048 size_t Idx,
1049 Value *&FunctionGateCmp,
1050 bool IsLeafFunc) {
1052 bool IsEntryBB = &BB == &F.getEntryBlock();
1053 DebugLoc EntryLoc;
1054 if (IsEntryBB) {
1055 if (auto SP = F.getSubprogram())
1056 EntryLoc = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
1057 // Keep static allocas and llvm.localescape calls in the entry block. Even
1058 // if we aren't splitting the block, it's nice for allocas to be before
1059 // calls.
1060 IP = PrepareToSplitEntryBlock(BB, IP);
1061 }
1062
1063 InstrumentationIRBuilder IRB(&*IP);
1064 if (EntryLoc)
1065 IRB.SetCurrentDebugLocation(EntryLoc);
1066 if (Options.TracePC || (IsEntryBB && Options.TracePCEntryExit)) {
1067 FunctionCallee Callee = IsEntryBB && Options.TracePCEntryExit
1068 ? SanCovTracePCEntry
1069 : SanCovTracePC;
1070 createRuntimeCall(IRB, Callee)
1071 ->setCannotMerge(); // gets the PC using GET_CALLER_PC.
1072 }
1073 if (Options.TracePCGuard) {
1074 auto GuardPtr = IRB.CreateConstInBoundsGEP2_64(
1075 FunctionGuardArray->getValueType(), FunctionGuardArray, 0, Idx);
1076 if (Options.GatedCallbacks) {
1077 Instruction *I = &*IP;
1078 auto GateBranch = CreateGateBranch(F, FunctionGateCmp, I);
1079 IRBuilder<> GateIRB(GateBranch);
1080 createRuntimeCall(GateIRB, SanCovTracePCGuard, GuardPtr)
1081 ->setCannotMerge();
1082 } else {
1083 createRuntimeCall(IRB, SanCovTracePCGuard, GuardPtr)->setCannotMerge();
1084 }
1085 }
1086 if (Options.Inline8bitCounters) {
1087 auto CounterPtr = IRB.CreateGEP(
1088 Function8bitCounterArray->getValueType(), Function8bitCounterArray,
1089 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
1090 auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
1091 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
1092 auto Store = IRB.CreateStore(Inc, CounterPtr);
1093 Load->setNoSanitizeMetadata();
1094 Store->setNoSanitizeMetadata();
1095 }
1096 if (Options.InlineBoolFlag) {
1097 auto FlagPtr = IRB.CreateGEP(
1098 FunctionBoolArray->getValueType(), FunctionBoolArray,
1099 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
1100 auto Load = IRB.CreateLoad(Int1Ty, FlagPtr);
1101 auto ThenTerm = SplitBlockAndInsertIfThen(
1102 IRB.CreateIsNull(Load), &*IP, false,
1104 InstrumentationIRBuilder ThenIRB(ThenTerm);
1105 auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr);
1106 if (EntryLoc)
1107 Store->setDebugLoc(EntryLoc);
1108 Load->setNoSanitizeMetadata();
1109 Store->setNoSanitizeMetadata();
1110 }
1111 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
1112 Module *M = F.getParent();
1113 const DataLayout &DL = M->getDataLayout();
1114
1115 if (Options.StackDepthCallbackMin) {
1116 // In callback mode, only add call when stack depth reaches minimum.
1117 int EstimatedStackSize = 0;
1118 // If dynamic alloca found, always add call.
1119 bool HasDynamicAlloc = false;
1120 // Find an insertion point after last "alloca".
1121 llvm::Instruction *InsertBefore = nullptr;
1122
1123 // Examine all allocas in the basic block. since we're too early
1124 // to have results from Intrinsic::frameaddress, we have to manually
1125 // estimate the stack size.
1126 for (auto &I : BB) {
1127 if (auto *AI = dyn_cast<AllocaInst>(&I)) {
1128 // Move potential insertion point past the "alloca".
1129 InsertBefore = AI->getNextNode();
1130
1131 // Make an estimate on the stack usage.
1132 if (auto AllocaSize = AI->getAllocationSize(DL)) {
1133 if (AllocaSize->isFixed())
1134 EstimatedStackSize += AllocaSize->getFixedValue();
1135 else
1136 HasDynamicAlloc = true;
1137 } else {
1138 HasDynamicAlloc = true;
1139 }
1140 }
1141 }
1142
1143 if (HasDynamicAlloc ||
1144 EstimatedStackSize >= Options.StackDepthCallbackMin) {
1145 if (InsertBefore)
1146 IRB.SetInsertPoint(InsertBefore);
1147 auto Call = createRuntimeCall(IRB, SanCovStackDepthCallback);
1148 if (EntryLoc)
1149 Call->setDebugLoc(EntryLoc);
1151 }
1152 } else {
1153 // Check stack depth. If it's the deepest so far, record it.
1154 auto FrameAddrPtr = IRB.CreateIntrinsic(
1155 Intrinsic::frameaddress, IRB.getPtrTy(DL.getAllocaAddrSpace()),
1156 {Constant::getNullValue(Int32Ty)});
1157 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
1158 auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
1159 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
1160 auto ThenTerm = SplitBlockAndInsertIfThen(
1161 IsStackLower, &*IP, false,
1163 InstrumentationIRBuilder ThenIRB(ThenTerm);
1164 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
1165 if (EntryLoc)
1166 Store->setDebugLoc(EntryLoc);
1167 LowestStack->setNoSanitizeMetadata();
1168 Store->setNoSanitizeMetadata();
1169 }
1170 }
1171}
1172
1173std::string
1174ModuleSanitizerCoverage::getSectionName(const std::string &Section) const {
1175 if (TargetTriple.isOSBinFormatCOFF()) {
1176 if (Section == SanCovCountersSectionName)
1177 return ".SCOV$CM";
1178 if (Section == SanCovBoolFlagSectionName)
1179 return ".SCOV$BM";
1180 if (Section == SanCovPCsSectionName)
1181 return ".SCOVP$M";
1182 return ".SCOV$GM"; // For SanCovGuardsSectionName.
1183 }
1184 if (TargetTriple.isOSBinFormatMachO())
1185 return "__DATA,__" + Section;
1186 return "__" + Section;
1187}
1188
1189std::string
1190ModuleSanitizerCoverage::getSectionStart(const std::string &Section) const {
1191 if (TargetTriple.isOSBinFormatMachO())
1192 return "\1section$start$__DATA$__" + Section;
1193 return "__start___" + Section;
1194}
1195
1196std::string
1197ModuleSanitizerCoverage::getSectionEnd(const std::string &Section) const {
1198 if (TargetTriple.isOSBinFormatMachO())
1199 return "\1section$end$__DATA$__" + Section;
1200 return "__stop___" + Section;
1201}
1202
1203void ModuleSanitizerCoverage::createFunctionControlFlow(Function &F) {
1205 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
1206
1207 for (auto &BB : F) {
1208 // blockaddress can not be used on function's entry block.
1209 if (&BB == &F.getEntryBlock())
1210 CFs.push_back((Constant *)IRB.CreatePointerCast(&F, PtrTy));
1211 else
1212 CFs.push_back(
1213 (Constant *)IRB.CreatePointerCast(BlockAddress::get(&BB), PtrTy));
1214
1215 for (auto SuccBB : successors(&BB)) {
1216 assert(SuccBB != &F.getEntryBlock());
1217 CFs.push_back(
1218 (Constant *)IRB.CreatePointerCast(BlockAddress::get(SuccBB), PtrTy));
1219 }
1220
1222
1223 for (auto &Inst : BB) {
1224 if (CallBase *CB = dyn_cast<CallBase>(&Inst)) {
1225 if (CB->isIndirectCall()) {
1226 // TODO(navidem): handle indirect calls, for now mark its existence.
1228 ConstantInt::getAllOnesValue(IntptrTy), PtrTy));
1229 } else {
1230 auto CalledF = CB->getCalledFunction();
1231 if (CalledF && !CalledF->isIntrinsic())
1232 CFs.push_back((Constant *)IRB.CreatePointerCast(CalledF, PtrTy));
1233 }
1234 }
1235 }
1236
1238 }
1239
1240 FunctionCFsArray = CreateFunctionLocalArrayInSection(CFs.size(), F, PtrTy,
1242 FunctionCFsArray->setInitializer(
1243 ConstantArray::get(ArrayType::get(PtrTy, CFs.size()), CFs));
1244 FunctionCFsArray->setConstant(true);
1245}
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