LLVM 20.0.0git
Module.cpp
Go to the documentation of this file.
1//===- Module.cpp - Implement the Module class ----------------------------===//
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 file implements the Module class for the IR library.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/Module.h"
17#include "llvm/ADT/StringMap.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/Twine.h"
20#include "llvm/IR/Attributes.h"
21#include "llvm/IR/Comdat.h"
22#include "llvm/IR/Constants.h"
23#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Function.h"
28#include "llvm/IR/GlobalAlias.h"
29#include "llvm/IR/GlobalIFunc.h"
30#include "llvm/IR/GlobalValue.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Metadata.h"
36#include "llvm/IR/Type.h"
37#include "llvm/IR/TypeFinder.h"
38#include "llvm/IR/Value.h"
42#include "llvm/Support/Error.h"
44#include "llvm/Support/Path.h"
47#include <cassert>
48#include <cstdint>
49#include <memory>
50#include <optional>
51#include <utility>
52#include <vector>
53
54using namespace llvm;
55
57
58//===----------------------------------------------------------------------===//
59// Methods to implement the globals and functions lists.
60//
61
62// Explicit instantiations of SymbolTableListTraits since some of the methods
63// are not in the public header file.
68
69//===----------------------------------------------------------------------===//
70// Primitive Module methods.
71//
72
73Module::Module(StringRef MID, LLVMContext &C)
74 : Context(C), ValSymTab(std::make_unique<ValueSymbolTable>(-1)),
75 ModuleID(std::string(MID)), SourceFileName(std::string(MID)),
76 IsNewDbgInfoFormat(UseNewDbgInfoFormat) {
77 Context.addModule(this);
78}
79
80Module &Module::operator=(Module &&Other) {
81 assert(&Context == &Other.Context && "Module must be in the same Context");
82
83 dropAllReferences();
84
85 ModuleID = std::move(Other.ModuleID);
86 SourceFileName = std::move(Other.SourceFileName);
87 IsNewDbgInfoFormat = std::move(Other.IsNewDbgInfoFormat);
88
89 GlobalList.clear();
90 GlobalList.splice(GlobalList.begin(), Other.GlobalList);
91
92 FunctionList.clear();
93 FunctionList.splice(FunctionList.begin(), Other.FunctionList);
94
95 AliasList.clear();
96 AliasList.splice(AliasList.begin(), Other.AliasList);
97
98 IFuncList.clear();
99 IFuncList.splice(IFuncList.begin(), Other.IFuncList);
100
101 NamedMDList.clear();
102 NamedMDList.splice(NamedMDList.begin(), Other.NamedMDList);
103 GlobalScopeAsm = std::move(Other.GlobalScopeAsm);
104 OwnedMemoryBuffer = std::move(Other.OwnedMemoryBuffer);
105 Materializer = std::move(Other.Materializer);
106 TargetTriple = std::move(Other.TargetTriple);
107 DL = std::move(Other.DL);
108 CurrentIntrinsicIds = std::move(Other.CurrentIntrinsicIds);
109 UniquedIntrinsicNames = std::move(Other.UniquedIntrinsicNames);
110 ModuleFlags = std::move(Other.ModuleFlags);
111 Context.addModule(this);
112 return *this;
113}
114
115Module::~Module() {
116 Context.removeModule(this);
117 dropAllReferences();
118 GlobalList.clear();
119 FunctionList.clear();
120 AliasList.clear();
121 IFuncList.clear();
122}
123
124void Module::removeDebugIntrinsicDeclarations() {
125 auto *DeclareIntrinsicFn =
126 Intrinsic::getOrInsertDeclaration(this, Intrinsic::dbg_declare);
127 assert((!isMaterialized() || DeclareIntrinsicFn->hasZeroLiveUses()) &&
128 "Debug declare intrinsic should have had uses removed.");
129 DeclareIntrinsicFn->eraseFromParent();
130 auto *ValueIntrinsicFn =
131 Intrinsic::getOrInsertDeclaration(this, Intrinsic::dbg_value);
132 assert((!isMaterialized() || ValueIntrinsicFn->hasZeroLiveUses()) &&
133 "Debug value intrinsic should have had uses removed.");
134 ValueIntrinsicFn->eraseFromParent();
135 auto *AssignIntrinsicFn =
136 Intrinsic::getOrInsertDeclaration(this, Intrinsic::dbg_assign);
137 assert((!isMaterialized() || AssignIntrinsicFn->hasZeroLiveUses()) &&
138 "Debug assign intrinsic should have had uses removed.");
139 AssignIntrinsicFn->eraseFromParent();
140 auto *LabelntrinsicFn =
141 Intrinsic::getOrInsertDeclaration(this, Intrinsic::dbg_label);
142 assert((!isMaterialized() || LabelntrinsicFn->hasZeroLiveUses()) &&
143 "Debug label intrinsic should have had uses removed.");
144 LabelntrinsicFn->eraseFromParent();
145}
146
147std::unique_ptr<RandomNumberGenerator>
148Module::createRNG(const StringRef Name) const {
149 SmallString<32> Salt(Name);
150
151 // This RNG is guaranteed to produce the same random stream only
152 // when the Module ID and thus the input filename is the same. This
153 // might be problematic if the input filename extension changes
154 // (e.g. from .c to .bc or .ll).
155 //
156 // We could store this salt in NamedMetadata, but this would make
157 // the parameter non-const. This would unfortunately make this
158 // interface unusable by any Machine passes, since they only have a
159 // const reference to their IR Module. Alternatively we can always
160 // store salt metadata from the Module constructor.
161 Salt += sys::path::filename(getModuleIdentifier());
162
163 return std::unique_ptr<RandomNumberGenerator>(
164 new RandomNumberGenerator(Salt));
165}
166
167/// getNamedValue - Return the first global value in the module with
168/// the specified name, of arbitrary type. This method returns null
169/// if a global with the specified name is not found.
170GlobalValue *Module::getNamedValue(StringRef Name) const {
171 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
172}
173
174unsigned Module::getNumNamedValues() const {
175 return getValueSymbolTable().size();
176}
177
178/// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
179/// This ID is uniqued across modules in the current LLVMContext.
180unsigned Module::getMDKindID(StringRef Name) const {
181 return Context.getMDKindID(Name);
182}
183
184/// getMDKindNames - Populate client supplied SmallVector with the name for
185/// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
186/// so it is filled in as an empty string.
187void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
188 return Context.getMDKindNames(Result);
189}
190
191void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
192 return Context.getOperandBundleTags(Result);
193}
194
195//===----------------------------------------------------------------------===//
196// Methods for easy access to the functions in the module.
197//
198
199// getOrInsertFunction - Look up the specified function in the module symbol
200// table. If it does not exist, add a prototype for the function and return
201// it. This is nice because it allows most passes to get away with not handling
202// the symbol table directly for this common task.
203//
204FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
206 // See if we have a definition for the specified function already.
207 GlobalValue *F = getNamedValue(Name);
208 if (!F) {
209 // Nope, add it
210 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage,
211 DL.getProgramAddressSpace(), Name, this);
212 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
213 New->setAttributes(AttributeList);
214 return {Ty, New}; // Return the new prototype.
215 }
216
217 // Otherwise, we just found the existing function or a prototype.
218 return {Ty, F};
219}
220
221FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) {
222 return getOrInsertFunction(Name, Ty, AttributeList());
223}
224
225// getFunction - Look up the specified function in the module symbol table.
226// If it does not exist, return null.
227//
228Function *Module::getFunction(StringRef Name) const {
229 return dyn_cast_or_null<Function>(getNamedValue(Name));
230}
231
232//===----------------------------------------------------------------------===//
233// Methods for easy access to the global variables in the module.
234//
235
236/// getGlobalVariable - Look up the specified global variable in the module
237/// symbol table. If it does not exist, return null. The type argument
238/// should be the underlying type of the global, i.e., it should not have
239/// the top-level PointerType, which represents the address of the global.
240/// If AllowLocal is set to true, this function will return types that
241/// have an local. By default, these types are not returned.
242///
243GlobalVariable *Module::getGlobalVariable(StringRef Name,
244 bool AllowLocal) const {
245 if (GlobalVariable *Result =
246 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
247 if (AllowLocal || !Result->hasLocalLinkage())
248 return Result;
249 return nullptr;
250}
251
252/// getOrInsertGlobal - Look up the specified global in the module symbol table.
253/// 1. If it does not exist, add a declaration of the global and return it.
254/// 2. Else, the global exists but has the wrong type: return the function
255/// with a constantexpr cast to the right type.
256/// 3. Finally, if the existing global is the correct declaration, return the
257/// existing global.
258Constant *Module::getOrInsertGlobal(
259 StringRef Name, Type *Ty,
260 function_ref<GlobalVariable *()> CreateGlobalCallback) {
261 // See if we have a definition for the specified global already.
262 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
263 if (!GV)
264 GV = CreateGlobalCallback();
265 assert(GV && "The CreateGlobalCallback is expected to create a global");
266
267 // Otherwise, we just found the existing function or a prototype.
268 return GV;
269}
270
271// Overload to construct a global variable using its constructor's defaults.
272Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
273 return getOrInsertGlobal(Name, Ty, [&] {
274 return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
275 nullptr, Name);
276 });
277}
278
279//===----------------------------------------------------------------------===//
280// Methods for easy access to the global variables in the module.
281//
282
283// getNamedAlias - Look up the specified global in the module symbol table.
284// If it does not exist, return null.
285//
286GlobalAlias *Module::getNamedAlias(StringRef Name) const {
287 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
288}
289
290GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
291 return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
292}
293
294/// getNamedMetadata - Return the first NamedMDNode in the module with the
295/// specified name. This method returns null if a NamedMDNode with the
296/// specified name is not found.
297NamedMDNode *Module::getNamedMetadata(StringRef Name) const {
298 return NamedMDSymTab.lookup(Name);
299}
300
301/// getOrInsertNamedMetadata - Return the first named MDNode in the module
302/// with the specified name. This method returns a new NamedMDNode if a
303/// NamedMDNode with the specified name is not found.
304NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
305 NamedMDNode *&NMD = NamedMDSymTab[Name];
306 if (!NMD) {
307 NMD = new NamedMDNode(Name);
308 NMD->setParent(this);
309 insertNamedMDNode(NMD);
310 if (Name == "llvm.module.flags")
311 ModuleFlags = NMD;
312 }
313 return NMD;
314}
315
316/// eraseNamedMetadata - Remove the given NamedMDNode from this module and
317/// delete it.
318void Module::eraseNamedMetadata(NamedMDNode *NMD) {
319 NamedMDSymTab.erase(NMD->getName());
320 if (NMD == ModuleFlags)
321 ModuleFlags = nullptr;
322 eraseNamedMDNode(NMD);
323}
324
325bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
326 if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
327 uint64_t Val = Behavior->getLimitedValue();
328 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
329 MFB = static_cast<ModFlagBehavior>(Val);
330 return true;
331 }
332 }
333 return false;
334}
335
336/// getModuleFlagsMetadata - Returns the module flags in the provided vector.
337void Module::
338getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
339 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
340 if (!ModFlags) return;
341
342 for (const MDNode *Flag : ModFlags->operands()) {
343 // The verifier will catch errors, so no need to check them here.
344 auto *MFBConstant = mdconst::extract<ConstantInt>(Flag->getOperand(0));
345 auto MFB = static_cast<ModFlagBehavior>(MFBConstant->getLimitedValue());
346 MDString *Key = cast<MDString>(Flag->getOperand(1));
347 Metadata *Val = Flag->getOperand(2);
348 Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
349 }
350}
351
352/// Return the corresponding value if Key appears in module flags, otherwise
353/// return null.
354Metadata *Module::getModuleFlag(StringRef Key) const {
355 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
356 if (!ModFlags)
357 return nullptr;
358 for (const MDNode *Flag : ModFlags->operands()) {
359 if (Key == cast<MDString>(Flag->getOperand(1))->getString())
360 return Flag->getOperand(2);
361 }
362 return nullptr;
363}
364
365/// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
366/// represents module-level flags. If module-level flags aren't found, it
367/// creates the named metadata that contains them.
368NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
369 if (ModuleFlags)
370 return ModuleFlags;
371 return getOrInsertNamedMetadata("llvm.module.flags");
372}
373
374/// addModuleFlag - Add a module-level flag to the module-level flags
375/// metadata. It will create the module-level flags named metadata if it doesn't
376/// already exist.
377void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
378 Metadata *Val) {
379 Type *Int32Ty = Type::getInt32Ty(Context);
380 Metadata *Ops[3] = {
381 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
382 MDString::get(Context, Key), Val};
383 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
384}
385void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
386 Constant *Val) {
387 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
388}
389void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
390 uint32_t Val) {
391 Type *Int32Ty = Type::getInt32Ty(Context);
392 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
393}
394void Module::addModuleFlag(MDNode *Node) {
395 assert(Node->getNumOperands() == 3 &&
396 "Invalid number of operands for module flag!");
397 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
398 isa<MDString>(Node->getOperand(1)) &&
399 "Invalid operand types for module flag!");
400 getOrInsertModuleFlagsMetadata()->addOperand(Node);
401}
402
403void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
404 Metadata *Val) {
405 NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata();
406 // Replace the flag if it already exists.
407 for (MDNode *Flag : ModFlags->operands()) {
408 if (cast<MDString>(Flag->getOperand(1))->getString() == Key) {
409 Flag->replaceOperandWith(2, Val);
410 return;
411 }
412 }
413 addModuleFlag(Behavior, Key, Val);
414}
415void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
416 Constant *Val) {
417 setModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
418}
419void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
420 uint32_t Val) {
421 Type *Int32Ty = Type::getInt32Ty(Context);
422 setModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
423}
424
425void Module::setDataLayout(StringRef Desc) { DL = DataLayout(Desc); }
426
427void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
428
429DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
430 return cast<DICompileUnit>(CUs->getOperand(Idx));
431}
432DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
433 return cast<DICompileUnit>(CUs->getOperand(Idx));
434}
435
436void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
437 while (CUs && (Idx < CUs->getNumOperands()) &&
438 ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
439 ++Idx;
440}
441
442iterator_range<Module::global_object_iterator> Module::global_objects() {
443 return concat<GlobalObject>(functions(), globals());
444}
446Module::global_objects() const {
447 return concat<const GlobalObject>(functions(), globals());
448}
449
450iterator_range<Module::global_value_iterator> Module::global_values() {
451 return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs());
452}
454Module::global_values() const {
455 return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs());
456}
457
458//===----------------------------------------------------------------------===//
459// Methods to control the materialization of GlobalValues in the Module.
460//
461void Module::setMaterializer(GVMaterializer *GVM) {
462 assert(!Materializer &&
463 "Module already has a GVMaterializer. Call materializeAll"
464 " to clear it out before setting another one.");
465 Materializer.reset(GVM);
466}
467
468Error Module::materialize(GlobalValue *GV) {
469 if (!Materializer)
470 return Error::success();
471
472 return Materializer->materialize(GV);
473}
474
475Error Module::materializeAll() {
476 if (!Materializer)
477 return Error::success();
478 std::unique_ptr<GVMaterializer> M = std::move(Materializer);
479 return M->materializeModule();
480}
481
482Error Module::materializeMetadata() {
483 if (!Materializer)
484 return Error::success();
485 return Materializer->materializeMetadata();
486}
487
488//===----------------------------------------------------------------------===//
489// Other module related stuff.
490//
491
492std::vector<StructType *> Module::getIdentifiedStructTypes() const {
493 // If we have a materializer, it is possible that some unread function
494 // uses a type that is currently not visible to a TypeFinder, so ask
495 // the materializer which types it created.
496 if (Materializer)
497 return Materializer->getIdentifiedStructTypes();
498
499 std::vector<StructType *> Ret;
500 TypeFinder SrcStructTypes;
501 SrcStructTypes.run(*this, true);
502 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
503 return Ret;
504}
505
506std::string Module::getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id,
507 const FunctionType *Proto) {
508 auto Encode = [&BaseName](unsigned Suffix) {
509 return (Twine(BaseName) + "." + Twine(Suffix)).str();
510 };
511
512 {
513 // fast path - the prototype is already known
514 auto UinItInserted = UniquedIntrinsicNames.insert({{Id, Proto}, 0});
515 if (!UinItInserted.second)
516 return Encode(UinItInserted.first->second);
517 }
518
519 // Not known yet. A new entry was created with index 0. Check if there already
520 // exists a matching declaration, or select a new entry.
521
522 // Start looking for names with the current known maximum count (or 0).
523 auto NiidItInserted = CurrentIntrinsicIds.insert({BaseName, 0});
524 unsigned Count = NiidItInserted.first->second;
525
526 // This might be slow if a whole population of intrinsics already existed, but
527 // we cache the values for later usage.
528 std::string NewName;
529 while (true) {
530 NewName = Encode(Count);
531 GlobalValue *F = getNamedValue(NewName);
532 if (!F) {
533 // Reserve this entry for the new proto
534 UniquedIntrinsicNames[{Id, Proto}] = Count;
535 break;
536 }
537
538 // A declaration with this name already exists. Remember it.
539 FunctionType *FT = dyn_cast<FunctionType>(F->getValueType());
540 auto UinItInserted = UniquedIntrinsicNames.insert({{Id, FT}, Count});
541 if (FT == Proto) {
542 // It was a declaration for our prototype. This entry was allocated in the
543 // beginning. Update the count to match the existing declaration.
544 UinItInserted.first->second = Count;
545 break;
546 }
547
548 ++Count;
549 }
550
551 NiidItInserted.first->second = Count + 1;
552
553 return NewName;
554}
555
556// dropAllReferences() - This function causes all the subelements to "let go"
557// of all references that they are maintaining. This allows one to 'delete' a
558// whole module at a time, even though there may be circular references... first
559// all references are dropped, and all use counts go to zero. Then everything
560// is deleted for real. Note that no operations are valid on an object that
561// has "dropped all references", except operator delete.
562//
563void Module::dropAllReferences() {
564 for (Function &F : *this)
565 F.dropAllReferences();
566
567 for (GlobalVariable &GV : globals())
569
570 for (GlobalAlias &GA : aliases())
571 GA.dropAllReferences();
572
573 for (GlobalIFunc &GIF : ifuncs())
574 GIF.dropAllReferences();
575}
576
577unsigned Module::getNumberRegisterParameters() const {
578 auto *Val =
579 cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
580 if (!Val)
581 return 0;
582 return cast<ConstantInt>(Val->getValue())->getZExtValue();
583}
584
585unsigned Module::getDwarfVersion() const {
586 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
587 if (!Val)
588 return 0;
589 return cast<ConstantInt>(Val->getValue())->getZExtValue();
590}
591
592bool Module::isDwarf64() const {
593 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("DWARF64"));
594 return Val && cast<ConstantInt>(Val->getValue())->isOne();
595}
596
597unsigned Module::getCodeViewFlag() const {
598 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
599 if (!Val)
600 return 0;
601 return cast<ConstantInt>(Val->getValue())->getZExtValue();
602}
603
604unsigned Module::getInstructionCount() const {
605 unsigned NumInstrs = 0;
606 for (const Function &F : FunctionList)
607 NumInstrs += F.getInstructionCount();
608 return NumInstrs;
609}
610
611Comdat *Module::getOrInsertComdat(StringRef Name) {
612 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
613 Entry.second.Name = &Entry;
614 return &Entry.second;
615}
616
617PICLevel::Level Module::getPICLevel() const {
618 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
619
620 if (!Val)
621 return PICLevel::NotPIC;
622
623 return static_cast<PICLevel::Level>(
624 cast<ConstantInt>(Val->getValue())->getZExtValue());
625}
626
627void Module::setPICLevel(PICLevel::Level PL) {
628 // The merge result of a non-PIC object and a PIC object can only be reliably
629 // used as a non-PIC object, so use the Min merge behavior.
630 addModuleFlag(ModFlagBehavior::Min, "PIC Level", PL);
631}
632
633PIELevel::Level Module::getPIELevel() const {
634 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
635
636 if (!Val)
637 return PIELevel::Default;
638
639 return static_cast<PIELevel::Level>(
640 cast<ConstantInt>(Val->getValue())->getZExtValue());
641}
642
643void Module::setPIELevel(PIELevel::Level PL) {
644 addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
645}
646
647std::optional<CodeModel::Model> Module::getCodeModel() const {
648 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
649
650 if (!Val)
651 return std::nullopt;
652
653 return static_cast<CodeModel::Model>(
654 cast<ConstantInt>(Val->getValue())->getZExtValue());
655}
656
657void Module::setCodeModel(CodeModel::Model CL) {
658 // Linking object files with different code models is undefined behavior
659 // because the compiler would have to generate additional code (to span
660 // longer jumps) if a larger code model is used with a smaller one.
661 // Therefore we will treat attempts to mix code models as an error.
662 addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
663}
664
665std::optional<uint64_t> Module::getLargeDataThreshold() const {
666 auto *Val =
667 cast_or_null<ConstantAsMetadata>(getModuleFlag("Large Data Threshold"));
668
669 if (!Val)
670 return std::nullopt;
671
672 return cast<ConstantInt>(Val->getValue())->getZExtValue();
673}
674
675void Module::setLargeDataThreshold(uint64_t Threshold) {
676 // Since the large data threshold goes along with the code model, the merge
677 // behavior is the same.
678 addModuleFlag(ModFlagBehavior::Error, "Large Data Threshold",
679 ConstantInt::get(Type::getInt64Ty(Context), Threshold));
680}
681
682void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) {
683 if (Kind == ProfileSummary::PSK_CSInstr)
684 setModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M);
685 else
686 setModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
687}
688
689Metadata *Module::getProfileSummary(bool IsCS) const {
690 return (IsCS ? getModuleFlag("CSProfileSummary")
691 : getModuleFlag("ProfileSummary"));
692}
693
694bool Module::getSemanticInterposition() const {
695 Metadata *MF = getModuleFlag("SemanticInterposition");
696
697 auto *Val = cast_or_null<ConstantAsMetadata>(MF);
698 if (!Val)
699 return false;
700
701 return cast<ConstantInt>(Val->getValue())->getZExtValue();
702}
703
704void Module::setSemanticInterposition(bool SI) {
705 addModuleFlag(ModFlagBehavior::Error, "SemanticInterposition", SI);
706}
707
708void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
709 OwnedMemoryBuffer = std::move(MB);
710}
711
712bool Module::getRtLibUseGOT() const {
713 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
714 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
715}
716
717void Module::setRtLibUseGOT() {
718 addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
719}
720
721bool Module::getDirectAccessExternalData() const {
722 auto *Val = cast_or_null<ConstantAsMetadata>(
723 getModuleFlag("direct-access-external-data"));
724 if (Val)
725 return cast<ConstantInt>(Val->getValue())->getZExtValue() > 0;
726 return getPICLevel() == PICLevel::NotPIC;
727}
728
729void Module::setDirectAccessExternalData(bool Value) {
730 addModuleFlag(ModFlagBehavior::Max, "direct-access-external-data", Value);
731}
732
733UWTableKind Module::getUwtable() const {
734 if (auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("uwtable")))
735 return UWTableKind(cast<ConstantInt>(Val->getValue())->getZExtValue());
736 return UWTableKind::None;
737}
738
739void Module::setUwtable(UWTableKind Kind) {
740 addModuleFlag(ModFlagBehavior::Max, "uwtable", uint32_t(Kind));
741}
742
743FramePointerKind Module::getFramePointer() const {
744 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("frame-pointer"));
745 return static_cast<FramePointerKind>(
746 Val ? cast<ConstantInt>(Val->getValue())->getZExtValue() : 0);
747}
748
749void Module::setFramePointer(FramePointerKind Kind) {
750 addModuleFlag(ModFlagBehavior::Max, "frame-pointer", static_cast<int>(Kind));
751}
752
753StringRef Module::getStackProtectorGuard() const {
754 Metadata *MD = getModuleFlag("stack-protector-guard");
755 if (auto *MDS = dyn_cast_or_null<MDString>(MD))
756 return MDS->getString();
757 return {};
758}
759
760void Module::setStackProtectorGuard(StringRef Kind) {
761 MDString *ID = MDString::get(getContext(), Kind);
762 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard", ID);
763}
764
765StringRef Module::getStackProtectorGuardReg() const {
766 Metadata *MD = getModuleFlag("stack-protector-guard-reg");
767 if (auto *MDS = dyn_cast_or_null<MDString>(MD))
768 return MDS->getString();
769 return {};
770}
771
772void Module::setStackProtectorGuardReg(StringRef Reg) {
773 MDString *ID = MDString::get(getContext(), Reg);
774 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-reg", ID);
775}
776
777StringRef Module::getStackProtectorGuardSymbol() const {
778 Metadata *MD = getModuleFlag("stack-protector-guard-symbol");
779 if (auto *MDS = dyn_cast_or_null<MDString>(MD))
780 return MDS->getString();
781 return {};
782}
783
784void Module::setStackProtectorGuardSymbol(StringRef Symbol) {
785 MDString *ID = MDString::get(getContext(), Symbol);
786 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-symbol", ID);
787}
788
789int Module::getStackProtectorGuardOffset() const {
790 Metadata *MD = getModuleFlag("stack-protector-guard-offset");
791 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
792 return CI->getSExtValue();
793 return INT_MAX;
794}
795
796void Module::setStackProtectorGuardOffset(int Offset) {
797 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-offset", Offset);
798}
799
800unsigned Module::getOverrideStackAlignment() const {
801 Metadata *MD = getModuleFlag("override-stack-alignment");
802 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
803 return CI->getZExtValue();
804 return 0;
805}
806
807unsigned Module::getMaxTLSAlignment() const {
808 Metadata *MD = getModuleFlag("MaxTLSAlign");
809 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
810 return CI->getZExtValue();
811 return 0;
812}
813
814void Module::setOverrideStackAlignment(unsigned Align) {
815 addModuleFlag(ModFlagBehavior::Error, "override-stack-alignment", Align);
816}
817
818static void addSDKVersionMD(const VersionTuple &V, Module &M, StringRef Name) {
820 Entries.push_back(V.getMajor());
821 if (auto Minor = V.getMinor()) {
822 Entries.push_back(*Minor);
823 if (auto Subminor = V.getSubminor())
824 Entries.push_back(*Subminor);
825 // Ignore the 'build' component as it can't be represented in the object
826 // file.
827 }
828 M.addModuleFlag(Module::ModFlagBehavior::Warning, Name,
829 ConstantDataArray::get(M.getContext(), Entries));
830}
831
832void Module::setSDKVersion(const VersionTuple &V) {
833 addSDKVersionMD(V, *this, "SDK Version");
834}
835
837 auto *CM = dyn_cast_or_null<ConstantAsMetadata>(MD);
838 if (!CM)
839 return {};
840 auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
841 if (!Arr)
842 return {};
843 auto getVersionComponent = [&](unsigned Index) -> std::optional<unsigned> {
844 if (Index >= Arr->getNumElements())
845 return std::nullopt;
846 return (unsigned)Arr->getElementAsInteger(Index);
847 };
848 auto Major = getVersionComponent(0);
849 if (!Major)
850 return {};
852 if (auto Minor = getVersionComponent(1)) {
853 Result = VersionTuple(*Major, *Minor);
854 if (auto Subminor = getVersionComponent(2)) {
855 Result = VersionTuple(*Major, *Minor, *Subminor);
856 }
857 }
858 return Result;
859}
860
861VersionTuple Module::getSDKVersion() const {
862 return getSDKVersionMD(getModuleFlag("SDK Version"));
863}
864
866 const Module &M, SmallVectorImpl<GlobalValue *> &Vec, bool CompilerUsed) {
867 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
868 GlobalVariable *GV = M.getGlobalVariable(Name);
869 if (!GV || !GV->hasInitializer())
870 return GV;
871
872 const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
873 for (Value *Op : Init->operands()) {
874 GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts());
875 Vec.push_back(G);
876 }
877 return GV;
878}
879
880void Module::setPartialSampleProfileRatio(const ModuleSummaryIndex &Index) {
881 if (auto *SummaryMD = getProfileSummary(/*IsCS*/ false)) {
882 std::unique_ptr<ProfileSummary> ProfileSummary(
883 ProfileSummary::getFromMD(SummaryMD));
884 if (ProfileSummary) {
885 if (ProfileSummary->getKind() != ProfileSummary::PSK_Sample ||
887 return;
888 uint64_t BlockCount = Index.getBlockCount();
889 uint32_t NumCounts = ProfileSummary->getNumCounts();
890 if (!NumCounts)
891 return;
892 double Ratio = (double)BlockCount / NumCounts;
894 setProfileSummary(ProfileSummary->getMD(getContext()),
895 ProfileSummary::PSK_Sample);
896 }
897 }
898}
899
900StringRef Module::getDarwinTargetVariantTriple() const {
901 if (const auto *MD = getModuleFlag("darwin.target_variant.triple"))
902 return cast<MDString>(MD)->getString();
903 return "";
904}
905
906void Module::setDarwinTargetVariantTriple(StringRef T) {
907 addModuleFlag(ModFlagBehavior::Warning, "darwin.target_variant.triple",
908 MDString::get(getContext(), T));
909}
910
911VersionTuple Module::getDarwinTargetVariantSDKVersion() const {
912 return getSDKVersionMD(getModuleFlag("darwin.target_variant.SDK Version"));
913}
914
915void Module::setDarwinTargetVariantSDKVersion(VersionTuple Version) {
916 addSDKVersionMD(Version, *this, "darwin.target_variant.SDK Version");
917}
This file defines the StringMap class.
Lower uses of LDS variables from non kernel functions
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil globals
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
std::string Name
uint32_t Index
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1313
uint64_t Offset
Definition: ELF_riscv.cpp:478
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Module.h This file contains the declarations for the Module class.
static bool lookup(const GsymReader &GR, DataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
Definition: InlineInfo.cpp:108
#define F(x, y, z)
Definition: MD5.cpp:55
#define G(x, y, z)
Definition: MD5.cpp:56
unsigned Reg
static Constant * getOrInsertGlobal(Module &M, StringRef Name, Type *Ty)
This file contains the declarations for metadata subclasses.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
StandardInstrumentations SI(Mod->getContext(), Debug, VerifyEach)
llvm::cl::opt< bool > UseNewDbgInfoFormat
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static VersionTuple getSDKVersionMD(Metadata *MD)
Definition: Module.cpp:836
static void addSDKVersionMD(const VersionTuple &V, Module &M, StringRef Name)
Definition: Module.cpp:818
This file defines the SmallString class.
This file defines the SmallVector class.
Defines the llvm::VersionTuple class, which represents a version in the form major[....
ConstantArray - Constant Array Declarations.
Definition: Constants.h:427
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
This is an important base class in LLVM.
Definition: Constant.h:42
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:170
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
Metadata node.
Definition: Metadata.h:1069
A single uniqued string.
Definition: Metadata.h:720
Root of the metadata hierarchy.
Definition: Metadata.h:62
Class to hold module path string table and global value map, and encapsulate methods for operating on...
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:1731
StringRef getName() const
Definition: Metadata.cpp:1442
iterator_range< op_iterator > operands()
Definition: Metadata.h:1827
void setPartialProfileRatio(double R)
Metadata * getMD(LLVMContext &Context, bool AddPartialField=true, bool AddPartialProfileRatioField=true)
Return summary information as metadata.
uint32_t getNumCounts() const
bool isPartialProfile() const
Kind getKind() const
A random number generator.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
TypeFinder - Walk over a module, identifying all of the types that are used by the module.
Definition: TypeFinder.h:31
iterator end()
Definition: TypeFinder.h:52
void run(const Module &M, bool onlyNamed)
Definition: TypeFinder.cpp:34
iterator begin()
Definition: TypeFinder.h:51
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
void dropAllReferences()
Drop all references to operands.
Definition: User.h:345
This class provides a symbol table of name/value pairs.
LLVM Value Representation.
Definition: Value.h:74
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:29
An efficient, type-erasing, non-owning reference to a callable.
A range adaptor for a pair of iterators.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
Key
PAL metadata keys.
@ Entry
Definition: COFF.h:844
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:148
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
FramePointerKind
Definition: CodeGen.h:90
UWTableKind
Definition: CodeGen.h:120
GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition: Module.cpp:865
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
Description of the encoding of one expression Op.