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