LLVM 24.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"
43#include "llvm/Support/Error.h"
45#include "llvm/Support/Path.h"
49#include <cassert>
50#include <cstdint>
51#include <memory>
52#include <optional>
53#include <utility>
54#include <vector>
55
56using namespace llvm;
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
74 : Context(C), ValSymTab(std::make_unique<ValueSymbolTable>(-1)),
75 ModuleID(std::string(MID)), SourceFileName(std::string(MID)) {
76 Context.addModule(this);
77}
78
80 assert(&Context == &Other.Context && "Module must be in the same Context");
81
82 dropAllReferences();
83
84 ModuleID = std::move(Other.ModuleID);
85 SourceFileName = std::move(Other.SourceFileName);
86
87 GlobalList.clear();
88 GlobalList.splice(GlobalList.begin(), Other.GlobalList);
89
90 FunctionList.clear();
91 FunctionList.splice(FunctionList.begin(), Other.FunctionList);
92
93 AliasList.clear();
94 AliasList.splice(AliasList.begin(), Other.AliasList);
95
96 IFuncList.clear();
97 IFuncList.splice(IFuncList.begin(), Other.IFuncList);
98
99 NamedMDList.clear();
100 NamedMDList.splice(NamedMDList.begin(), Other.NamedMDList);
101 for (NamedMDNode &NMD : NamedMDList)
102 NMD.setParent(this);
103
104 NamedMDSymTab = std::move(Other.NamedMDSymTab);
105 ComdatSymTab = std::move(Other.ComdatSymTab);
106 GlobalScopeAsm = std::move(Other.GlobalScopeAsm);
107 OwnedMemoryBuffer = std::move(Other.OwnedMemoryBuffer);
108 Materializer = std::move(Other.Materializer);
109 TargetTriple = std::move(Other.TargetTriple);
110 DL = std::move(Other.DL);
111 CurrentIntrinsicIds = std::move(Other.CurrentIntrinsicIds);
112 UniquedIntrinsicNames = std::move(Other.UniquedIntrinsicNames);
113 ModuleFlags = std::move(Other.ModuleFlags);
114 Context.addModule(this);
115 return *this;
116}
117
119 Context.removeModule(this);
120 dropAllReferences();
121 GlobalList.clear();
122 FunctionList.clear();
123 AliasList.clear();
124 IFuncList.clear();
125}
126
128 if (auto *DeclareIntrinsicFn =
129 Intrinsic::getDeclarationIfExists(this, Intrinsic::dbg_declare)) {
130 assert((!isMaterialized() || DeclareIntrinsicFn->hasZeroLiveUses()) &&
131 "Debug declare intrinsic should have had uses removed.");
132 DeclareIntrinsicFn->eraseFromParent();
133 }
134 if (auto *ValueIntrinsicFn =
135 Intrinsic::getDeclarationIfExists(this, Intrinsic::dbg_value)) {
136 assert((!isMaterialized() || ValueIntrinsicFn->hasZeroLiveUses()) &&
137 "Debug value intrinsic should have had uses removed.");
138 ValueIntrinsicFn->eraseFromParent();
139 }
140 if (auto *AssignIntrinsicFn =
141 Intrinsic::getDeclarationIfExists(this, Intrinsic::dbg_assign)) {
142 assert((!isMaterialized() || AssignIntrinsicFn->hasZeroLiveUses()) &&
143 "Debug assign intrinsic should have had uses removed.");
144 AssignIntrinsicFn->eraseFromParent();
145 }
146 if (auto *LabelntrinsicFn =
147 Intrinsic::getDeclarationIfExists(this, Intrinsic::dbg_label)) {
148 assert((!isMaterialized() || LabelntrinsicFn->hasZeroLiveUses()) &&
149 "Debug label intrinsic should have had uses removed.");
150 LabelntrinsicFn->eraseFromParent();
151 }
152}
153
154std::unique_ptr<RandomNumberGenerator>
155Module::createRNG(const StringRef Name) const {
156 SmallString<32> Salt(Name);
157
158 // This RNG is guaranteed to produce the same random stream only
159 // when the Module ID and thus the input filename is the same. This
160 // might be problematic if the input filename extension changes
161 // (e.g. from .c to .bc or .ll).
162 //
163 // We could store this salt in NamedMetadata, but this would make
164 // the parameter non-const. This would unfortunately make this
165 // interface unusable by any Machine passes, since they only have a
166 // const reference to their IR Module. Alternatively we can always
167 // store salt metadata from the Module constructor.
168 Salt += sys::path::filename(getModuleIdentifier());
169
170 return std::unique_ptr<RandomNumberGenerator>(
171 new RandomNumberGenerator(Salt));
172}
173
174/// getNamedValue - Return the first global value in the module with
175/// the specified name, of arbitrary type. This method returns null
176/// if a global with the specified name is not found.
178 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
179}
180
181unsigned Module::getNumNamedValues() const {
182 return getValueSymbolTable().size();
183}
184
185/// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
186/// This ID is uniqued across modules in the current LLVMContext.
187unsigned Module::getMDKindID(StringRef Name) const {
188 return Context.getMDKindID(Name);
189}
190
191/// getMDKindNames - Populate client supplied SmallVector with the name for
192/// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
193/// so it is filled in as an empty string.
195 return Context.getMDKindNames(Result);
196}
197
199 return Context.getOperandBundleTags(Result);
200}
201
202//===----------------------------------------------------------------------===//
203// Methods for easy access to the functions in the module.
204//
205
206// getOrInsertFunction - Look up the specified function in the module symbol
207// table. If it does not exist, add a prototype for the function and return
208// it. This is nice because it allows most passes to get away with not handling
209// the symbol table directly for this common task.
210//
213 function_ref<void(Function &)> InitCallback) {
214 assert(InitCallback && "missing init callback");
215 assert(!Name.empty() && !Name.starts_with("llvm.") &&
216 "intrinsics and unnamed functions are not supported");
217
218 Function *New = nullptr;
219 Value *F = ValSymTab->lookupOrInsert(Name, [&] {
221 DL.getProgramAddressSpace(), "", this);
222 return New;
223 });
224 if (New)
225 InitCallback(*New);
226 return {Ty, F};
227}
228
231 // Intrinsics are set up from their name on construction.
232 if (Name.empty() || Name.starts_with("llvm.")) {
233 if (GlobalValue *F = getNamedValue(Name))
234 return {Ty, F};
235
237 DL.getProgramAddressSpace(), Name, this);
238 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
239 New->setAttributes(AttributeList);
240 return {Ty, New};
241 }
242
243 return getOrInsertFunction(
244 Name, Ty, [&](Function &New) { New.setAttributes(AttributeList); });
245}
246
248 return getOrInsertFunction(Name, Ty, AttributeList());
249}
250
251// getFunction - Look up the specified function in the module symbol table.
252// If it does not exist, return null.
253//
255 return dyn_cast_or_null<Function>(getNamedValue(Name));
256}
257
258//===----------------------------------------------------------------------===//
259// Methods for easy access to the global variables in the module.
260//
261
262/// getGlobalVariable - Look up the specified global variable in the module
263/// symbol table. If it does not exist, return null. The type argument
264/// should be the underlying type of the global, i.e., it should not have
265/// the top-level PointerType, which represents the address of the global.
266/// If AllowLocal is set to true, this function will return types that
267/// have an local. By default, these types are not returned.
268///
270 bool AllowLocal) const {
271 if (GlobalVariable *Result =
272 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
273 if (AllowLocal || !Result->hasLocalLinkage())
274 return Result;
275 return nullptr;
276}
277
278/// getOrInsertGlobal - Look up the specified global in the module symbol table.
279/// If it does not exist, add a declaration of the global and return it.
280/// Otherwise, return the existing global.
282 StringRef Name, Type *Ty,
283 function_ref<GlobalVariable *()> CreateGlobalCallback) {
284 // See if we have a definition for the specified global already.
285 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
286 if (!GV)
287 GV = CreateGlobalCallback();
288 assert(GV && "The CreateGlobalCallback is expected to create a global");
289
290 // Otherwise, we just found the existing function or a prototype.
291 return GV;
292}
293
294// Overload to construct a global variable using its constructor's defaults.
296 return getOrInsertGlobal(Name, Ty, [&] {
297 return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
298 nullptr, Name);
299 });
300}
301
302//===----------------------------------------------------------------------===//
303// Methods for easy access to the global variables in the module.
304//
305
306// getNamedAlias - Look up the specified global in the module symbol table.
307// If it does not exist, return null.
308//
310 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
311}
312
314 return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
315}
316
317/// getNamedMetadata - Return the first NamedMDNode in the module with the
318/// specified name. This method returns null if a NamedMDNode with the
319/// specified name is not found.
321 return NamedMDSymTab.lookup(Name);
322}
323
324/// getOrInsertNamedMetadata - Return the first named MDNode in the module
325/// with the specified name. This method returns a new NamedMDNode if a
326/// NamedMDNode with the specified name is not found.
328 NamedMDNode *&NMD = NamedMDSymTab[Name];
329 if (!NMD) {
330 NMD = new NamedMDNode(Name);
331 NMD->setParent(this);
332 insertNamedMDNode(NMD);
333 if (Name == "llvm.module.flags")
334 ModuleFlags = NMD;
335 }
336 return NMD;
337}
338
339/// eraseNamedMetadata - Remove the given NamedMDNode from this module and
340/// delete it.
342 NamedMDSymTab.erase(NMD->getName());
343 if (NMD == ModuleFlags)
344 ModuleFlags = nullptr;
345 eraseNamedMDNode(NMD);
346}
347
348bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
350 uint64_t Val = Behavior->getLimitedValue();
351 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
352 MFB = static_cast<ModFlagBehavior>(Val);
353 return true;
354 }
355 }
356 return false;
357}
358
359/// getModuleFlagsMetadata - Returns the module flags in the provided vector.
360void Module::
361getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
362 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
363 if (!ModFlags) return;
364
365 for (const MDNode *Flag : ModFlags->operands()) {
366 // The verifier will catch errors, so no need to check them here.
367 auto *MFBConstant = mdconst::extract<ConstantInt>(Flag->getOperand(0));
368 auto MFB = static_cast<ModFlagBehavior>(MFBConstant->getLimitedValue());
369 MDString *Key = cast<MDString>(Flag->getOperand(1));
370 Metadata *Val = Flag->getOperand(2);
371 Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
372 }
373}
374
375/// Return the corresponding value if Key appears in module flags, otherwise
376/// return null.
378 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
379 if (!ModFlags)
380 return nullptr;
381 for (const MDNode *Flag : ModFlags->operands()) {
382 if (Key == cast<MDString>(Flag->getOperand(1))->getString())
383 return Flag->getOperand(2);
384 }
385 return nullptr;
386}
387
388/// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
389/// represents module-level flags. If module-level flags aren't found, it
390/// creates the named metadata that contains them.
392 if (ModuleFlags)
393 return ModuleFlags;
394 return getOrInsertNamedMetadata("llvm.module.flags");
395}
396
397/// addModuleFlag - Add a module-level flag to the module-level flags
398/// metadata. It will create the module-level flags named metadata if it doesn't
399/// already exist.
400void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
401 Metadata *Val) {
402 Type *Int32Ty = Type::getInt32Ty(Context);
403 Metadata *Ops[3] = {
404 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
405 MDString::get(Context, Key), Val};
406 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
407}
408void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
409 Constant *Val) {
410 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
411}
412void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
413 uint64_t Val) {
414 Type *Int64Ty = Type::getInt64Ty(Context);
415 addModuleFlag(Behavior, Key, ConstantInt::get(Int64Ty, Val));
416}
417void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
418 uint32_t Val) {
419 Type *Int32Ty = Type::getInt32Ty(Context);
420 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
421}
423 assert(Node->getNumOperands() == 3 &&
424 "Invalid number of operands for module flag!");
425 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
426 isa<MDString>(Node->getOperand(1)) &&
427 "Invalid operand types for module flag!");
428 getOrInsertModuleFlagsMetadata()->addOperand(Node);
429}
430
431void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
432 Metadata *Val) {
433 NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata();
434 // Replace the flag if it already exists.
435 for (unsigned i = 0; i < ModFlags->getNumOperands(); ++i) {
436 MDNode *Flag = ModFlags->getOperand(i);
437 if (cast<MDString>(Flag->getOperand(1))->getString() == Key) {
438 Type *Int32Ty = Type::getInt32Ty(Context);
439 Metadata *Ops[3] = {
440 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
441 MDString::get(Context, Key), Val};
442 ModFlags->setOperand(i, MDNode::get(Context, Ops));
443 return;
444 }
445 }
446 addModuleFlag(Behavior, Key, Val);
447}
448void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
449 Constant *Val) {
450 setModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
451}
452void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
453 uint64_t Val) {
454 Type *Int64Ty = Type::getInt64Ty(Context);
455 setModuleFlag(Behavior, Key, ConstantInt::get(Int64Ty, Val));
456}
457void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
458 uint32_t Val) {
459 Type *Int32Ty = Type::getInt32Ty(Context);
460 setModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
461}
462
464
466
468 return cast<DICompileUnit>(CUs->getOperand(Idx));
469}
471 return cast<DICompileUnit>(CUs->getOperand(Idx));
472}
473
474void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
475 while (CUs && (Idx < CUs->getNumOperands()) &&
476 ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
477 ++Idx;
478}
479
482}
486}
487
489 return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs());
490}
492Module::global_values() const {
493 return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs());
494}
495
496//===----------------------------------------------------------------------===//
497// Methods to control the materialization of GlobalValues in the Module.
498//
500 assert(!Materializer &&
501 "Module already has a GVMaterializer. Call materializeAll"
502 " to clear it out before setting another one.");
503 Materializer.reset(GVM);
504}
505
507 if (!Materializer)
508 return Error::success();
509
510 return Materializer->materialize(GV);
511}
512
514 if (!Materializer)
515 return Error::success();
516 std::unique_ptr<GVMaterializer> M = std::move(Materializer);
517 return M->materializeModule();
518}
519
521 llvm::TimeTraceScope timeScope("Materialize metadata");
522 if (!Materializer)
523 return Error::success();
524 return Materializer->materializeMetadata();
525}
526
527//===----------------------------------------------------------------------===//
528// Other module related stuff.
529//
530
531std::vector<StructType *> Module::getIdentifiedStructTypes() const {
532 // If we have a materializer, it is possible that some unread function
533 // uses a type that is currently not visible to a TypeFinder, so ask
534 // the materializer which types it created.
535 if (Materializer)
536 return Materializer->getIdentifiedStructTypes();
537
538 std::vector<StructType *> Ret;
539 TypeFinder SrcStructTypes;
540 SrcStructTypes.run(*this, true);
541 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
542 return Ret;
543}
544
546 const FunctionType *Proto) {
547 auto Encode = [&BaseName](unsigned Suffix) {
548 return (Twine(BaseName) + "." + Twine(Suffix)).str();
549 };
550
551 {
552 // fast path - the prototype is already known
553 auto UinItInserted = UniquedIntrinsicNames.insert({{Id, Proto}, 0});
554 if (!UinItInserted.second)
555 return Encode(UinItInserted.first->second);
556 }
557
558 // Not known yet. A new entry was created with index 0. Check if there already
559 // exists a matching declaration, or select a new entry.
560
561 // Start looking for names with the current known maximum count (or 0).
562 auto NiidItInserted = CurrentIntrinsicIds.insert({BaseName, 0});
563 unsigned Count = NiidItInserted.first->second;
564
565 // This might be slow if a whole population of intrinsics already existed, but
566 // we cache the values for later usage.
567 std::string NewName;
568 while (true) {
569 NewName = Encode(Count);
570 GlobalValue *F = getNamedValue(NewName);
571 if (!F) {
572 // Reserve this entry for the new proto
573 UniquedIntrinsicNames[{Id, Proto}] = Count;
574 break;
575 }
576
577 // A declaration with this name already exists. Remember it.
578 FunctionType *FT = dyn_cast<FunctionType>(F->getValueType());
579 auto UinItInserted = UniquedIntrinsicNames.insert({{Id, FT}, Count});
580 if (FT == Proto) {
581 // It was a declaration for our prototype. This entry was allocated in the
582 // beginning. Update the count to match the existing declaration.
583 UinItInserted.first->second = Count;
584 break;
585 }
586
587 ++Count;
588 }
589
590 NiidItInserted.first->second = Count + 1;
591
592 return NewName;
593}
594
595// dropAllReferences() - This function causes all the subelements to "let go"
596// of all references that they are maintaining. This allows one to 'delete' a
597// whole module at a time, even though there may be circular references... first
598// all references are dropped, and all use counts go to zero. Then everything
599// is deleted for real. Note that no operations are valid on an object that
600// has "dropped all references", except operator delete.
601//
603 for (Function &F : *this)
604 F.dropAllReferences();
605
606 for (GlobalVariable &GV : globals())
608
609 for (GlobalAlias &GA : aliases())
610 GA.dropAllReferences();
611
612 for (GlobalIFunc &GIF : ifuncs())
613 GIF.dropAllReferences();
614}
615
617 auto *Val =
618 cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
619 if (!Val)
620 return 0;
621 return cast<ConstantInt>(Val->getValue())->getZExtValue();
622}
623
624unsigned Module::getDwarfVersion() const {
625 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
626 if (!Val)
627 return 0;
628 return cast<ConstantInt>(Val->getValue())->getZExtValue();
629}
630
631bool Module::isDwarf64() const {
632 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("DWARF64"));
633 return Val && cast<ConstantInt>(Val->getValue())->isOne();
634}
635
636unsigned Module::getCodeViewFlag() const {
637 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
638 if (!Val)
639 return 0;
640 return cast<ConstantInt>(Val->getValue())->getZExtValue();
641}
642
643unsigned Module::getInstructionCount() const {
644 unsigned NumInstrs = 0;
645 for (const Function &F : FunctionList)
646 NumInstrs += F.getInstructionCount();
647 return NumInstrs;
648}
649
651 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
652 Entry.second.Name = &Entry;
653 return &Entry.second;
654}
655
657 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
658
659 if (!Val)
660 return PICLevel::NotPIC;
661
662 return static_cast<PICLevel::Level>(
663 cast<ConstantInt>(Val->getValue())->getZExtValue());
664}
665
667 // The merge result of a non-PIC object and a PIC object can only be reliably
668 // used as a non-PIC object, so use the Min merge behavior.
669 addModuleFlag(ModFlagBehavior::Min, "PIC Level", PL);
670}
671
673 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
674
675 if (!Val)
676 return PIELevel::Default;
677
678 return static_cast<PIELevel::Level>(
679 cast<ConstantInt>(Val->getValue())->getZExtValue());
680}
681
683 addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
684}
685
686std::optional<CodeModel::Model> Module::getCodeModel() const {
687 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
688
689 if (!Val)
690 return std::nullopt;
691
692 return static_cast<CodeModel::Model>(
693 cast<ConstantInt>(Val->getValue())->getZExtValue());
694}
695
697 // Linking object files with different code models is undefined behavior
698 // because the compiler would have to generate additional code (to span
699 // longer jumps) if a larger code model is used with a smaller one.
700 // Therefore we will treat attempts to mix code models as an error.
701 addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
702}
703
704unsigned Module::getWCharSize() const {
705 if (auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("wchar_size")))
706 return cast<ConstantInt>(Val->getValue())->getZExtValue();
707 return getTargetTriple().getDefaultWCharSize();
708}
709
710LongDoubleFormat Module::getLongDoubleFormat() const {
711 if (auto *Val = cast_or_null<MDString>(getModuleFlag("long-double-type"))) {
712 if (std::optional<LongDoubleFormat> Format =
713 parseLongDoubleFormat(Val->getString()))
714 return *Format;
715 }
716
717 return getTargetTriple().getDefaultLongDoubleFormat();
718}
719
720void Module::setLongDoubleFormat(LongDoubleFormat Format) {
721 addModuleFlag(ModFlagBehavior::Error, "long-double-type",
723}
724
726 if (auto *Val = cast_or_null<MDString>(getModuleFlag("float-abi")))
727 return *FloatABI::parseABIType(Val->getString());
728 // Without an explicit flag, fall back to the ABI implied by the target
729 // triple.
730 return getTargetTriple().getDefaultFloatABI();
731}
732
734 if (auto *Val = cast_or_null<MDString>(getModuleFlag("thread-model")))
735 return *parseThreadModel(Val->getString());
736 return getTargetTriple().getDefaultThreadModel();
737}
738
740 addModuleFlag(ModFlagBehavior::Error, "thread-model",
742}
743
744ExceptionHandling Module::getExceptionModel() const {
745 if (auto *Val = cast_or_null<MDString>(getModuleFlag("exception-model")))
746 return *parseExceptionModel(Val->getString());
747 return getTargetTriple().getDefaultExceptionHandling();
748}
749
750DebuggerKind Module::getDebuggerTuning() const {
751 if (auto *Val = cast_or_null<MDString>(getModuleFlag("debugger-tuning"))) {
752 if (std::optional<DebuggerKind> Tuning =
753 parseDebuggerTuning(Val->getString()))
754 return *Tuning;
755 }
756
757 return getTargetTriple().getDefaultDebuggerTuning();
758}
759
760void Module::setDebuggerTuning(DebuggerKind Tuning) {
761 assert(Tuning != DebuggerKind::Default &&
762 "removing existing flag not handled");
763
764 addModuleFlag(ModFlagBehavior::Warning, "debugger-tuning",
766}
767
768std::optional<uint64_t> Module::getLargeDataThreshold() const {
769 auto *Val =
770 cast_or_null<ConstantAsMetadata>(getModuleFlag("Large Data Threshold"));
771
772 if (!Val)
773 return std::nullopt;
774
775 return cast<ConstantInt>(Val->getValue())->getZExtValue();
776}
777
779 // Since the large data threshold goes along with the code model, the merge
780 // behavior is the same.
781 addModuleFlag(ModFlagBehavior::Error, "Large Data Threshold",
782 ConstantInt::get(Type::getInt64Ty(Context), Threshold));
783}
784
786 if (Kind == ProfileSummary::PSK_CSInstr)
787 setModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M);
788 else
789 setModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
790}
791
792Metadata *Module::getProfileSummary(bool IsCS) const {
793 return (IsCS ? getModuleFlag("CSProfileSummary")
794 : getModuleFlag("ProfileSummary"));
795}
796
798 Metadata *MF = getModuleFlag("SemanticInterposition");
799
800 auto *Val = cast_or_null<ConstantAsMetadata>(MF);
801 if (!Val)
802 return false;
803
804 return cast<ConstantInt>(Val->getValue())->getZExtValue();
805}
806
808 addModuleFlag(ModFlagBehavior::Error, "SemanticInterposition", SI);
809}
810
811void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
812 OwnedMemoryBuffer = std::move(MB);
813}
814
815bool Module::getRtLibUseGOT() const {
816 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
817 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
818}
819
821 addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
822}
823
826 getModuleFlag("direct-access-external-data"));
827 if (Val)
828 return cast<ConstantInt>(Val->getValue())->getZExtValue() > 0;
829 return getPICLevel() == PICLevel::NotPIC;
830}
831
833 addModuleFlag(ModFlagBehavior::Max, "direct-access-external-data", Value);
834}
835
837 if (auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("uwtable")))
838 return UWTableKind(cast<ConstantInt>(Val->getValue())->getZExtValue());
839 return UWTableKind::None;
840}
841
843 addModuleFlag(ModFlagBehavior::Max, "uwtable", uint32_t(Kind));
844}
845
846FramePointerKind Module::getFramePointer() const {
847 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("frame-pointer"));
848 return static_cast<FramePointerKind>(
849 Val ? cast<ConstantInt>(Val->getValue())->getZExtValue() : 0);
850}
851
852void Module::setFramePointer(FramePointerKind Kind) {
853 addModuleFlag(ModFlagBehavior::Max, "frame-pointer", static_cast<int>(Kind));
854}
855
858 getModuleFlag("stack-protector-guard-record"));
859 return Val && cast<ConstantInt>(Val->getValue())->isOne();
860}
861
863 addModuleFlag(ModFlagBehavior::Max, "stack-protector-guard-record",
864 Flag ? 1 : 0);
865}
866
868 Metadata *MD = getModuleFlag("stack-protector-guard");
869 if (auto *MDS = dyn_cast_or_null<MDString>(MD))
870 return MDS->getString();
871 return {};
872}
873
875 MDString *ID = MDString::get(getContext(), Kind);
876 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard", ID);
877}
878
880 Metadata *MD = getModuleFlag("stack-protector-guard-reg");
881 if (auto *MDS = dyn_cast_or_null<MDString>(MD))
882 return MDS->getString();
883 return {};
884}
885
888 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-reg", ID);
889}
890
892 Metadata *MD = getModuleFlag("stack-protector-guard-symbol");
893 if (auto *MDS = dyn_cast_or_null<MDString>(MD))
894 return MDS->getString();
895 return {};
896}
897
899 MDString *ID = MDString::get(getContext(), Symbol);
900 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-symbol", ID);
901}
902
904 Metadata *MD = getModuleFlag("stack-protector-guard-offset");
906 return CI->getSExtValue();
907 return INT_MAX;
908}
909
911 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-offset", Offset);
912}
913
914std::optional<unsigned> Module::getStackProtectorGuardValueWidth() const {
915 Metadata *MD = getModuleFlag("stack-protector-guard-value-width");
917 return CI->getZExtValue();
918 return std::nullopt;
919}
920
921void Module::setStackProtectorGuardValueWidth(unsigned Width) {
922 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-value-width",
923 Width);
924}
925
926unsigned Module::getOverrideStackAlignment() const {
927 Metadata *MD = getModuleFlag("override-stack-alignment");
929 return CI->getZExtValue();
930 return 0;
931}
932
933unsigned Module::getMaxTLSAlignment() const {
934 Metadata *MD = getModuleFlag("MaxTLSAlign");
936 return CI->getZExtValue();
937 return 0;
938}
939
941 addModuleFlag(ModFlagBehavior::Error, "override-stack-alignment", Align);
942}
943
944static void addSDKVersionMD(const VersionTuple &V, Module &M, StringRef Name) {
946 Entries.push_back(V.getMajor());
947 if (auto Minor = V.getMinor()) {
948 Entries.push_back(*Minor);
949 if (auto Subminor = V.getSubminor())
950 Entries.push_back(*Subminor);
951 // Ignore the 'build' component as it can't be represented in the object
952 // file.
953 }
954 M.addModuleFlag(Module::ModFlagBehavior::Warning, Name,
955 ConstantDataArray::get(M.getContext(), Entries));
956}
957
959 addSDKVersionMD(V, *this, "SDK Version");
960}
961
964 if (!CM)
965 return {};
966 auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
967 if (!Arr)
968 return {};
969 auto getVersionComponent = [&](unsigned Index) -> std::optional<unsigned> {
970 if (Index >= Arr->getNumElements())
971 return std::nullopt;
972 return (unsigned)Arr->getElementAsInteger(Index);
973 };
974 auto Major = getVersionComponent(0);
975 if (!Major)
976 return {};
978 if (auto Minor = getVersionComponent(1)) {
979 Result = VersionTuple(*Major, *Minor);
980 if (auto Subminor = getVersionComponent(2)) {
981 Result = VersionTuple(*Major, *Minor, *Subminor);
982 }
983 }
984 return Result;
985}
986
988 return getSDKVersionMD(getModuleFlag("SDK Version"));
989}
990
992 const Module &M, SmallVectorImpl<GlobalValue *> &Vec, bool CompilerUsed) {
993 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
994 GlobalVariable *GV = M.getGlobalVariable(Name);
995 if (!GV || !GV->hasInitializer())
996 return GV;
997
999 for (Value *Op : Init->operands()) {
1000 GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts());
1001 Vec.push_back(G);
1002 }
1003 return GV;
1004}
1005
1007 if (auto *SummaryMD = getProfileSummary(/*IsCS*/ false)) {
1008 std::unique_ptr<ProfileSummary> ProfileSummary(
1009 ProfileSummary::getFromMD(SummaryMD));
1010 if (ProfileSummary) {
1013 return;
1014 uint64_t BlockCount = Index.getBlockCount();
1015 uint32_t NumCounts = ProfileSummary->getNumCounts();
1016 if (!NumCounts)
1017 return;
1018 double Ratio = (double)BlockCount / NumCounts;
1020 setProfileSummary(ProfileSummary->getMD(getContext()),
1022 }
1023 }
1024}
1025
1027 if (const auto *MD = getModuleFlag("darwin.target_variant.triple"))
1028 return cast<MDString>(MD)->getString();
1029 return "";
1030}
1031
1033 addModuleFlag(ModFlagBehavior::Warning, "darwin.target_variant.triple",
1035}
1036
1038 return getSDKVersionMD(getModuleFlag("darwin.target_variant.SDK Version"));
1039}
1040
1042 addSDKVersionMD(Version, *this, "darwin.target_variant.SDK Version");
1043}
1044
1046 StringRef TargetABI;
1047 if (auto *TargetABIMD = cast_or_null<MDString>(getModuleFlag("target-abi")))
1048 TargetABI = TargetABIMD->getString();
1049 return TargetABI;
1050}
1051
1053 // Check the new unified flag first.
1054 if (Metadata *MD = getModuleFlag("winx64-eh-unwind")) {
1056 return static_cast<WinX64EHUnwindMode>(CI->getZExtValue());
1057 }
1058 // Fall back to the legacy V2 flag.
1059 if (Metadata *MD = getModuleFlag("winx64-eh-unwindv2")) {
1061 return static_cast<WinX64EHUnwindMode>(CI->getZExtValue());
1062 }
1064}
1065
1067 Metadata *MD = getModuleFlag("cfguard");
1069 return static_cast<ControlFlowGuardMode>(CI->getZExtValue());
1071}
1072
1073bool Module::GlobalAsmProperties::set(StringRef Name, std::string Value) {
1074 if (Name == "target_features")
1075 TargetFeatures = std::move(Value);
1076 else if (Name == "target_cpu")
1077 TargetCPU = std::move(Value);
1078 else
1079 return false;
1080 return true;
1081}
1082
1086 if (!TargetFeatures.empty())
1087 Props.emplace_back("target_features", TargetFeatures);
1088 if (!TargetCPU.empty())
1089 Props.emplace_back("target_cpu", TargetCPU);
1090 return Props;
1091}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
uint64_t uint64_t
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")
#define LLVM_EXPORT_TEMPLATE
Definition Compiler.h:213
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil container globals
dxil translate DXIL Translate Metadata
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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, GsymDataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define G(x, y, z)
Definition MD5.cpp:55
Machine Check Debug Module
Register Reg
static Constant * getOrInsertGlobal(Module &M, StringRef Name, Type *Ty)
This file contains the declarations for metadata subclasses.
#define T
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
StandardInstrumentations SI(Mod->getContext(), Debug, VerifyEach)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
static VersionTuple getSDKVersionMD(Metadata *MD)
Definition Module.cpp:962
static void addSDKVersionMD(const VersionTuple &V, Module &M, StringRef Name)
Definition Module.cpp:944
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:590
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:548
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:878
This is the shared class of boolean and integer constants.
Definition Constants.h:87
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
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:76
Metadata node.
Definition Metadata.h:1081
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
A single uniqued string.
Definition Metadata.h:733
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
Class to hold module path string table and global value map, and encapsulate methods for operating on...
LLVM_ABI DICompileUnit * operator*() const
Definition Module.cpp:467
LLVM_ABI DICompileUnit * operator->() const
Definition Module.cpp:470
void setStackProtectorGuardSymbol(StringRef Symbol)
Definition Module.cpp:898
void setSemanticInterposition(bool)
Set whether semantic interposition is to be respected.
Definition Module.cpp:807
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
Definition Module.cpp:320
@ Warning
Emits a warning if two values disagree.
Definition Module.h:125
llvm::Error materializeAll()
Make sure all GlobalValues in this Module are fully read and clear the Materializer.
Definition Module.cpp:513
void setOverrideStackAlignment(unsigned Align)
Definition Module.cpp:940
void setDirectAccessExternalData(bool Value)
Definition Module.cpp:832
unsigned getMaxTLSAlignment() const
Definition Module.cpp:933
StringRef getTargetABIFromMD()
Returns target-abi from MDString, null if target-abi is absent.
Definition Module.cpp:1045
WinX64EHUnwindMode getWinX64EHUnwindMode() const
Get how unwind information should be generated for x64 Windows.
Definition Module.cpp:1052
void setOwnedMemoryBuffer(std::unique_ptr< MemoryBuffer > MB)
Take ownership of the given memory buffer.
Definition Module.cpp:811
void setMaterializer(GVMaterializer *GVM)
Sets the GVMaterializer to GVM.
Definition Module.cpp:499
llvm::Error materialize(GlobalValue *GV)
Make sure the GlobalValue is fully read.
Definition Module.cpp:506
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition Module.cpp:254
void setCodeModel(CodeModel::Model CL)
Set the code model (tiny, small, kernel, medium or large)
Definition Module.cpp:696
LongDoubleFormat getLongDoubleFormat() const
Returns the long double format from the "long-double-type" module flag, or the triple default when th...
Definition Module.cpp:710
StringRef getStackProtectorGuardSymbol() const
Get/set a symbol to use as the stack protector guard.
Definition Module.cpp:891
FloatABI::ABIType getFloatABI() const
Returns the floating-point ABI recorded by the "float-abi" module flag, or the ABI implied by the tar...
Definition Module.cpp:725
bool getSemanticInterposition() const
Returns whether semantic interposition is to be respected.
Definition Module.cpp:797
void getMDKindNames(SmallVectorImpl< StringRef > &Result) const
Populate client supplied SmallVector with the name for custom metadata IDs registered in this LLVMCon...
Definition Module.cpp:194
Module(StringRef ModuleID, LLVMContext &C)
The Module constructor.
Definition Module.cpp:73
std::optional< unsigned > getStackProtectorGuardValueWidth() const
Get/set the width in memory of the stack protector guard value.
Definition Module.cpp:914
void removeDebugIntrinsicDeclarations()
Used when printing this module in the new debug info format; removes all declarations of debug intrin...
Definition Module.cpp:127
void setRtLibUseGOT()
Set that PLT should be avoid for RTLib calls.
Definition Module.cpp:820
llvm::Error materializeMetadata()
Definition Module.cpp:520
NamedMDNode * getOrInsertModuleFlagsMetadata()
Returns the NamedMDNode in the module that represents module-level flags.
Definition Module.cpp:391
ControlFlowGuardMode getControlFlowGuardMode() const
Gets the Control Flow Guard mode.
Definition Module.cpp:1066
void eraseNamedMetadata(NamedMDNode *NMD)
Remove the given NamedMDNode from this module and delete it.
Definition Module.cpp:341
unsigned getNumNamedValues() const
Return the number of global values in the module.
Definition Module.cpp:181
bool hasStackProtectorGuardRecord() const
Definition Module.cpp:856
unsigned getMDKindID(StringRef Name) const
Return a unique non-zero ID for the specified metadata kind.
Definition Module.cpp:187
void setFramePointer(FramePointerKind Kind)
Definition Module.cpp:852
std::optional< uint64_t > getLargeDataThreshold() const
Returns the large data threshold.
Definition Module.cpp:768
void setDebuggerTuning(DebuggerKind Tuning)
Set the debugger tuning.
Definition Module.cpp:760
StringRef getStackProtectorGuard() const
Get/set what kind of stack protector guard to use.
Definition Module.cpp:867
bool getRtLibUseGOT() const
Returns true if PLT should be avoided for RTLib calls.
Definition Module.cpp:815
void setModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val)
Like addModuleFlag but replaces the old module flag if it already exists.
Definition Module.cpp:431
UWTableKind getUwtable() const
Get/set whether synthesized functions should get the uwtable attribute.
Definition Module.cpp:836
void dropAllReferences()
This function causes all the subinstructions to "let go" of all references that they are maintaining.
Definition Module.cpp:602
void setStackProtectorGuard(StringRef Kind)
Definition Module.cpp:874
void setProfileSummary(Metadata *M, ProfileSummary::Kind Kind)
Attach profile summary metadata to this module.
Definition Module.cpp:785
void setUwtable(UWTableKind Kind)
Definition Module.cpp:842
unsigned getCodeViewFlag() const
Returns the CodeView Version by checking module flags.
Definition Module.cpp:636
void setPartialSampleProfileRatio(const ModuleSummaryIndex &Index)
Set the partial sample profile ratio in the profile summary module flag, if applicable.
Definition Module.cpp:1006
ExceptionHandling getExceptionModel() const
Returns the exception model recorded by the "exception-model" module flag, or the target's default ex...
Definition Module.cpp:744
DebuggerKind getDebuggerTuning() const
Returns the debugger tuning recorded by the "debugger-tuning" module flag, or the target's default de...
Definition Module.cpp:750
Module & operator=(Module &&Other)
Move assignment.
Definition Module.cpp:79
ThreadModel getThreadModel() const
Returns the thread model recorded by the "thread-model" module flag, or the model implied by the targ...
Definition Module.cpp:733
std::string getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id, const FunctionType *Proto)
Return a unique name for an intrinsic whose mangling is based on an unnamed type.
Definition Module.cpp:545
~Module()
The module destructor. This will dropAllReferences.
Definition Module.cpp:118
FramePointerKind getFramePointer() const
Get/set whether synthesized functions should get the "frame-pointer" attribute.
Definition Module.cpp:846
unsigned getOverrideStackAlignment() const
Get/set the stack alignment overridden from the default.
Definition Module.cpp:926
void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val)
Add a module-level flag to the module-level flags metadata.
Definition Module.cpp:400
void setStackProtectorGuardReg(StringRef Reg)
Definition Module.cpp:886
PICLevel::Level getPICLevel() const
Returns the PIC level (small or large model)
Definition Module.cpp:656
unsigned getWCharSize() const
Returns the size of the wchar_t type from the "wchar_size" module flag, or the triple default when th...
Definition Module.cpp:704
std::unique_ptr< RandomNumberGenerator > createRNG(const StringRef Name) const
Get a RandomNumberGenerator salted for use with this module.
Definition Module.cpp:155
std::vector< StructType * > getIdentifiedStructTypes() const
Definition Module.cpp:531
void setDarwinTargetVariantTriple(StringRef T)
Set the target variant triple which is a string describing a variant of the target host platform.
Definition Module.cpp:1032
void setPICLevel(PICLevel::Level PL)
Set the PIC level (small or large model)
Definition Module.cpp:666
unsigned getNumberRegisterParameters() const
Returns the Number of Register ParametersDwarf Version by checking module flags.
Definition Module.cpp:616
GlobalIFunc * getNamedIFunc(StringRef Name) const
Return the global ifunc in the module with the specified name, of arbitrary type.
Definition Module.cpp:313
StringRef getStackProtectorGuardReg() const
Get/set which register to use as the stack protector guard register.
Definition Module.cpp:879
unsigned getDwarfVersion() const
Returns the Dwarf Version by checking module flags.
Definition Module.cpp:624
void setDataLayout(StringRef Desc)
Set the data layout.
Definition Module.cpp:463
GlobalVariable * getGlobalVariable(StringRef Name) const
Look up the specified global variable in the module symbol table.
Definition Module.h:519
void setLargeDataThreshold(uint64_t Threshold)
Set the large data threshold.
Definition Module.cpp:778
bool isDwarf64() const
Returns the DWARF format by checking module flags.
Definition Module.cpp:631
static bool isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB)
Checks if Metadata represents a valid ModFlagBehavior, and stores the converted result in MFB.
Definition Module.cpp:348
void setStackProtectorGuardOffset(int Offset)
Definition Module.cpp:910
iterator_range< global_object_iterator > global_objects()
Definition Module.cpp:480
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
Definition Module.cpp:177
unsigned getInstructionCount() const
Returns the number of non-debug IR instructions in the module.
Definition Module.cpp:643
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition Module.cpp:327
void getOperandBundleTags(SmallVectorImpl< StringRef > &Result) const
Populate client supplied SmallVector with the bundle tags registered in this LLVMContext.
Definition Module.cpp:198
void setStackProtectorGuardRecord(bool Flag)
Definition Module.cpp:862
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition Module.cpp:650
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition Module.cpp:229
std::optional< CodeModel::Model > getCodeModel() const
Returns the code model (tiny, small, kernel, medium or large model)
Definition Module.cpp:686
VersionTuple getDarwinTargetVariantSDKVersion() const
Get the target variant version build SDK version metadata.
Definition Module.cpp:1037
void setThreadModel(ThreadModel Model)
Set the thread model.
Definition Module.cpp:739
void setStackProtectorGuardValueWidth(unsigned Width)
Definition Module.cpp:921
void setLongDoubleFormat(LongDoubleFormat Format)
Set the long double format.
Definition Module.cpp:720
void setPIELevel(PIELevel::Level PL)
Set the PIE level (small or large model)
Definition Module.cpp:682
GlobalVariable * getOrInsertGlobal(StringRef Name, Type *Ty, function_ref< GlobalVariable *()> CreateGlobalCallback)
Look up the specified global in the module symbol table.
Definition Module.cpp:281
VersionTuple getSDKVersion() const
Get the build SDK version metadata.
Definition Module.cpp:987
GlobalAlias * getNamedAlias(StringRef Name) const
Return the global alias in the module with the specified name, of arbitrary type.
Definition Module.cpp:309
void setDarwinTargetVariantSDKVersion(VersionTuple Version)
Set the target variant version build SDK version metadata.
Definition Module.cpp:1041
PIELevel::Level getPIELevel() const
Returns the PIE level (small or large model)
Definition Module.cpp:672
StringRef getDarwinTargetVariantTriple() const
Get the target variant triple which is a string describing a variant of the target host platform.
Definition Module.cpp:1026
void setSDKVersion(const VersionTuple &V)
Attach a build SDK version metadata to this module.
Definition Module.cpp:958
iterator_range< global_value_iterator > global_values()
Definition Module.cpp:488
int getStackProtectorGuardOffset() const
Get/set what offset from the stack protector to use.
Definition Module.cpp:903
bool getDirectAccessExternalData() const
Get/set whether referencing global variables can use direct access relocations on ELF targets.
Definition Module.cpp:824
Metadata * getProfileSummary(bool IsCS) const
Returns profile summary metadata.
Definition Module.cpp:792
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition Module.cpp:377
A tuple of MDNodes.
Definition Metadata.h:1797
LLVM_ABI void setOperand(unsigned I, MDNode *New)
LLVM_ABI StringRef getName() const
LLVM_ABI MDNode * getOperand(unsigned i) const
LLVM_ABI unsigned getNumOperands() const
iterator_range< op_iterator > operands()
Definition Metadata.h:1893
void setPartialProfileRatio(double R)
LLVM_ABI Metadata * getMD(LLVMContext &Context, bool AddPartialField=true, bool AddPartialProfileRatioField=true)
Return summary information as metadata.
uint32_t getNumCounts() const
bool isPartialProfile() const
static LLVM_ABI ProfileSummary * getFromMD(Metadata *MD)
Construct profile summary from metdata.
A random number generator.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
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
LLVM_ABI void run(const Module &M, bool onlyNamed)
iterator begin()
Definition TypeFinder.h:51
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
void dropAllReferences()
Drop all references to operands.
Definition User.h:324
This class provides a symbol table of name/value pairs.
Represents a version number in the form major[.minor[.subminor[.build]]].
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.
std::optional< ABIType > parseABIType(StringRef S)
Parse the string spelling used by the "float-abi" IR module flag into an ABIType.
Definition CodeGen.h:167
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition Metadata.h:720
std::enable_if_t< detail::IsValidPointer< X, Y >::value, bool > hasa(Y &&MD)
Check whether Metadata has a Value.
Definition Metadata.h:662
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
This is an optimization pass for GlobalISel generic memory operations.
std::optional< LongDoubleFormat > parseLongDoubleFormat(StringRef Name)
Parses an IR floating-point type name into a LongDoubleFormat, returning std::nullopt if it does not ...
Definition CodeGen.h:144
@ Offset
Definition DWP.cpp:577
StringRef getLongDoubleFormatName(LongDoubleFormat Format)
Returns the IR floating-point type name for a LongDoubleFormat.
Definition CodeGen.h:126
StringRef getDebuggerTuningName(DebuggerKind Tuning)
Returns the string spelling used by the "debugger-tuning" IR module flag for a DebuggerKind.
Definition CodeGen.h:255
auto cast_or_null(const Y &Val)
Definition Casting.h:714
Op::Description Desc
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
Definition STLExtras.h:1167
std::optional< ExceptionHandling > parseExceptionModel(StringRef Name)
Parses the string spelling used by the "exception-model" IR module flag into an ExceptionHandling val...
Definition CodeGen.h:98
ControlFlowGuardMode
Definition CodeGen.h:385
WinX64EHUnwindMode
Definition CodeGen.h:375
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
UWTableKind
Definition CodeGen.h:362
@ None
No unwind table requested.
Definition CodeGen.h:363
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Other
Any other memory.
Definition ModRef.h:68
ThreadModel
The threading model to assume for lowering, e.g. of atomics.
Definition CodeGen.h:191
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
std::optional< ThreadModel > parseThreadModel(StringRef S)
Parse the string spelling used by the "thread-model" IR module flag into a ThreadModel.
Definition CodeGen.h:198
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
std::optional< DebuggerKind > parseDebuggerTuning(StringRef S)
Parse the string spelling used by the "debugger-tuning" IR module flag into a DebuggerKind.
Definition CodeGen.h:241
StringRef getThreadModelName(ThreadModel TM)
Returns the string spelling used by the "thread-model" IR module flag for a ThreadModel.
Definition CodeGen.h:208
@ Default
No specific tuning requested.
Definition CodeGen.h:232
LLVM_ABI 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:991
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
LLVM_ABI bool set(StringRef Name, std::string Value)
Set a property using a string name.
Definition Module.cpp:1073
LLVM_ABI SmallVector< std::pair< StringRef, StringRef > > getAsStrings() const
Get a list of set properties as pairs of key and value.
Definition Module.cpp:1084