LLVM 17.0.0git
ModuleUtils.cpp
Go to the documentation of this file.
1//===-- ModuleUtils.cpp - Functions to manipulate Modules -----------------===//
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// This family of functions perform manipulations on Modules.
10//
11//===----------------------------------------------------------------------===//
12
16#include "llvm/IR/Function.h"
17#include "llvm/IR/IRBuilder.h"
18#include "llvm/IR/MDBuilder.h"
19#include "llvm/IR/Module.h"
21#include "llvm/Support/xxhash.h"
22using namespace llvm;
23
24#define DEBUG_TYPE "moduleutils"
25
26static void appendToGlobalArray(StringRef ArrayName, Module &M, Function *F,
27 int Priority, Constant *Data) {
28 IRBuilder<> IRB(M.getContext());
29 FunctionType *FnTy = FunctionType::get(IRB.getVoidTy(), false);
30
31 // Get the current set of static global constructors and add the new ctor
32 // to the list.
33 SmallVector<Constant *, 16> CurrentCtors;
34 StructType *EltTy;
35 if (GlobalVariable *GVCtor = M.getNamedGlobal(ArrayName)) {
36 EltTy = cast<StructType>(GVCtor->getValueType()->getArrayElementType());
37 if (Constant *Init = GVCtor->getInitializer()) {
38 unsigned n = Init->getNumOperands();
39 CurrentCtors.reserve(n + 1);
40 for (unsigned i = 0; i != n; ++i)
41 CurrentCtors.push_back(cast<Constant>(Init->getOperand(i)));
42 }
43 GVCtor->eraseFromParent();
44 } else {
45 EltTy = StructType::get(
46 IRB.getInt32Ty(), PointerType::get(FnTy, F->getAddressSpace()),
47 IRB.getInt8PtrTy());
48 }
49
50 // Build a 3 field global_ctor entry. We don't take a comdat key.
51 Constant *CSVals[3];
52 CSVals[0] = IRB.getInt32(Priority);
53 CSVals[1] = F;
56 Constant *RuntimeCtorInit =
57 ConstantStruct::get(EltTy, ArrayRef(CSVals, EltTy->getNumElements()));
58
59 CurrentCtors.push_back(RuntimeCtorInit);
60
61 // Create a new initializer.
62 ArrayType *AT = ArrayType::get(EltTy, CurrentCtors.size());
63 Constant *NewInit = ConstantArray::get(AT, CurrentCtors);
64
65 // Create the new global variable and replace all uses of
66 // the old global variable with the new one.
67 (void)new GlobalVariable(M, NewInit->getType(), false,
68 GlobalValue::AppendingLinkage, NewInit, ArrayName);
69}
70
72 appendToGlobalArray("llvm.global_ctors", M, F, Priority, Data);
73}
74
76 appendToGlobalArray("llvm.global_dtors", M, F, Priority, Data);
77}
78
81 if (!GV || !GV->hasInitializer())
82 return;
83
84 auto *CA = cast<ConstantArray>(GV->getInitializer());
85 for (Use &Op : CA->operands())
86 Init.insert(cast<Constant>(Op));
87}
88
90 GlobalVariable *GV = M.getGlobalVariable(Name);
91
94 if (GV)
95 GV->eraseFromParent();
96
97 Type *ArrayEltTy = llvm::Type::getInt8PtrTy(M.getContext());
98 for (auto *V : Values)
100
101 if (Init.empty())
102 return;
103
104 ArrayType *ATy = ArrayType::get(ArrayEltTy, Init.size());
106 ConstantArray::get(ATy, Init.getArrayRef()),
107 Name);
108 GV->setSection("llvm.metadata");
109}
110
112 appendToUsedList(M, "llvm.used", Values);
113}
114
116 appendToUsedList(M, "llvm.compiler.used", Values);
117}
118
120 function_ref<bool(Constant *)> ShouldRemove) {
121 GlobalVariable *GV = M.getNamedGlobal(Name);
122 if (!GV)
123 return;
124
127
128 Type *ArrayEltTy = cast<ArrayType>(GV->getValueType())->getElementType();
129
131 for (Constant *MaybeRemoved : Init) {
132 if (!ShouldRemove(MaybeRemoved->stripPointerCasts()))
133 NewInit.push_back(MaybeRemoved);
134 }
135
136 if (!NewInit.empty()) {
137 ArrayType *ATy = ArrayType::get(ArrayEltTy, NewInit.size());
138 GlobalVariable *NewGV =
140 ConstantArray::get(ATy, NewInit), "", GV,
142 NewGV->setSection(GV->getSection());
143 NewGV->takeName(GV);
144 }
145
146 GV->eraseFromParent();
147}
148
150 function_ref<bool(Constant *)> ShouldRemove) {
151 removeFromUsedList(M, "llvm.used", ShouldRemove);
152 removeFromUsedList(M, "llvm.compiler.used", ShouldRemove);
153}
154
155void llvm::setKCFIType(Module &M, Function &F, StringRef MangledType) {
156 if (!M.getModuleFlag("kcfi"))
157 return;
158 // Matches CodeGenModule::CreateKCFITypeId in Clang.
159 LLVMContext &Ctx = M.getContext();
160 MDBuilder MDB(Ctx);
161 F.setMetadata(
162 LLVMContext::MD_kcfi_type,
164 Type::getInt32Ty(Ctx),
165 static_cast<uint32_t>(xxHash64(MangledType))))));
166 // If the module was compiled with -fpatchable-function-entry, ensure
167 // we use the same patchable-function-prefix.
168 if (auto *MD = mdconst::extract_or_null<ConstantInt>(
169 M.getModuleFlag("kcfi-offset"))) {
170 if (unsigned Offset = MD->getZExtValue())
171 F.addFnAttr("patchable-function-prefix", std::to_string(Offset));
172 }
173}
174
176 ArrayRef<Type *> InitArgTypes,
177 bool Weak) {
178 assert(!InitName.empty() && "Expected init function name");
179 auto *VoidTy = Type::getVoidTy(M.getContext());
180 auto *FnTy = FunctionType::get(VoidTy, InitArgTypes, false);
181 auto FnCallee = M.getOrInsertFunction(InitName, FnTy);
182 auto *Fn = cast<Function>(FnCallee.getCallee());
183 if (Weak && Fn->isDeclaration())
184 Fn->setLinkage(Function::ExternalWeakLinkage);
185 return FnCallee;
186}
187
190 FunctionType::get(Type::getVoidTy(M.getContext()), false),
191 GlobalValue::InternalLinkage, M.getDataLayout().getProgramAddressSpace(),
192 CtorName, &M);
193 Ctor->addFnAttr(Attribute::NoUnwind);
194 setKCFIType(M, *Ctor, "_ZTSFvvE"); // void (*)(void)
195 BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
196 ReturnInst::Create(M.getContext(), CtorBB);
197 // Ensure Ctor cannot be discarded, even if in a comdat.
198 appendToUsed(M, {Ctor});
199 return Ctor;
200}
201
202std::pair<Function *, FunctionCallee> llvm::createSanitizerCtorAndInitFunctions(
203 Module &M, StringRef CtorName, StringRef InitName,
204 ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs,
205 StringRef VersionCheckName, bool Weak) {
206 assert(!InitName.empty() && "Expected init function name");
207 assert(InitArgs.size() == InitArgTypes.size() &&
208 "Sanitizer's init function expects different number of arguments");
209 FunctionCallee InitFunction =
210 declareSanitizerInitFunction(M, InitName, InitArgTypes, Weak);
211 Function *Ctor = createSanitizerCtor(M, CtorName);
212 IRBuilder<> IRB(M.getContext());
213
214 BasicBlock *RetBB = &Ctor->getEntryBlock();
215 if (Weak) {
216 RetBB->setName("ret");
217 auto *EntryBB = BasicBlock::Create(M.getContext(), "entry", Ctor, RetBB);
218 auto *CallInitBB =
219 BasicBlock::Create(M.getContext(), "callfunc", Ctor, RetBB);
220 auto *InitFn = cast<Function>(InitFunction.getCallee());
221 auto *InitFnPtr =
222 PointerType::get(InitFn->getType(), InitFn->getAddressSpace());
223 IRB.SetInsertPoint(EntryBB);
224 Value *InitNotNull =
225 IRB.CreateICmpNE(InitFn, ConstantPointerNull::get(InitFnPtr));
226 IRB.CreateCondBr(InitNotNull, CallInitBB, RetBB);
227 IRB.SetInsertPoint(CallInitBB);
228 } else {
229 IRB.SetInsertPoint(RetBB->getTerminator());
230 }
231
232 IRB.CreateCall(InitFunction, InitArgs);
233 if (!VersionCheckName.empty()) {
234 FunctionCallee VersionCheckFunction = M.getOrInsertFunction(
235 VersionCheckName, FunctionType::get(IRB.getVoidTy(), {}, false),
236 AttributeList());
237 IRB.CreateCall(VersionCheckFunction, {});
238 }
239
240 if (Weak)
241 IRB.CreateBr(RetBB);
242
243 return std::make_pair(Ctor, InitFunction);
244}
245
246std::pair<Function *, FunctionCallee>
248 Module &M, StringRef CtorName, StringRef InitName,
249 ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs,
250 function_ref<void(Function *, FunctionCallee)> FunctionsCreatedCallback,
251 StringRef VersionCheckName, bool Weak) {
252 assert(!CtorName.empty() && "Expected ctor function name");
253
254 if (Function *Ctor = M.getFunction(CtorName))
255 // FIXME: Sink this logic into the module, similar to the handling of
256 // globals. This will make moving to a concurrent model much easier.
257 if (Ctor->arg_empty() ||
258 Ctor->getReturnType() == Type::getVoidTy(M.getContext()))
259 return {Ctor,
260 declareSanitizerInitFunction(M, InitName, InitArgTypes, Weak)};
261
262 Function *Ctor;
263 FunctionCallee InitFunction;
264 std::tie(Ctor, InitFunction) = llvm::createSanitizerCtorAndInitFunctions(
265 M, CtorName, InitName, InitArgTypes, InitArgs, VersionCheckName, Weak);
266 FunctionsCreatedCallback(Ctor, InitFunction);
267 return std::make_pair(Ctor, InitFunction);
268}
269
271 SmallVectorImpl<Function *> &DeadComdatFunctions) {
272 SmallPtrSet<Function *, 32> MaybeDeadFunctions;
273 SmallPtrSet<Comdat *, 32> MaybeDeadComdats;
274 for (Function *F : DeadComdatFunctions) {
275 MaybeDeadFunctions.insert(F);
276 if (Comdat *C = F->getComdat())
277 MaybeDeadComdats.insert(C);
278 }
279
280 // Find comdats for which all users are dead now.
281 SmallPtrSet<Comdat *, 32> DeadComdats;
282 for (Comdat *C : MaybeDeadComdats) {
283 auto IsUserDead = [&](GlobalObject *GO) {
284 auto *F = dyn_cast<Function>(GO);
285 return F && MaybeDeadFunctions.contains(F);
286 };
287 if (all_of(C->getUsers(), IsUserDead))
288 DeadComdats.insert(C);
289 }
290
291 // Only keep functions which have no comdat or a dead comdat.
292 erase_if(DeadComdatFunctions, [&](Function *F) {
293 Comdat *C = F->getComdat();
294 return C && !DeadComdats.contains(C);
295 });
296}
297
299 MD5 Md5;
300 bool ExportsSymbols = false;
301 auto AddGlobal = [&](GlobalValue &GV) {
302 if (GV.isDeclaration() || GV.getName().startswith("llvm.") ||
303 !GV.hasExternalLinkage() || GV.hasComdat())
304 return;
305 ExportsSymbols = true;
306 Md5.update(GV.getName());
308 };
309
310 for (auto &F : *M)
311 AddGlobal(F);
312 for (auto &GV : M->globals())
313 AddGlobal(GV);
314 for (auto &GA : M->aliases())
315 AddGlobal(GA);
316 for (auto &IF : M->ifuncs())
317 AddGlobal(IF);
318
319 if (!ExportsSymbols)
320 return "";
321
323 Md5.final(R);
324
325 SmallString<32> Str;
326 MD5::stringifyResult(R, Str);
327 return ("." + Str).str();
328}
329
331 ArrayRef<std::string> VariantMappings) {
332 if (VariantMappings.empty())
333 return;
334
335 SmallString<256> Buffer;
336 llvm::raw_svector_ostream Out(Buffer);
337 for (const std::string &VariantMapping : VariantMappings)
338 Out << VariantMapping << ",";
339 // Get rid of the trailing ','.
340 assert(!Buffer.str().empty() && "Must have at least one char.");
341 Buffer.pop_back();
342
343 Module *M = CI->getModule();
344#ifndef NDEBUG
345 for (const std::string &VariantMapping : VariantMappings) {
346 LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << VariantMapping << "'\n");
347 std::optional<VFInfo> VI = VFABI::tryDemangleForVFABI(VariantMapping, *M);
348 assert(VI && "Cannot add an invalid VFABI name.");
349 assert(M->getNamedValue(VI->VectorName) &&
350 "Cannot add variant to attribute: "
351 "vector function declaration is missing.");
352 }
353#endif
354 CI->addFnAttr(
355 Attribute::get(M->getContext(), MappingsAttrName, Buffer.str()));
356}
357
359 StringRef SectionName, Align Alignment) {
360 // Embed the memory buffer into the module.
361 Constant *ModuleConstant = ConstantDataArray::get(
362 M.getContext(), ArrayRef(Buf.getBufferStart(), Buf.getBufferSize()));
364 M, ModuleConstant->getType(), true, GlobalValue::PrivateLinkage,
365 ModuleConstant, "llvm.embedded.object");
367 GV->setAlignment(Alignment);
368
369 LLVMContext &Ctx = M.getContext();
370 NamedMDNode *MD = M.getOrInsertNamedMetadata("llvm.embedded.objects");
371 Metadata *MDVals[] = {ConstantAsMetadata::get(GV),
373
374 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
375 GV->setMetadata(LLVMContext::MD_exclude, llvm::MDNode::get(Ctx, {}));
376
378}
379
381 Module &M, ArrayRef<GlobalIFunc *> FilteredIFuncsToLower) {
383 ArrayRef<GlobalIFunc *> IFuncsToLower = FilteredIFuncsToLower;
384 if (FilteredIFuncsToLower.empty()) { // Default to lowering all ifuncs
385 for (GlobalIFunc &GI : M.ifuncs())
386 AllIFuncs.push_back(&GI);
387 IFuncsToLower = AllIFuncs;
388 }
389
390 bool UnhandledUsers = false;
391 LLVMContext &Ctx = M.getContext();
392 const DataLayout &DL = M.getDataLayout();
393
394 PointerType *TableEntryTy =
396 ? PointerType::get(Type::getInt8Ty(Ctx), DL.getProgramAddressSpace())
397 : PointerType::get(Ctx, DL.getProgramAddressSpace());
398
399 ArrayType *FuncPtrTableTy =
400 ArrayType::get(TableEntryTy, IFuncsToLower.size());
401
402 Align PtrAlign = DL.getABITypeAlign(TableEntryTy);
403
404 // Create a global table of function pointers we'll initialize in a global
405 // constructor.
406 auto *FuncPtrTable = new GlobalVariable(
407 M, FuncPtrTableTy, false, GlobalValue::InternalLinkage,
408 PoisonValue::get(FuncPtrTableTy), "", nullptr,
409 GlobalVariable::NotThreadLocal, DL.getDefaultGlobalsAddressSpace());
410 FuncPtrTable->setAlignment(PtrAlign);
411
412 // Create a function to initialize the function pointer table.
413 Function *NewCtor = Function::Create(
414 FunctionType::get(Type::getVoidTy(Ctx), false), Function::InternalLinkage,
415 DL.getProgramAddressSpace(), "", &M);
416
417 BasicBlock *BB = BasicBlock::Create(Ctx, "", NewCtor);
418 IRBuilder<> InitBuilder(BB);
419
420 size_t TableIndex = 0;
421 for (GlobalIFunc *GI : IFuncsToLower) {
422 Function *ResolvedFunction = GI->getResolverFunction();
423
424 // We don't know what to pass to a resolver function taking arguments
425 //
426 // FIXME: Is this even valid? clang and gcc don't complain but this
427 // probably should be invalid IR. We could just pass through undef.
428 if (!std::empty(ResolvedFunction->getFunctionType()->params())) {
429 LLVM_DEBUG(dbgs() << "Not lowering ifunc resolver function "
430 << ResolvedFunction->getName() << " with parameters\n");
431 UnhandledUsers = true;
432 continue;
433 }
434
435 // Initialize the function pointer table.
436 CallInst *ResolvedFunc = InitBuilder.CreateCall(ResolvedFunction);
437 Value *Casted = InitBuilder.CreatePointerCast(ResolvedFunc, TableEntryTy);
438 Constant *GEP = cast<Constant>(InitBuilder.CreateConstInBoundsGEP2_32(
439 FuncPtrTableTy, FuncPtrTable, 0, TableIndex++));
440 InitBuilder.CreateAlignedStore(Casted, GEP, PtrAlign);
441
442 // Update all users to load a pointer from the global table.
443 for (User *User : make_early_inc_range(GI->users())) {
444 Instruction *UserInst = dyn_cast<Instruction>(User);
445 if (!UserInst) {
446 // TODO: Should handle constantexpr casts in user instructions. Probably
447 // can't do much about constant initializers.
448 UnhandledUsers = true;
449 continue;
450 }
451
452 IRBuilder<> UseBuilder(UserInst);
453 LoadInst *ResolvedTarget =
454 UseBuilder.CreateAlignedLoad(TableEntryTy, GEP, PtrAlign);
455 Value *ResolvedCast =
456 UseBuilder.CreatePointerCast(ResolvedTarget, GI->getType());
457 UserInst->replaceUsesOfWith(GI, ResolvedCast);
458 }
459
460 // If we handled all users, erase the ifunc.
461 if (GI->use_empty())
462 GI->eraseFromParent();
463 }
464
465 InitBuilder.CreateRetVoid();
466
467 PointerType *ConstantDataTy = Ctx.supportsTypedPointers()
468 ? PointerType::get(Type::getInt8Ty(Ctx), 0)
469 : PointerType::get(Ctx, 0);
470
471 // TODO: Is this the right priority? Probably should be before any other
472 // constructors?
473 const int Priority = 10;
474 appendToGlobalCtors(M, NewCtor, Priority,
475 ConstantPointerNull::get(ConstantDataTy));
476 return UnhandledUsers;
477}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define LLVM_DEBUG(X)
Definition: Debug.h:101
std::string Name
Hexagon Common GEP
#define F(x, y, z)
Definition: MD5.cpp:55
static void appendToUsedList(Module &M, StringRef Name, ArrayRef< GlobalValue * > Values)
Definition: ModuleUtils.cpp:89
static void collectUsedGlobals(GlobalVariable *GV, SmallSetVector< Constant *, 16 > &Init)
Definition: ModuleUtils.cpp:79
static void removeFromUsedList(Module &M, StringRef Name, function_ref< bool(Constant *)> ShouldRemove)
static void appendToGlobalArray(StringRef ArrayName, Module &M, Function *F, int Priority, Constant *Data)
Definition: ModuleUtils.cpp:26
Module.h This file contains the declarations for the Module class.
@ VI
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
@ Weak
Definition: TextStubV5.cpp:113
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:163
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:158
Class to represent array types.
Definition: DerivedTypes.h:368
static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
Definition: Attributes.cpp:91
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:105
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:127
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
Definition: InstrTypes.h:1522
This class represents a function call, abstracting a target machine's calling convention.
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1235
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:419
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition: Constants.h:690
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:2025
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
Definition: Constants.cpp:2040
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:888
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1691
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1300
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:356
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:165
ArrayRef< Type * > params() const
Definition: DerivedTypes.h:130
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition: Function.cpp:554
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:136
const BasicBlock & getEntryBlock() const
Definition: Function.h:749
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:174
static Function * createWithDefaultAttr(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Creates a function with some attributes recorded in llvm.module.flags applied.
Definition: Function.cpp:336
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:117
void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
Definition: Metadata.cpp:1391
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:128
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:250
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:267
unsigned getAddressSpace() const
Definition: GlobalValue.h:201
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:56
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:55
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:54
Type * getValueType() const
Definition: GlobalValue.h:292
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition: Globals.cpp:454
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1736
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2068
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:512
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2140
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:472
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition: IRBuilder.h:1049
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
Definition: IRBuilder.h:560
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
Definition: IRBuilder.h:1019
Value * CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1, const Twine &Name="")
Definition: IRBuilder.h:1843
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition: IRBuilder.h:1043
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:180
Type * getVoidTy()
Fetch the type representing void.
Definition: IRBuilder.h:550
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition: IRBuilder.h:1755
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2307
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2564
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:70
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
bool supportsTypedPointers() const
Whether typed pointers are supported. If false, all pointers are opaque.
An instruction for reading from memory.
Definition: Instructions.h:177
Definition: MD5.h:41
void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition: MD5.cpp:189
static void stringifyResult(MD5Result &Result, SmallVectorImpl< char > &Str)
Translates the bytes in Res to a hex string that is deposited into Str.
Definition: MD5.cpp:287
void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition: MD5.cpp:234
ConstantAsMetadata * createConstant(Constant *C)
Return the given constant as metadata.
Definition: MDBuilder.cpp:24
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1416
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:499
size_t getBufferSize() const
const char * getBufferStart() const
Root of the metadata hierarchy.
Definition: Metadata.h:61
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A tuple of MDNodes.
Definition: Metadata.h:1604
void addOperand(MDNode *M)
Definition: Metadata.cpp:1287
Class to represent pointers.
Definition: DerivedTypes.h:643
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1743
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:365
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:389
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:450
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:312
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:261
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:577
void reserve(size_type N)
Definition: SmallVector.h:667
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
Class to represent struct types.
Definition: DerivedTypes.h:213
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:434
unsigned getNumElements() const
Random access to the elements.
Definition: DerivedTypes.h:338
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static Type * getVoidTy(LLVMContext &C)
static IntegerType * getInt8Ty(LLVMContext &C)
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
static IntegerType * getInt32Ty(LLVMContext &C)
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition: User.cpp:21
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:378
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:384
An efficient, type-erasing, non-owning reference to a callable.
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:672
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
std::optional< VFInfo > tryDemangleForVFABI(StringRef MangledName, const Module &M)
Function to construct a VFInfo out of a mangled names in the following format:
void setVectorVariantNames(CallInst *CI, ArrayRef< std::string > VariantMappings)
Overwrite the Vector Function ABI variants attribute with the names provide in VariantMappings.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:406
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:1819
Function * createSanitizerCtor(Module &M, StringRef CtorName)
Creates sanitizer constructor function.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:748
FunctionCallee declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type * > InitArgTypes, bool Weak=false)
std::string getUniqueModuleId(Module *M)
Produce a unique identifier for this module by taking the MD5 sum of the names of the module's strong...
std::pair< Function *, FunctionCallee > getOrCreateSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs, function_ref< void(Function *, FunctionCallee)> FunctionsCreatedCallback, StringRef VersionCheckName=StringRef(), bool Weak=false)
Creates sanitizer constructor function lazily.
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.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void removeFromUsedLists(Module &M, function_ref< bool(Constant *)> ShouldRemove)
Removes global values from the llvm.used and llvm.compiler.used arrays.
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
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.
Definition: ModuleUtils.cpp:71
void setKCFIType(Module &M, Function &F, StringRef MangledType)
Sets the KCFI type for the function.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition: STLExtras.h:2113
void filterDeadComdatFunctions(SmallVectorImpl< Function * > &DeadComdatFunctions)
Filter out potentially dead comdat functions where other entries keep the entire comdat group alive.
void embedBufferInModule(Module &M, MemoryBufferRef Buf, StringRef SectionName, Align Alignment=Align(1))
Embed the memory buffer Buf into the module M as a global using the specified section name.
bool lowerGlobalIFuncUsersAsGlobalCtor(Module &M, ArrayRef< GlobalIFunc * > IFuncsToLower={})
Lower all calls to ifuncs by replacing uses with indirect calls loaded out of a global table initiali...
void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
void appendToGlobalDtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Same as appendToGlobalCtors(), but for global dtors.
Definition: ModuleUtils.cpp:75
uint64_t xxHash64(llvm::StringRef Data)
Definition: xxhash.cpp:70
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39