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