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"
19#include "llvm/IR/Constant.h"
20#include "llvm/IR/Constants.h"
21#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/Dominators.h"
24#include "llvm/IR/Function.h"
26#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/MDBuilder.h"
31#include "llvm/IR/Module.h"
32#include "llvm/IR/Type.h"
40
41using namespace llvm;
42
43#define DEBUG_TYPE "sancov"
44
45const char SanCovTracePCIndirName[] = "__sanitizer_cov_trace_pc_indir";
46const char SanCovTracePCName[] = "__sanitizer_cov_trace_pc";
47const char SanCovTracePCEntryName[] = "__sanitizer_cov_trace_pc_entry";
48const char SanCovTracePCExitName[] = "__sanitizer_cov_trace_pc_exit";
49const char SanCovTraceCmp1[] = "__sanitizer_cov_trace_cmp1";
50const char SanCovTraceCmp2[] = "__sanitizer_cov_trace_cmp2";
51const char SanCovTraceCmp4[] = "__sanitizer_cov_trace_cmp4";
52const char SanCovTraceCmp8[] = "__sanitizer_cov_trace_cmp8";
53const char SanCovTraceConstCmp1[] = "__sanitizer_cov_trace_const_cmp1";
54const char SanCovTraceConstCmp2[] = "__sanitizer_cov_trace_const_cmp2";
55const char SanCovTraceConstCmp4[] = "__sanitizer_cov_trace_const_cmp4";
56const char SanCovTraceConstCmp8[] = "__sanitizer_cov_trace_const_cmp8";
57const char SanCovLoad1[] = "__sanitizer_cov_load1";
58const char SanCovLoad2[] = "__sanitizer_cov_load2";
59const char SanCovLoad4[] = "__sanitizer_cov_load4";
60const char SanCovLoad8[] = "__sanitizer_cov_load8";
61const char SanCovLoad16[] = "__sanitizer_cov_load16";
62const char SanCovStore1[] = "__sanitizer_cov_store1";
63const char SanCovStore2[] = "__sanitizer_cov_store2";
64const char SanCovStore4[] = "__sanitizer_cov_store4";
65const char SanCovStore8[] = "__sanitizer_cov_store8";
66const char SanCovStore16[] = "__sanitizer_cov_store16";
67const char SanCovTraceDiv4[] = "__sanitizer_cov_trace_div4";
68const char SanCovTraceDiv8[] = "__sanitizer_cov_trace_div8";
69const char SanCovTraceGep[] = "__sanitizer_cov_trace_gep";
70const char SanCovTraceSwitchName[] = "__sanitizer_cov_trace_switch";
72 "sancov.module_ctor_trace_pc_guard";
74 "sancov.module_ctor_8bit_counters";
75const char SanCovModuleCtorBoolFlagName[] = "sancov.module_ctor_bool_flag";
77
78const char SanCovTracePCGuardName[] = "__sanitizer_cov_trace_pc_guard";
79const char SanCovTracePCGuardInitName[] = "__sanitizer_cov_trace_pc_guard_init";
80const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init";
81const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init";
82const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init";
83const char SanCovCFsInitName[] = "__sanitizer_cov_cfs_init";
84
85const char SanCovGuardsSectionName[] = "sancov_guards";
86const char SanCovCountersSectionName[] = "sancov_cntrs";
87const char SanCovBoolFlagSectionName[] = "sancov_bools";
88const char SanCovPCsSectionName[] = "sancov_pcs";
89const char SanCovCFsSectionName[] = "sancov_cfs";
90const char SanCovCallbackGateSectionName[] = "sancov_gate";
91
92const char SanCovStackDepthCallbackName[] = "__sanitizer_cov_stack_depth";
93const char SanCovLowestStackName[] = "__sancov_lowest_stack";
94const char SanCovCallbackGateName[] = "__sancov_should_track";
95
96namespace {
97
98SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
100 switch (LegacyCoverageLevel) {
101 case 0:
103 break;
104 case 1:
106 break;
107 case 2:
109 break;
110 case 3:
112 break;
113 case 4:
115 Res.IndirectCalls = true;
116 break;
117 }
118 return Res;
119}
120
121SanitizerCoverageOptions overrideFromCL(const InstrumentationOptions &Opts,
123 // Sets CoverageType and IndirectCalls.
124 SanitizerCoverageOptions CLOpts = getOptions(Opts.sanitizer_coverage_level);
125 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
126 Options.IndirectCalls |= CLOpts.IndirectCalls;
127 Options.TraceCmp |= Opts.sanitizer_coverage_trace_compares;
128 Options.TraceDiv |= Opts.sanitizer_coverage_trace_divs;
129 Options.TraceGep |= Opts.sanitizer_coverage_trace_geps;
130 Options.TracePC |= Opts.sanitizer_coverage_trace_pc;
131 Options.TracePCEntryExit |= Opts.sanitizer_coverage_trace_pc_entry_exit;
132 Options.TracePCGuard |= Opts.sanitizer_coverage_trace_pc_guard;
133 Options.Inline8bitCounters |= Opts.sanitizer_coverage_inline_8bit_counters;
134 Options.InlineBoolFlag |= Opts.sanitizer_coverage_inline_bool_flag;
135 Options.PCTable |= Opts.sanitizer_coverage_pc_table;
136 Options.NoPrune |= !Opts.sanitizer_coverage_prune_blocks;
137 Options.StackDepth |= Opts.sanitizer_coverage_stack_depth;
138 Options.StackDepthCallbackMin =
139 std::max(Options.StackDepthCallbackMin,
140 Opts.sanitizer_coverage_stack_depth_callback_min);
141 Options.TraceLoads |= Opts.sanitizer_coverage_trace_loads;
142 Options.TraceStores |= Opts.sanitizer_coverage_trace_stores;
143 Options.GatedCallbacks |= Opts.sanitizer_coverage_gated_trace_callbacks;
144 if (!Options.TracePCGuard && !Options.TracePC && !Options.TracePCEntryExit &&
145 !Options.Inline8bitCounters && !Options.StackDepth &&
146 !Options.InlineBoolFlag && !Options.TraceLoads && !Options.TraceStores)
147 Options.TracePCGuard = true; // TracePCGuard is default.
148 Options.CollectControlFlow |= Opts.sanitizer_coverage_control_flow;
149 return Options;
150}
151
152class ModuleSanitizerCoverage {
153public:
154 using DomTreeCallback = function_ref<const DominatorTree &(Function &F)>;
155 using PostDomTreeCallback =
157
158 ModuleSanitizerCoverage(const InstrumentationOptions &Opts, Module &M,
159 DomTreeCallback DTCallback,
160 PostDomTreeCallback PDTCallback,
162 const SpecialCaseList *Allowlist,
163 const SpecialCaseList *Blocklist)
164 : Opts(Opts), M(M), DTCallback(DTCallback), PDTCallback(PDTCallback),
165 Options(Options), Allowlist(Allowlist), Blocklist(Blocklist) {}
166
167 bool instrumentModule();
168
169private:
170 void createFunctionControlFlow(Function &F);
171 void instrumentFunction(Function &F);
172 void InjectCoverageForIndirectCalls(Function &F,
173 ArrayRef<Instruction *> IndirCalls);
174 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets,
175 Value *&FunctionGateCmp);
176 void InjectTraceForDiv(Function &F,
177 ArrayRef<BinaryOperator *> DivTraceTargets);
178 void InjectTraceForGep(Function &F,
179 ArrayRef<GetElementPtrInst *> GepTraceTargets);
180 void InjectTraceForLoadsAndStores(Function &F, ArrayRef<LoadInst *> Loads,
181 ArrayRef<StoreInst *> Stores);
182 void InjectTraceForExits(Function &F);
183 void InjectTraceForSwitch(Function &F,
184 ArrayRef<Instruction *> SwitchTraceTargets,
185 Value *&FunctionGateCmp);
186 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
187 Value *&FunctionGateCmp, bool IsLeafFunc);
188 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
189 Function &F, Type *Ty,
190 const char *Section);
191 GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
192 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
193 Instruction *CreateGateBranch(Function &F, Value *&FunctionGateCmp,
194 Instruction *I);
195 Value *CreateFunctionLocalGateCmp(IRBuilder<> &IRB);
196 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
197 Value *&FunctionGateCmp, bool IsLeafFunc);
198 Function *CreateInitCallsForSections(Module &M, const char *CtorName,
199 const char *InitFunctionName, Type *Ty,
200 const char *Section);
201 std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
202 Type *Ty);
203
204 std::string getSectionName(const std::string &Section) const;
205 std::string getSectionStart(const std::string &Section) const;
206 std::string getSectionEnd(const std::string &Section) const;
207
208 const InstrumentationOptions &Opts;
209 Module &M;
210 DomTreeCallback DTCallback;
211 PostDomTreeCallback PDTCallback;
212
213 FunctionCallee SanCovStackDepthCallback;
214 FunctionCallee SanCovTracePCIndir;
215 FunctionCallee SanCovTracePC, SanCovTracePCGuard;
216 FunctionCallee SanCovTracePCEntry, SanCovTracePCExit;
217 std::array<FunctionCallee, 4> SanCovTraceCmpFunction;
218 std::array<FunctionCallee, 4> SanCovTraceConstCmpFunction;
219 std::array<FunctionCallee, 5> SanCovLoadFunction;
220 std::array<FunctionCallee, 5> SanCovStoreFunction;
221 std::array<FunctionCallee, 2> SanCovTraceDivFunction;
222 FunctionCallee SanCovTraceGepFunction;
223 FunctionCallee SanCovTraceSwitchFunction;
224 GlobalVariable *SanCovLowestStack;
225 GlobalVariable *SanCovCallbackGate;
226 Type *PtrTy, *IntptrTy, *Int64Ty, *Int32Ty, *Int16Ty, *Int8Ty, *Int1Ty;
227 Module *CurModule;
228 Triple TargetTriple;
229 LLVMContext *C;
230 const DataLayout *DL;
231
232 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
233 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
234 GlobalVariable *FunctionBoolArray; // for inline-bool-flag.
235 GlobalVariable *FunctionPCsArray; // for pc-table.
236 GlobalVariable *FunctionCFsArray; // for control flow table
237 SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
238 SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
239
241
242 const SpecialCaseList *Allowlist;
243 const SpecialCaseList *Blocklist;
244};
245} // namespace
246
249 const std::vector<std::string> &AllowlistFiles,
250 const std::vector<std::string> &BlocklistFiles)
251 : Options(std::move(Options)),
252 VFS(VFS ? std::move(VFS) : vfs::getRealFileSystem()) {
253 if (AllowlistFiles.size() > 0)
254 Allowlist = SpecialCaseList::createOrDie(AllowlistFiles, *this->VFS);
255 if (BlocklistFiles.size() > 0)
256 Blocklist = SpecialCaseList::createOrDie(BlocklistFiles, *this->VFS);
257}
258
261 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
262 auto DTCallback = [&FAM](Function &F) -> const DominatorTree & {
263 return FAM.getResult<DominatorTreeAnalysis>(F);
264 };
265 auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree & {
266 return FAM.getResult<PostDominatorTreeAnalysis>(F);
267 };
268 const InstrumentationOptions &Opts =
269 M.getContext().getLibraryOptions().get<InstrumentationOptions>();
270 ModuleSanitizerCoverage ModuleSancov(Opts, M, DTCallback, PDTCallback,
271 overrideFromCL(Opts, Options),
272 Allowlist.get(), Blocklist.get());
273 if (!ModuleSancov.instrumentModule())
274 return PreservedAnalyses::all();
275
277 // GlobalsAA is considered stateless and does not get invalidated unless
278 // explicitly invalidated; PreservedAnalyses::none() is not enough. Sanitizers
279 // make changes that require GlobalsAA to be invalidated.
280 PA.abandon<GlobalsAA>();
281 return PA;
282}
283
284std::pair<Value *, Value *>
285ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section,
286 Type *Ty) {
287 // Use ExternalWeak so that if all sections are discarded due to section
288 // garbage collection, the linker will not report undefined symbol errors.
289 // Windows defines the start/stop symbols in compiler-rt so no need for
290 // ExternalWeak.
291 GlobalValue::LinkageTypes Linkage = TargetTriple.isOSBinFormatCOFF()
294 GlobalVariable *SecStart = new GlobalVariable(M, Ty, false, Linkage, nullptr,
295 getSectionStart(Section));
297 GlobalVariable *SecEnd = new GlobalVariable(M, Ty, false, Linkage, nullptr,
298 getSectionEnd(Section));
300 if (!TargetTriple.isOSBinFormatCOFF())
301 return std::make_pair(SecStart, SecEnd);
302
303 // Account for the fact that on windows-msvc __start_* symbols actually
304 // point to a uint64_t before the start of the array.
306 SecStart, ConstantInt::get(IntptrTy, sizeof(uint64_t)));
307 return std::make_pair(GEP, SecEnd);
308}
309
310Function *ModuleSanitizerCoverage::CreateInitCallsForSections(
311 Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
312 const char *Section) {
313 if (Opts.sanitizer_coverage_drop_ctors)
314 return nullptr;
315 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
316 auto SecStart = SecStartEnd.first;
317 auto SecEnd = SecStartEnd.second;
318 Function *CtorFunc;
319 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
320 M, CtorName, InitFunctionName, {PtrTy, PtrTy}, {SecStart, SecEnd});
321 assert(CtorFunc->getName() == CtorName);
322
323 if (TargetTriple.supportsCOMDAT()) {
324 // Use comdat to dedup CtorFunc.
325 CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
326 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
327 } else {
329 }
330
331 if (TargetTriple.isOSBinFormatCOFF()) {
332 // In COFF files, if the contructors are set as COMDAT (they are because
333 // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
334 // functions and data) is used, the constructors get stripped. To prevent
335 // this, give the constructors weak ODR linkage and ensure the linker knows
336 // to include the sancov constructor. This way the linker can deduplicate
337 // the constructors but always leave one copy.
339 }
340 return CtorFunc;
341}
342
343bool ModuleSanitizerCoverage::instrumentModule() {
345 return false;
346 if (Allowlist &&
347 !Allowlist->inSection("coverage", "src", M.getSourceFileName()))
348 return false;
349 if (Blocklist &&
350 Blocklist->inSection("coverage", "src", M.getSourceFileName()))
351 return false;
352 C = &(M.getContext());
353 DL = &M.getDataLayout();
354 CurModule = &M;
355 TargetTriple = M.getTargetTriple();
356 FunctionGuardArray = nullptr;
357 Function8bitCounterArray = nullptr;
358 FunctionBoolArray = nullptr;
359 FunctionPCsArray = nullptr;
360 FunctionCFsArray = nullptr;
361 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
362 PtrTy = PointerType::getUnqual(*C);
363 Type *VoidTy = Type::getVoidTy(*C);
364 IRBuilder<> IRB(M);
365 Int64Ty = IRB.getInt64Ty();
366 Int32Ty = IRB.getInt32Ty();
367 Int16Ty = IRB.getInt16Ty();
368 Int8Ty = IRB.getInt8Ty();
369 Int1Ty = IRB.getInt1Ty();
370
371 SanCovTracePCIndir =
372 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
373 // Make sure smaller parameters are zero-extended to i64 if required by the
374 // target ABI.
375 AttributeList SanCovTraceCmpZeroExtAL;
376 SanCovTraceCmpZeroExtAL =
377 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
378 SanCovTraceCmpZeroExtAL =
379 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
380
381 SanCovTraceCmpFunction[0] =
382 M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
383 IRB.getInt8Ty(), IRB.getInt8Ty());
384 SanCovTraceCmpFunction[1] =
385 M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
386 IRB.getInt16Ty(), IRB.getInt16Ty());
387 SanCovTraceCmpFunction[2] =
388 M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
389 IRB.getInt32Ty(), IRB.getInt32Ty());
390 SanCovTraceCmpFunction[3] =
391 M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
392
393 SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
394 SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
395 SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
396 SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
397 SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
398 SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
399 SanCovTraceConstCmpFunction[3] =
400 M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
401
402 // Loads.
403 SanCovLoadFunction[0] = M.getOrInsertFunction(SanCovLoad1, VoidTy, PtrTy);
404 SanCovLoadFunction[1] = M.getOrInsertFunction(SanCovLoad2, VoidTy, PtrTy);
405 SanCovLoadFunction[2] = M.getOrInsertFunction(SanCovLoad4, VoidTy, PtrTy);
406 SanCovLoadFunction[3] = M.getOrInsertFunction(SanCovLoad8, VoidTy, PtrTy);
407 SanCovLoadFunction[4] = M.getOrInsertFunction(SanCovLoad16, VoidTy, PtrTy);
408 // Stores.
409 SanCovStoreFunction[0] = M.getOrInsertFunction(SanCovStore1, VoidTy, PtrTy);
410 SanCovStoreFunction[1] = M.getOrInsertFunction(SanCovStore2, VoidTy, PtrTy);
411 SanCovStoreFunction[2] = M.getOrInsertFunction(SanCovStore4, VoidTy, PtrTy);
412 SanCovStoreFunction[3] = M.getOrInsertFunction(SanCovStore8, VoidTy, PtrTy);
413 SanCovStoreFunction[4] = M.getOrInsertFunction(SanCovStore16, VoidTy, PtrTy);
414
415 {
416 AttributeList AL;
417 AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
418 SanCovTraceDivFunction[0] =
419 M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
420 }
421 SanCovTraceDivFunction[1] =
422 M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
423 SanCovTraceGepFunction =
424 M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
425 SanCovTraceSwitchFunction =
426 M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, PtrTy);
427
428 SanCovLowestStack = M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
429 if (SanCovLowestStack->getValueType() != IntptrTy) {
430 C->emitError(StringRef("'") + SanCovLowestStackName +
431 "' should not be declared by the user");
432 return true;
433 }
434 SanCovLowestStack->setThreadLocalMode(
436 if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
437 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
438
439 if (Options.GatedCallbacks) {
440 if (!Options.TracePCGuard && !Options.TraceCmp) {
441 C->emitError("'sanitizer-coverage-gated-trace-callbacks' is only "
442 "supported with trace-pc-guard or trace-cmp");
443 return true;
444 }
445
446 SanCovCallbackGate = cast<GlobalVariable>(
447 M.getOrInsertGlobal(SanCovCallbackGateName, Int64Ty));
448 SanCovCallbackGate->setSection(
450 SanCovCallbackGate->setInitializer(Constant::getNullValue(Int64Ty));
451 SanCovCallbackGate->setLinkage(GlobalVariable::LinkOnceAnyLinkage);
452 SanCovCallbackGate->setVisibility(GlobalVariable::HiddenVisibility);
453 appendToCompilerUsed(M, SanCovCallbackGate);
454 }
455
456 SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
457 SanCovTracePCEntry = M.getOrInsertFunction(SanCovTracePCEntryName, VoidTy);
458 SanCovTracePCExit = M.getOrInsertFunction(SanCovTracePCExitName, VoidTy);
459 SanCovTracePCGuard =
460 M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, PtrTy);
461
462 SanCovStackDepthCallback =
463 M.getOrInsertFunction(SanCovStackDepthCallbackName, VoidTy);
464
465 for (auto &F : M)
466 instrumentFunction(F);
467
468 Function *Ctor = nullptr;
469
470 if (FunctionGuardArray)
471 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
474 if (Function8bitCounterArray)
475 Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
478 if (FunctionBoolArray) {
479 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName,
482 }
483 if (Ctor && Options.PCTable) {
484 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrTy);
485 FunctionCallee InitFunction =
487 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
488 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
489 }
490
491 if (Ctor && Options.CollectControlFlow) {
492 auto SecStartEnd = CreateSecStartEnd(M, SanCovCFsSectionName, IntptrTy);
493 FunctionCallee InitFunction =
495 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
496 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
497 }
498
499 appendToUsed(M, GlobalsToAppendToUsed);
500 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
501 return true;
502}
503
504// True if block has successors and it dominates all of them.
505static bool isFullDominator(const BasicBlock *BB, const DominatorTree &DT) {
506 if (succ_empty(BB))
507 return false;
508
509 return llvm::all_of(successors(BB), [&](const BasicBlock *SUCC) {
510 return DT.dominates(BB, SUCC);
511 });
512}
513
514// True if block has predecessors and it postdominates all of them.
515static bool isFullPostDominator(const BasicBlock *BB,
516 const PostDominatorTree &PDT) {
517 if (pred_empty(BB))
518 return false;
519
520 return llvm::all_of(predecessors(BB), [&](const BasicBlock *PRED) {
521 return PDT.dominates(BB, PRED);
522 });
523}
524
525static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
526 const DominatorTree &DT,
527 const PostDominatorTree &PDT,
529 // Don't insert coverage for blocks containing nothing but unreachable: we
530 // will never call __sanitizer_cov() for them, so counting them in
531 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
532 // percentage. Also, unreachable instructions frequently have no debug
533 // locations.
535 return false;
536
537 // Don't insert coverage into blocks without a valid insertion point
538 // (catchswitch blocks).
539 if (BB->getFirstInsertionPt() == BB->end())
540 return false;
541
542 if (Options.NoPrune || &F.getEntryBlock() == BB)
543 return true;
544
546 &F.getEntryBlock() != BB)
547 return false;
548
549 // Do not instrument full dominators, or full post-dominators with multiple
550 // predecessors.
551 return !isFullDominator(BB, DT) &&
552 !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
553}
554
555// Returns true iff From->To is a backedge.
556// A twist here is that we treat From->To as a backedge if
557// * To dominates From or
558// * To->UniqueSuccessor dominates From
559static bool IsBackEdge(BasicBlock *From, BasicBlock *To,
560 const DominatorTree &DT) {
561 if (DT.dominates(To, From))
562 return true;
563 if (auto Next = To->getUniqueSuccessor())
564 if (DT.dominates(Next, From))
565 return true;
566 return false;
567}
568
569// Prunes uninteresting Cmp instrumentation:
570// * CMP instructions that feed into loop backedge branch.
571//
572// Note that Cmp pruning is controlled by the same flag as the
573// BB pruning.
574static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree &DT,
576 if (!Options.NoPrune)
577 if (CMP->hasOneUse())
578 if (auto BR = dyn_cast<CondBrInst>(CMP->user_back()))
579 for (BasicBlock *B : BR->successors())
580 if (IsBackEdge(BR->getParent(), B, DT))
581 return false;
582 return true;
583}
584
585void ModuleSanitizerCoverage::instrumentFunction(Function &F) {
586 if (F.empty())
587 return;
588 if (F.getName().contains(".module_ctor"))
589 return; // Should not instrument sanitizer init functions.
590 if (F.getName().starts_with("__sanitizer_"))
591 return; // Don't instrument __sanitizer_* callbacks.
592 // Don't touch available_externally functions, their actual body is elewhere.
593 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
594 return;
595 // Don't instrument MSVC CRT configuration helpers. They may run before normal
596 // initialization.
597 if (F.getName() == "__local_stdio_printf_options" ||
598 F.getName() == "__local_stdio_scanf_options")
599 return;
600 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
601 return;
602 // Don't instrument functions using SEH for now. Splitting basic blocks like
603 // we do for coverage breaks WinEHPrepare.
604 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
605 if (F.hasPersonalityFn() &&
607 return;
608 if (Allowlist && !Allowlist->inSection("coverage", "fun", F.getName()))
609 return;
610 if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName()))
611 return;
612 // Do not apply any instrumentation for naked functions.
613 if (F.hasFnAttribute(Attribute::Naked))
614 return;
615 if (F.hasFnAttribute(Attribute::NoSanitizeCoverage))
616 return;
617 if (F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation))
618 return;
619 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge) {
621 F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
622 }
624 SmallVector<BasicBlock *, 16> BlocksToInstrument;
625 SmallVector<Instruction *, 8> CmpTraceTargets;
626 SmallVector<Instruction *, 8> SwitchTraceTargets;
627 SmallVector<BinaryOperator *, 8> DivTraceTargets;
631
632 const DominatorTree &DT = DTCallback(F);
633 const PostDominatorTree &PDT = PDTCallback(F);
634 bool IsLeafFunc = true;
635
636 for (auto &BB : F) {
637 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
638 BlocksToInstrument.push_back(&BB);
639 for (auto &Inst : BB) {
640 if (Options.IndirectCalls) {
641 CallBase *CB = dyn_cast<CallBase>(&Inst);
642 if (CB && CB->isIndirectCall())
643 IndirCalls.push_back(&Inst);
644 }
645 if (Options.TraceCmp) {
646 if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
647 if (IsInterestingCmp(CMP, DT, Options))
648 CmpTraceTargets.push_back(&Inst);
649 if (isa<SwitchInst>(&Inst))
650 SwitchTraceTargets.push_back(&Inst);
651 }
652 if (Options.TraceDiv)
654 if (BO->getOpcode() == Instruction::SDiv ||
655 BO->getOpcode() == Instruction::UDiv)
656 DivTraceTargets.push_back(BO);
657 if (Options.TraceGep)
659 GepTraceTargets.push_back(GEP);
660 if (Options.TraceLoads)
661 if (LoadInst *LI = dyn_cast<LoadInst>(&Inst))
662 Loads.push_back(LI);
663 if (Options.TraceStores)
664 if (StoreInst *SI = dyn_cast<StoreInst>(&Inst))
665 Stores.push_back(SI);
666 if (Options.StackDepth)
667 if (isa<InvokeInst>(Inst) ||
668 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
669 IsLeafFunc = false;
670 }
671 }
672
673 if (Options.CollectControlFlow)
674 createFunctionControlFlow(F);
675
676 Value *FunctionGateCmp = nullptr;
677 InjectCoverage(F, BlocksToInstrument, FunctionGateCmp, IsLeafFunc);
678 InjectCoverageForIndirectCalls(F, IndirCalls);
679 InjectTraceForCmp(F, CmpTraceTargets, FunctionGateCmp);
680 InjectTraceForSwitch(F, SwitchTraceTargets, FunctionGateCmp);
681 InjectTraceForDiv(F, DivTraceTargets);
682 InjectTraceForGep(F, GepTraceTargets);
683 InjectTraceForLoadsAndStores(F, Loads, Stores);
684
685 if (Options.TracePCEntryExit)
686 InjectTraceForExits(F);
687}
688
689GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection(
690 size_t NumElements, Function &F, Type *Ty, const char *Section) {
691 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
692 auto Array = new GlobalVariable(
693 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
694 Constant::getNullValue(ArrayTy), "__sancov_gen_");
695
696 // sancov_pcs parallels the other arrays, so they must be retained or
697 // discarded together. Put them in F's comdat to tie them to F for linker GC
698 // benefit. Outside ELF (nodeduplicate), a new comdat for an interposable F
699 // could prevail over a strong definition (COFF: the weak external becomes a
700 // COMDAT definition; Wasm: comdats deduplicate first). noipa doesn't affect
701 // symbol resolution.
702 if (TargetTriple.supportsCOMDAT() &&
703 (F.hasComdat() || TargetTriple.isOSBinFormatELF() ||
704 !F.isInterposable(/*CheckNoIPA=*/false)))
705 if (auto Comdat = getOrCreateFunctionComdat(F, TargetTriple))
706 Array->setComdat(Comdat);
707 Array->setSection(getSectionName(Section));
708 Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedValue()));
709
710 // Optimizers (e.g. GlobalOpt/ConstantMerge) may not discard the arrays as a
711 // unit, so retain them in the compiler; without a comdat, in the linker too.
712 if (Array->hasComdat())
713 GlobalsToAppendToCompilerUsed.push_back(Array);
714 else
715 GlobalsToAppendToUsed.push_back(Array);
716
717 return Array;
718}
719
721ModuleSanitizerCoverage::CreatePCArray(Function &F,
722 ArrayRef<BasicBlock *> AllBlocks) {
723 size_t N = AllBlocks.size();
724 assert(N);
726 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
727 for (size_t i = 0; i < N; i++) {
728 if (&F.getEntryBlock() == AllBlocks[i]) {
729 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, PtrTy));
730 PCs.push_back(
731 (Constant *)IRB.CreateIntToPtr(ConstantInt::get(IntptrTy, 1), PtrTy));
732 } else {
733 PCs.push_back((Constant *)IRB.CreatePointerCast(
734 BlockAddress::get(AllBlocks[i]), PtrTy));
736 }
737 }
738 auto *PCArray =
739 CreateFunctionLocalArrayInSection(N * 2, F, PtrTy, SanCovPCsSectionName);
740 PCArray->setInitializer(
741 ConstantArray::get(ArrayType::get(PtrTy, N * 2), PCs));
742 PCArray->setConstant(true);
743
744 return PCArray;
745}
746
747void ModuleSanitizerCoverage::CreateFunctionLocalArrays(
748 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
749 if (Options.TracePCGuard)
750 FunctionGuardArray = CreateFunctionLocalArrayInSection(
751 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
752
753 if (Options.Inline8bitCounters)
754 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
755 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
756 if (Options.InlineBoolFlag)
757 FunctionBoolArray = CreateFunctionLocalArrayInSection(
758 AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName);
759
760 if (Options.PCTable)
761 FunctionPCsArray = CreatePCArray(F, AllBlocks);
762}
763
764Value *ModuleSanitizerCoverage::CreateFunctionLocalGateCmp(IRBuilder<> &IRB) {
765 auto Load = IRB.CreateLoad(Int64Ty, SanCovCallbackGate);
766 Load->setNoSanitizeMetadata();
767 auto Cmp = IRB.CreateIsNotNull(Load);
768 Cmp->setName("sancov gate cmp");
769 return Cmp;
770}
771
772Instruction *ModuleSanitizerCoverage::CreateGateBranch(Function &F,
773 Value *&FunctionGateCmp,
774 Instruction *IP) {
775 if (!FunctionGateCmp) {
776 // Create this in the entry block
777 BasicBlock &BB = F.getEntryBlock();
779 IP = PrepareToSplitEntryBlock(BB, IP);
780 IRBuilder<> EntryIRB(&*IP);
781 FunctionGateCmp = CreateFunctionLocalGateCmp(EntryIRB);
782 }
783 // Set the branch weights in order to minimize the price paid when the
784 // gate is turned off, allowing the default enablement of this
785 // instrumentation with as little of a performance cost as possible
786 auto Weights = MDBuilder(*C).createBranchWeights(1, 100000);
787 return SplitBlockAndInsertIfThen(FunctionGateCmp, IP, false, Weights);
788}
789
790bool ModuleSanitizerCoverage::InjectCoverage(Function &F,
791 ArrayRef<BasicBlock *> AllBlocks,
792 Value *&FunctionGateCmp,
793 bool IsLeafFunc) {
794 if (AllBlocks.empty())
795 return false;
796 CreateFunctionLocalArrays(F, AllBlocks);
797 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
798 InjectCoverageAtBlock(F, *AllBlocks[i], i, FunctionGateCmp, IsLeafFunc);
799
800 return true;
801}
802
803// On every indirect call we call a run-time function
804// __sanitizer_cov_indir_call* with two parameters:
805// - callee address,
806// - global cache array that contains CacheSize pointers (zero-initialized).
807// The cache is used to speed up recording the caller-callee pairs.
808// The address of the caller is passed implicitly via caller PC.
809// CacheSize is encoded in the name of the run-time function.
810void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls(
811 Function &F, ArrayRef<Instruction *> IndirCalls) {
812 if (IndirCalls.empty())
813 return;
814 assert(Options.TracePC || Options.TracePCEntryExit || Options.TracePCGuard ||
815 Options.Inline8bitCounters || Options.InlineBoolFlag);
816 for (auto *I : IndirCalls) {
818 CallBase &CB = cast<CallBase>(*I);
820 if (isa<InlineAsm>(Callee))
821 continue;
822 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
823 }
824}
825
826// For every switch statement we insert a call:
827// __sanitizer_cov_trace_switch(CondValue,
828// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
829
830void ModuleSanitizerCoverage::InjectTraceForSwitch(
831 Function &F, ArrayRef<Instruction *> SwitchTraceTargets,
832 Value *&FunctionGateCmp) {
833 for (auto *I : SwitchTraceTargets) {
836 SmallVector<Constant *, 16> Initializers;
837 Value *Cond = SI->getCondition();
838 if (Cond->getType()->getScalarSizeInBits() >
839 Int64Ty->getScalarSizeInBits())
840 continue;
841 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
842 Initializers.push_back(
843 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
844 if (Cond->getType()->getScalarSizeInBits() <
845 Int64Ty->getScalarSizeInBits())
846 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
847 for (auto It : SI->cases()) {
848 ConstantInt *C = It.getCaseValue();
849 if (C->getType()->getScalarSizeInBits() < 64)
850 C = ConstantInt::get(C->getContext(), C->getValue().zext(64));
851 Initializers.push_back(C);
852 }
853 llvm::sort(drop_begin(Initializers, 2),
854 [](const Constant *A, const Constant *B) {
855 return cast<ConstantInt>(A)->getLimitedValue() <
856 cast<ConstantInt>(B)->getLimitedValue();
857 });
858 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
860 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
861 ConstantArray::get(ArrayOfInt64Ty, Initializers),
862 "__sancov_gen_cov_switch_values");
863 if (Options.GatedCallbacks) {
864 auto GateBranch = CreateGateBranch(F, FunctionGateCmp, I);
865 IRBuilder<> GateIRB(GateBranch);
866 GateIRB.CreateCall(SanCovTraceSwitchFunction, {Cond, GV});
867 } else {
868 IRB.CreateCall(SanCovTraceSwitchFunction, {Cond, GV});
869 }
870 }
871 }
872}
873
874void ModuleSanitizerCoverage::InjectTraceForDiv(
875 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
876 for (auto *BO : DivTraceTargets) {
878 Value *A1 = BO->getOperand(1);
879 if (isa<ConstantInt>(A1))
880 continue;
881 if (!A1->getType()->isIntegerTy())
882 continue;
883 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
884 int CallbackIdx = TypeSize == 32 ? 0 : TypeSize == 64 ? 1 : -1;
885 if (CallbackIdx < 0)
886 continue;
887 auto Ty = Type::getIntNTy(*C, TypeSize);
888 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
889 {IRB.CreateIntCast(A1, Ty, true)});
890 }
891}
892
893void ModuleSanitizerCoverage::InjectTraceForGep(
894 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
895 for (auto *GEP : GepTraceTargets) {
897 for (Use &Idx : GEP->indices())
898 if (!isa<ConstantInt>(Idx) && Idx->getType()->isIntegerTy())
899 IRB.CreateCall(SanCovTraceGepFunction,
900 {IRB.CreateIntCast(Idx, IntptrTy, true)});
901 }
902}
903
904void ModuleSanitizerCoverage::InjectTraceForLoadsAndStores(
906 auto CallbackIdx = [&](Type *ElementTy) -> int {
907 uint64_t TypeSize = DL->getTypeStoreSizeInBits(ElementTy);
908 return TypeSize == 8 ? 0
909 : TypeSize == 16 ? 1
910 : TypeSize == 32 ? 2
911 : TypeSize == 64 ? 3
912 : TypeSize == 128 ? 4
913 : -1;
914 };
915 for (auto *LI : Loads) {
917 auto Ptr = LI->getPointerOperand();
918 int Idx = CallbackIdx(LI->getType());
919 if (Idx < 0)
920 continue;
921 IRB.CreateCall(SanCovLoadFunction[Idx], Ptr);
922 }
923 for (auto *SI : Stores) {
925 auto Ptr = SI->getPointerOperand();
926 int Idx = CallbackIdx(SI->getValueOperand()->getType());
927 if (Idx < 0)
928 continue;
929 IRB.CreateCall(SanCovStoreFunction[Idx], Ptr);
930 }
931}
932
933void ModuleSanitizerCoverage::InjectTraceForExits(Function &F) {
934 EscapeEnumerator EE(F, "sancov_exit");
935 while (IRBuilder<> *AtExit = EE.Next()) {
937 AtExit->CreateCall(SanCovTracePCExit, {})
938 ->setTailCallKind(CallInst::TCK_NoTail);
939 }
940}
941
942void ModuleSanitizerCoverage::InjectTraceForCmp(
943 Function &F, ArrayRef<Instruction *> CmpTraceTargets,
944 Value *&FunctionGateCmp) {
945 for (auto *I : CmpTraceTargets) {
946 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
947 InstrumentationIRBuilder IRB(ICMP);
948 Value *A0 = ICMP->getOperand(0);
949 Value *A1 = ICMP->getOperand(1);
950 if (!A0->getType()->isIntegerTy())
951 continue;
952 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
953 int CallbackIdx = TypeSize == 8 ? 0
954 : TypeSize == 16 ? 1
955 : TypeSize == 32 ? 2
956 : TypeSize == 64 ? 3
957 : -1;
958 if (CallbackIdx < 0)
959 continue;
960 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
961 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
962 bool FirstIsConst = isa<ConstantInt>(A0);
963 bool SecondIsConst = isa<ConstantInt>(A1);
964 // If both are const, then we don't need such a comparison.
965 if (FirstIsConst && SecondIsConst)
966 continue;
967 // If only one is const, then make it the first callback argument.
968 if (FirstIsConst || SecondIsConst) {
969 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
970 if (SecondIsConst)
971 std::swap(A0, A1);
972 }
973
974 auto Ty = Type::getIntNTy(*C, TypeSize);
975 if (Options.GatedCallbacks) {
976 auto GateBranch = CreateGateBranch(F, FunctionGateCmp, I);
977 IRBuilder<> GateIRB(GateBranch);
978 GateIRB.CreateCall(CallbackFunc, {GateIRB.CreateIntCast(A0, Ty, true),
979 GateIRB.CreateIntCast(A1, Ty, true)});
980 } else {
981 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
982 IRB.CreateIntCast(A1, Ty, true)});
983 }
984 }
985 }
986}
987
988void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
989 size_t Idx,
990 Value *&FunctionGateCmp,
991 bool IsLeafFunc) {
993 bool IsEntryBB = &BB == &F.getEntryBlock();
994 DebugLoc EntryLoc;
995 if (IsEntryBB) {
996 if (auto SP = F.getSubprogram())
997 EntryLoc = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
998 // Keep static allocas and llvm.localescape calls in the entry block. Even
999 // if we aren't splitting the block, it's nice for allocas to be before
1000 // calls.
1001 IP = PrepareToSplitEntryBlock(BB, IP);
1002 }
1003
1004 InstrumentationIRBuilder IRB(&*IP);
1005 if (EntryLoc)
1006 IRB.SetCurrentDebugLocation(EntryLoc);
1007 if (Options.TracePC || (IsEntryBB && Options.TracePCEntryExit)) {
1008 FunctionCallee Callee = IsEntryBB && Options.TracePCEntryExit
1009 ? SanCovTracePCEntry
1010 : SanCovTracePC;
1011 IRB.CreateCall(Callee)
1012 ->setCannotMerge(); // gets the PC using GET_CALLER_PC.
1013 }
1014 if (Options.TracePCGuard) {
1015 auto GuardPtr = IRB.CreateConstInBoundsGEP2_64(
1016 FunctionGuardArray->getValueType(), FunctionGuardArray, 0, Idx);
1017 if (Options.GatedCallbacks) {
1018 Instruction *I = &*IP;
1019 auto GateBranch = CreateGateBranch(F, FunctionGateCmp, I);
1020 IRBuilder<> GateIRB(GateBranch);
1021 GateIRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge();
1022 } else {
1023 IRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge();
1024 }
1025 }
1026 if (Options.Inline8bitCounters) {
1027 auto CounterPtr = IRB.CreateGEP(
1028 Function8bitCounterArray->getValueType(), Function8bitCounterArray,
1029 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
1030 auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
1031 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
1032 auto Store = IRB.CreateStore(Inc, CounterPtr);
1033 Load->setNoSanitizeMetadata();
1034 Store->setNoSanitizeMetadata();
1035 }
1036 if (Options.InlineBoolFlag) {
1037 auto FlagPtr = IRB.CreateGEP(
1038 FunctionBoolArray->getValueType(), FunctionBoolArray,
1039 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
1040 auto Load = IRB.CreateLoad(Int1Ty, FlagPtr);
1041 auto ThenTerm = SplitBlockAndInsertIfThen(
1042 IRB.CreateIsNull(Load), &*IP, false,
1044 InstrumentationIRBuilder ThenIRB(ThenTerm);
1045 auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr);
1046 if (EntryLoc)
1047 Store->setDebugLoc(EntryLoc);
1048 Load->setNoSanitizeMetadata();
1049 Store->setNoSanitizeMetadata();
1050 }
1051 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
1052 Module *M = F.getParent();
1053 const DataLayout &DL = M->getDataLayout();
1054
1055 if (Options.StackDepthCallbackMin) {
1056 // In callback mode, only add call when stack depth reaches minimum.
1057 int EstimatedStackSize = 0;
1058 // If dynamic alloca found, always add call.
1059 bool HasDynamicAlloc = false;
1060 // Find an insertion point after last "alloca".
1061 llvm::Instruction *InsertBefore = nullptr;
1062
1063 // Examine all allocas in the basic block. since we're too early
1064 // to have results from Intrinsic::frameaddress, we have to manually
1065 // estimate the stack size.
1066 for (auto &I : BB) {
1067 if (auto *AI = dyn_cast<AllocaInst>(&I)) {
1068 // Move potential insertion point past the "alloca".
1069 InsertBefore = AI->getNextNode();
1070
1071 // Make an estimate on the stack usage.
1072 if (auto AllocaSize = AI->getAllocationSize(DL)) {
1073 if (AllocaSize->isFixed())
1074 EstimatedStackSize += AllocaSize->getFixedValue();
1075 else
1076 HasDynamicAlloc = true;
1077 } else {
1078 HasDynamicAlloc = true;
1079 }
1080 }
1081 }
1082
1083 if (HasDynamicAlloc ||
1084 EstimatedStackSize >= Options.StackDepthCallbackMin) {
1085 if (InsertBefore)
1086 IRB.SetInsertPoint(InsertBefore);
1087 auto Call = IRB.CreateCall(SanCovStackDepthCallback);
1088 if (EntryLoc)
1089 Call->setDebugLoc(EntryLoc);
1091 }
1092 } else {
1093 // Check stack depth. If it's the deepest so far, record it.
1094 auto FrameAddrPtr = IRB.CreateIntrinsic(
1095 Intrinsic::frameaddress, IRB.getPtrTy(DL.getAllocaAddrSpace()),
1096 {Constant::getNullValue(Int32Ty)});
1097 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
1098 auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
1099 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
1100 auto ThenTerm = SplitBlockAndInsertIfThen(
1101 IsStackLower, &*IP, false,
1103 InstrumentationIRBuilder ThenIRB(ThenTerm);
1104 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
1105 if (EntryLoc)
1106 Store->setDebugLoc(EntryLoc);
1107 LowestStack->setNoSanitizeMetadata();
1108 Store->setNoSanitizeMetadata();
1109 }
1110 }
1111}
1112
1113std::string
1114ModuleSanitizerCoverage::getSectionName(const std::string &Section) const {
1115 if (TargetTriple.isOSBinFormatCOFF()) {
1116 if (Section == SanCovCountersSectionName)
1117 return ".SCOV$CM";
1118 if (Section == SanCovBoolFlagSectionName)
1119 return ".SCOV$BM";
1120 if (Section == SanCovPCsSectionName)
1121 return ".SCOVP$M";
1122 return ".SCOV$GM"; // For SanCovGuardsSectionName.
1123 }
1124 if (TargetTriple.isOSBinFormatMachO())
1125 return "__DATA,__" + Section;
1126 return "__" + Section;
1127}
1128
1129std::string
1130ModuleSanitizerCoverage::getSectionStart(const std::string &Section) const {
1131 if (TargetTriple.isOSBinFormatMachO())
1132 return "\1section$start$__DATA$__" + Section;
1133 return "__start___" + Section;
1134}
1135
1136std::string
1137ModuleSanitizerCoverage::getSectionEnd(const std::string &Section) const {
1138 if (TargetTriple.isOSBinFormatMachO())
1139 return "\1section$end$__DATA$__" + Section;
1140 return "__stop___" + Section;
1141}
1142
1143void ModuleSanitizerCoverage::createFunctionControlFlow(Function &F) {
1145 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
1146
1147 for (auto &BB : F) {
1148 // blockaddress can not be used on function's entry block.
1149 if (&BB == &F.getEntryBlock())
1150 CFs.push_back((Constant *)IRB.CreatePointerCast(&F, PtrTy));
1151 else
1152 CFs.push_back(
1153 (Constant *)IRB.CreatePointerCast(BlockAddress::get(&BB), PtrTy));
1154
1155 for (auto SuccBB : successors(&BB)) {
1156 assert(SuccBB != &F.getEntryBlock());
1157 CFs.push_back(
1158 (Constant *)IRB.CreatePointerCast(BlockAddress::get(SuccBB), PtrTy));
1159 }
1160
1162
1163 for (auto &Inst : BB) {
1164 if (CallBase *CB = dyn_cast<CallBase>(&Inst)) {
1165 if (CB->isIndirectCall()) {
1166 // TODO(navidem): handle indirect calls, for now mark its existence.
1168 ConstantInt::getAllOnesValue(IntptrTy), PtrTy));
1169 } else {
1170 auto CalledF = CB->getCalledFunction();
1171 if (CalledF && !CalledF->isIntrinsic())
1172 CFs.push_back((Constant *)IRB.CreatePointerCast(CalledF, PtrTy));
1173 }
1174 }
1175 }
1176
1178 }
1179
1180 FunctionCFsArray = CreateFunctionLocalArrayInSection(CFs.size(), F, PtrTy,
1182 FunctionCFsArray->setInitializer(
1183 ConstantArray::get(ArrayType::get(PtrTy, CFs.size()), CFs));
1184 FunctionCFsArray->setConstant(true);
1185}
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
static cl::opt< bool > SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false), cl::Hidden, cl::desc("Split all critical edges during " "PHI elimination"))
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
if(PassOpts->AAPipeline)
const SmallVectorImpl< MachineOperand > & 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 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()
Value * getCalledOperand() const
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:43
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:126
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:794
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:2398
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2297
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2238
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:228
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2011
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:1907
LLVMContext & getContext() const
Definition IRBuilder.h:177
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:2076
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1925
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1418
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2233
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition IRBuilder.h:2763
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2561
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:565
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition IRBuilder.h:2323
Value * CreateIsNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg == 0.
Definition IRBuilder.h:2758
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:196
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
Instruction * user_back()
void setDebugLoc(DebugLoc Loc)
Set the debug location information for 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:1579
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:171
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.
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:272
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:303
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 StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
An efficient, type-erasing, non-owning reference to a callable.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
CallInst * Call
constexpr MCPhysReg SP
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
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).
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
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
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.
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.
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:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#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