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;
35 IRB.getInt32Ty(), PointerType::get(FnTy, F->getAddressSpace()),
36 IRB.getInt8PtrTy());
37
38 if (GlobalVariable *GVCtor = M.getNamedGlobal(ArrayName)) {
39 if (Constant *Init = GVCtor->getInitializer()) {
40 unsigned n = Init->getNumOperands();
41 CurrentCtors.reserve(n + 1);
42 for (unsigned i = 0; i != n; ++i)
43 CurrentCtors.push_back(cast<Constant>(Init->getOperand(i)));
44 }
45 GVCtor->eraseFromParent();
46 }
47
48 // Build a 3 field global_ctor entry. We don't take a comdat key.
49 Constant *CSVals[3];
50 CSVals[0] = IRB.getInt32(Priority);
51 CSVals[1] = F;
54 Constant *RuntimeCtorInit =
55 ConstantStruct::get(EltTy, ArrayRef(CSVals, EltTy->getNumElements()));
56
57 CurrentCtors.push_back(RuntimeCtorInit);
58
59 // Create a new initializer.
60 ArrayType *AT = ArrayType::get(EltTy, CurrentCtors.size());
61 Constant *NewInit = ConstantArray::get(AT, CurrentCtors);
62
63 // Create the new global variable and replace all uses of
64 // the old global variable with the new one.
65 (void)new GlobalVariable(M, NewInit->getType(), false,
66 GlobalValue::AppendingLinkage, NewInit, ArrayName);
67}
68
70 appendToGlobalArray("llvm.global_ctors", M, F, Priority, Data);
71}
72
74 appendToGlobalArray("llvm.global_dtors", M, F, Priority, Data);
75}
76
79 if (!GV || !GV->hasInitializer())
80 return;
81
82 auto *CA = cast<ConstantArray>(GV->getInitializer());
83 for (Use &Op : CA->operands())
84 Init.insert(cast<Constant>(Op));
85}
86
88 GlobalVariable *GV = M.getGlobalVariable(Name);
89
92 if (GV)
93 GV->eraseFromParent();
94
95 Type *ArrayEltTy = llvm::Type::getInt8PtrTy(M.getContext());
96 for (auto *V : Values)
98
99 if (Init.empty())
100 return;
101
102 ArrayType *ATy = ArrayType::get(ArrayEltTy, Init.size());
104 ConstantArray::get(ATy, Init.getArrayRef()),
105 Name);
106 GV->setSection("llvm.metadata");
107}
108
110 appendToUsedList(M, "llvm.used", Values);
111}
112
114 appendToUsedList(M, "llvm.compiler.used", Values);
115}
116
118 function_ref<bool(Constant *)> ShouldRemove) {
119 GlobalVariable *GV = M.getNamedGlobal(Name);
120 if (!GV)
121 return;
122
125
126 Type *ArrayEltTy = cast<ArrayType>(GV->getValueType())->getElementType();
127
129 for (Constant *MaybeRemoved : Init) {
130 if (!ShouldRemove(MaybeRemoved->stripPointerCasts()))
131 NewInit.push_back(MaybeRemoved);
132 }
133
134 if (!NewInit.empty()) {
135 ArrayType *ATy = ArrayType::get(ArrayEltTy, NewInit.size());
136 GlobalVariable *NewGV =
138 ConstantArray::get(ATy, NewInit), "", GV,
140 NewGV->setSection(GV->getSection());
141 NewGV->takeName(GV);
142 }
143
144 GV->eraseFromParent();
145}
146
148 function_ref<bool(Constant *)> ShouldRemove) {
149 removeFromUsedList(M, "llvm.used", ShouldRemove);
150 removeFromUsedList(M, "llvm.compiler.used", ShouldRemove);
151}
152
153void llvm::setKCFIType(Module &M, Function &F, StringRef MangledType) {
154 if (!M.getModuleFlag("kcfi"))
155 return;
156 // Matches CodeGenModule::CreateKCFITypeId in Clang.
157 LLVMContext &Ctx = M.getContext();
158 MDBuilder MDB(Ctx);
159 F.setMetadata(
160 LLVMContext::MD_kcfi_type,
162 Type::getInt32Ty(Ctx),
163 static_cast<uint32_t>(xxHash64(MangledType))))));
164 // If the module was compiled with -fpatchable-function-entry, ensure
165 // we use the same patchable-function-prefix.
166 if (auto *MD = mdconst::extract_or_null<ConstantInt>(
167 M.getModuleFlag("kcfi-offset"))) {
168 if (unsigned Offset = MD->getZExtValue())
169 F.addFnAttr("patchable-function-prefix", std::to_string(Offset));
170 }
171}
172
174 ArrayRef<Type *> InitArgTypes,
175 bool Weak) {
176 assert(!InitName.empty() && "Expected init function name");
177 auto *VoidTy = Type::getVoidTy(M.getContext());
178 auto *FnTy = FunctionType::get(VoidTy, InitArgTypes, false);
179 auto FnCallee = M.getOrInsertFunction(InitName, FnTy);
180 auto *Fn = cast<Function>(FnCallee.getCallee());
181 if (Weak && Fn->isDeclaration())
182 Fn->setLinkage(Function::ExternalWeakLinkage);
183 return FnCallee;
184}
185
188 FunctionType::get(Type::getVoidTy(M.getContext()), false),
189 GlobalValue::InternalLinkage, M.getDataLayout().getProgramAddressSpace(),
190 CtorName, &M);
191 Ctor->addFnAttr(Attribute::NoUnwind);
192 setKCFIType(M, *Ctor, "_ZTSFvvE"); // void (*)(void)
193 BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
194 ReturnInst::Create(M.getContext(), CtorBB);
195 // Ensure Ctor cannot be discarded, even if in a comdat.
196 appendToUsed(M, {Ctor});
197 return Ctor;
198}
199
200std::pair<Function *, FunctionCallee> llvm::createSanitizerCtorAndInitFunctions(
201 Module &M, StringRef CtorName, StringRef InitName,
202 ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs,
203 StringRef VersionCheckName, bool Weak) {
204 assert(!InitName.empty() && "Expected init function name");
205 assert(InitArgs.size() == InitArgTypes.size() &&
206 "Sanitizer's init function expects different number of arguments");
207 FunctionCallee InitFunction =
208 declareSanitizerInitFunction(M, InitName, InitArgTypes, Weak);
209 Function *Ctor = createSanitizerCtor(M, CtorName);
210 IRBuilder<> IRB(M.getContext());
211
212 BasicBlock *RetBB = &Ctor->getEntryBlock();
213 if (Weak) {
214 RetBB->setName("ret");
215 auto *EntryBB = BasicBlock::Create(M.getContext(), "entry", Ctor, RetBB);
216 auto *CallInitBB =
217 BasicBlock::Create(M.getContext(), "callfunc", Ctor, RetBB);
218 auto *InitFn = cast<Function>(InitFunction.getCallee());
219 auto *InitFnPtr =
220 PointerType::get(InitFn->getType(), InitFn->getAddressSpace());
221 IRB.SetInsertPoint(EntryBB);
222 Value *InitNotNull =
223 IRB.CreateICmpNE(InitFn, ConstantPointerNull::get(InitFnPtr));
224 IRB.CreateCondBr(InitNotNull, CallInitBB, RetBB);
225 IRB.SetInsertPoint(CallInitBB);
226 } else {
227 IRB.SetInsertPoint(RetBB->getTerminator());
228 }
229
230 IRB.CreateCall(InitFunction, InitArgs);
231 if (!VersionCheckName.empty()) {
232 FunctionCallee VersionCheckFunction = M.getOrInsertFunction(
233 VersionCheckName, FunctionType::get(IRB.getVoidTy(), {}, false),
234 AttributeList());
235 IRB.CreateCall(VersionCheckFunction, {});
236 }
237
238 if (Weak)
239 IRB.CreateBr(RetBB);
240
241 return std::make_pair(Ctor, InitFunction);
242}
243
244std::pair<Function *, FunctionCallee>
246 Module &M, StringRef CtorName, StringRef InitName,
247 ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs,
248 function_ref<void(Function *, FunctionCallee)> FunctionsCreatedCallback,
249 StringRef VersionCheckName, bool Weak) {
250 assert(!CtorName.empty() && "Expected ctor function name");
251
252 if (Function *Ctor = M.getFunction(CtorName))
253 // FIXME: Sink this logic into the module, similar to the handling of
254 // globals. This will make moving to a concurrent model much easier.
255 if (Ctor->arg_empty() ||
256 Ctor->getReturnType() == Type::getVoidTy(M.getContext()))
257 return {Ctor,
258 declareSanitizerInitFunction(M, InitName, InitArgTypes, Weak)};
259
260 Function *Ctor;
261 FunctionCallee InitFunction;
262 std::tie(Ctor, InitFunction) = llvm::createSanitizerCtorAndInitFunctions(
263 M, CtorName, InitName, InitArgTypes, InitArgs, VersionCheckName, Weak);
264 FunctionsCreatedCallback(Ctor, InitFunction);
265 return std::make_pair(Ctor, InitFunction);
266}
267
269 SmallVectorImpl<Function *> &DeadComdatFunctions) {
270 SmallPtrSet<Function *, 32> MaybeDeadFunctions;
271 SmallPtrSet<Comdat *, 32> MaybeDeadComdats;
272 for (Function *F : DeadComdatFunctions) {
273 MaybeDeadFunctions.insert(F);
274 if (Comdat *C = F->getComdat())
275 MaybeDeadComdats.insert(C);
276 }
277
278 // Find comdats for which all users are dead now.
279 SmallPtrSet<Comdat *, 32> DeadComdats;
280 for (Comdat *C : MaybeDeadComdats) {
281 auto IsUserDead = [&](GlobalObject *GO) {
282 auto *F = dyn_cast<Function>(GO);
283 return F && MaybeDeadFunctions.contains(F);
284 };
285 if (all_of(C->getUsers(), IsUserDead))
286 DeadComdats.insert(C);
287 }
288
289 // Only keep functions which have no comdat or a dead comdat.
290 erase_if(DeadComdatFunctions, [&](Function *F) {
291 Comdat *C = F->getComdat();
292 return C && !DeadComdats.contains(C);
293 });
294}
295
297 MD5 Md5;
298 bool ExportsSymbols = false;
299 auto AddGlobal = [&](GlobalValue &GV) {
300 if (GV.isDeclaration() || GV.getName().startswith("llvm.") ||
301 !GV.hasExternalLinkage() || GV.hasComdat())
302 return;
303 ExportsSymbols = true;
304 Md5.update(GV.getName());
306 };
307
308 for (auto &F : *M)
309 AddGlobal(F);
310 for (auto &GV : M->globals())
311 AddGlobal(GV);
312 for (auto &GA : M->aliases())
313 AddGlobal(GA);
314 for (auto &IF : M->ifuncs())
315 AddGlobal(IF);
316
317 if (!ExportsSymbols)
318 return "";
319
321 Md5.final(R);
322
323 SmallString<32> Str;
324 MD5::stringifyResult(R, Str);
325 return ("." + Str).str();
326}
327
329 ArrayRef<std::string> VariantMappings) {
330 if (VariantMappings.empty())
331 return;
332
333 SmallString<256> Buffer;
334 llvm::raw_svector_ostream Out(Buffer);
335 for (const std::string &VariantMapping : VariantMappings)
336 Out << VariantMapping << ",";
337 // Get rid of the trailing ','.
338 assert(!Buffer.str().empty() && "Must have at least one char.");
339 Buffer.pop_back();
340
341 Module *M = CI->getModule();
342#ifndef NDEBUG
343 for (const std::string &VariantMapping : VariantMappings) {
344 LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << VariantMapping << "'\n");
345 std::optional<VFInfo> VI = VFABI::tryDemangleForVFABI(VariantMapping, *M);
346 assert(VI && "Cannot add an invalid VFABI name.");
347 assert(M->getNamedValue(VI->VectorName) &&
348 "Cannot add variant to attribute: "
349 "vector function declaration is missing.");
350 }
351#endif
352 CI->addFnAttr(
353 Attribute::get(M->getContext(), MappingsAttrName, Buffer.str()));
354}
355
357 StringRef SectionName, Align Alignment) {
358 // Embed the memory buffer into the module.
359 Constant *ModuleConstant = ConstantDataArray::get(
360 M.getContext(), ArrayRef(Buf.getBufferStart(), Buf.getBufferSize()));
362 M, ModuleConstant->getType(), true, GlobalValue::PrivateLinkage,
363 ModuleConstant, "llvm.embedded.object");
365 GV->setAlignment(Alignment);
366
367 LLVMContext &Ctx = M.getContext();
368 NamedMDNode *MD = M.getOrInsertNamedMetadata("llvm.embedded.objects");
369 Metadata *MDVals[] = {ConstantAsMetadata::get(GV),
371
372 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
373 GV->setMetadata(LLVMContext::MD_exclude, llvm::MDNode::get(Ctx, {}));
374
376}
377
379 Module &M, ArrayRef<GlobalIFunc *> FilteredIFuncsToLower) {
381 ArrayRef<GlobalIFunc *> IFuncsToLower = FilteredIFuncsToLower;
382 if (FilteredIFuncsToLower.empty()) { // Default to lowering all ifuncs
383 for (GlobalIFunc &GI : M.ifuncs())
384 AllIFuncs.push_back(&GI);
385 IFuncsToLower = AllIFuncs;
386 }
387
388 bool UnhandledUsers = false;
389 LLVMContext &Ctx = M.getContext();
390 const DataLayout &DL = M.getDataLayout();
391
392 PointerType *TableEntryTy =
394 ? PointerType::get(Type::getInt8Ty(Ctx), DL.getProgramAddressSpace())
395 : PointerType::get(Ctx, DL.getProgramAddressSpace());
396
397 ArrayType *FuncPtrTableTy =
398 ArrayType::get(TableEntryTy, IFuncsToLower.size());
399
400 Align PtrAlign = DL.getABITypeAlign(TableEntryTy);
401
402 // Create a global table of function pointers we'll initialize in a global
403 // constructor.
404 auto *FuncPtrTable = new GlobalVariable(
405 M, FuncPtrTableTy, false, GlobalValue::InternalLinkage,
406 PoisonValue::get(FuncPtrTableTy), "", nullptr,
407 GlobalVariable::NotThreadLocal, DL.getDefaultGlobalsAddressSpace());
408 FuncPtrTable->setAlignment(PtrAlign);
409
410 // Create a function to initialize the function pointer table.
411 Function *NewCtor = Function::Create(
412 FunctionType::get(Type::getVoidTy(Ctx), false), Function::InternalLinkage,
413 DL.getProgramAddressSpace(), "", &M);
414
415 BasicBlock *BB = BasicBlock::Create(Ctx, "", NewCtor);
416 IRBuilder<> InitBuilder(BB);
417
418 size_t TableIndex = 0;
419 for (GlobalIFunc *GI : IFuncsToLower) {
420 Function *ResolvedFunction = GI->getResolverFunction();
421
422 // We don't know what to pass to a resolver function taking arguments
423 //
424 // FIXME: Is this even valid? clang and gcc don't complain but this
425 // probably should be invalid IR. We could just pass through undef.
426 if (!std::empty(ResolvedFunction->getFunctionType()->params())) {
427 LLVM_DEBUG(dbgs() << "Not lowering ifunc resolver function "
428 << ResolvedFunction->getName() << " with parameters\n");
429 UnhandledUsers = true;
430 continue;
431 }
432
433 // Initialize the function pointer table.
434 CallInst *ResolvedFunc = InitBuilder.CreateCall(ResolvedFunction);
435 Value *Casted = InitBuilder.CreatePointerCast(ResolvedFunc, TableEntryTy);
436 Constant *GEP = cast<Constant>(InitBuilder.CreateConstInBoundsGEP2_32(
437 FuncPtrTableTy, FuncPtrTable, 0, TableIndex++));
438 InitBuilder.CreateAlignedStore(Casted, GEP, PtrAlign);
439
440 // Update all users to load a pointer from the global table.
441 for (User *User : make_early_inc_range(GI->users())) {
442 Instruction *UserInst = dyn_cast<Instruction>(User);
443 if (!UserInst) {
444 // TODO: Should handle constantexpr casts in user instructions. Probably
445 // can't do much about constant initializers.
446 UnhandledUsers = true;
447 continue;
448 }
449
450 IRBuilder<> UseBuilder(UserInst);
451 LoadInst *ResolvedTarget =
452 UseBuilder.CreateAlignedLoad(TableEntryTy, GEP, PtrAlign);
453 Value *ResolvedCast =
454 UseBuilder.CreatePointerCast(ResolvedTarget, GI->getType());
455 UserInst->replaceUsesOfWith(GI, ResolvedCast);
456 }
457
458 // If we handled all users, erase the ifunc.
459 if (GI->use_empty())
460 GI->eraseFromParent();
461 }
462
463 InitBuilder.CreateRetVoid();
464
465 PointerType *ConstantDataTy = Ctx.supportsTypedPointers()
466 ? PointerType::get(Type::getInt8Ty(Ctx), 0)
467 : PointerType::get(Ctx, 0);
468
469 // TODO: Is this the right priority? Probably should be before any other
470 // constructors?
471 const int Priority = 10;
472 appendToGlobalCtors(M, NewCtor, Priority,
473 ConstantPointerNull::get(ConstantDataTy));
474 return UnhandledUsers;
475}
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:87
static void collectUsedGlobals(GlobalVariable *GV, SmallSetVector< Constant *, 16 > &Init)
Definition: ModuleUtils.cpp:77
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())
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:357
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:1516
This class represents a function call, abstracting a target machine's calling convention.
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1249
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:691
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:2041
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
Definition: Constants.cpp:2056
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:887
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1707
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1314
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:114
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:550
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:735
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:332
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:1325
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:130
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:252
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:468
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1722
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2054
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:2126
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:1035
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:1005
Value * CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1, const Twine &Name="")
Definition: IRBuilder.h:1829
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition: IRBuilder.h:1029
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:1741
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2293
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2550
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:1399
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:497
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:1587
void addOperand(MDNode *M)
Definition: Metadata.cpp:1221
Class to represent pointers.
Definition: DerivedTypes.h:632
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1759
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:301
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:420
unsigned getNumElements() const
Random access to the elements.
Definition: DerivedTypes.h:327
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:375
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:308
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:381
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:1735
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:721
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:69
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:1998
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:73
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