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