xref: /llvm-project-15.0.7/llvm/lib/IR/Module.cpp (revision 86aae782)
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/Optional.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/IR/Attributes.h"
23 #include "llvm/IR/Comdat.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/GVMaterializer.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalIFunc.h"
32 #include "llvm/IR/GlobalValue.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Metadata.h"
36 #include "llvm/IR/SymbolTableListTraits.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/TypeFinder.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/IR/ValueSymbolTable.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/CodeGen.h"
44 #include "llvm/Support/Error.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/RandomNumberGenerator.h"
48 #include "llvm/Support/VersionTuple.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <cstdint>
52 #include <memory>
53 #include <utility>
54 #include <vector>
55 
56 using namespace llvm;
57 
58 //===----------------------------------------------------------------------===//
59 // Methods to implement the globals and functions lists.
60 //
61 
62 // Explicit instantiations of SymbolTableListTraits since some of the methods
63 // are not in the public header file.
64 template class llvm::SymbolTableListTraits<Function>;
65 template class llvm::SymbolTableListTraits<GlobalVariable>;
66 template class llvm::SymbolTableListTraits<GlobalAlias>;
67 template class llvm::SymbolTableListTraits<GlobalIFunc>;
68 
69 //===----------------------------------------------------------------------===//
70 // Primitive Module methods.
71 //
72 
73 Module::Module(StringRef MID, LLVMContext &C)
74     : Context(C), ValSymTab(std::make_unique<ValueSymbolTable>()),
75       Materializer(), ModuleID(std::string(MID)),
76       SourceFileName(std::string(MID)), DL("") {
77   Context.addModule(this);
78 }
79 
80 Module::~Module() {
81   Context.removeModule(this);
82   dropAllReferences();
83   GlobalList.clear();
84   FunctionList.clear();
85   AliasList.clear();
86   IFuncList.clear();
87 }
88 
89 std::unique_ptr<RandomNumberGenerator> Module::createRNG(const Pass* P) const {
90   SmallString<32> Salt(P->getPassName());
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>(new RandomNumberGenerator(Salt));
105 }
106 
107 /// getNamedValue - Return the first global value in the module with
108 /// the specified name, of arbitrary type.  This method returns null
109 /// if a global with the specified name is not found.
110 GlobalValue *Module::getNamedValue(StringRef Name) const {
111   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
112 }
113 
114 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
115 /// This ID is uniqued across modules in the current LLVMContext.
116 unsigned Module::getMDKindID(StringRef Name) const {
117   return Context.getMDKindID(Name);
118 }
119 
120 /// getMDKindNames - Populate client supplied SmallVector with the name for
121 /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
122 /// so it is filled in as an empty string.
123 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
124   return Context.getMDKindNames(Result);
125 }
126 
127 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
128   return Context.getOperandBundleTags(Result);
129 }
130 
131 //===----------------------------------------------------------------------===//
132 // Methods for easy access to the functions in the module.
133 //
134 
135 // getOrInsertFunction - Look up the specified function in the module symbol
136 // table.  If it does not exist, add a prototype for the function and return
137 // it.  This is nice because it allows most passes to get away with not handling
138 // the symbol table directly for this common task.
139 //
140 FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
141                                            AttributeList AttributeList) {
142   // See if we have a definition for the specified function already.
143   GlobalValue *F = getNamedValue(Name);
144   if (!F) {
145     // Nope, add it
146     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage,
147                                      DL.getProgramAddressSpace(), Name);
148     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
149       New->setAttributes(AttributeList);
150     FunctionList.push_back(New);
151     return {Ty, New}; // Return the new prototype.
152   }
153 
154   // If the function exists but has the wrong type, return a bitcast to the
155   // right type.
156   auto *PTy = PointerType::get(Ty, F->getAddressSpace());
157   if (F->getType() != PTy)
158     return {Ty, ConstantExpr::getBitCast(F, PTy)};
159 
160   // Otherwise, we just found the existing function or a prototype.
161   return {Ty, F};
162 }
163 
164 FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) {
165   return getOrInsertFunction(Name, Ty, AttributeList());
166 }
167 
168 // getFunction - Look up the specified function in the module symbol table.
169 // If it does not exist, return null.
170 //
171 Function *Module::getFunction(StringRef Name) const {
172   return dyn_cast_or_null<Function>(getNamedValue(Name));
173 }
174 
175 //===----------------------------------------------------------------------===//
176 // Methods for easy access to the global variables in the module.
177 //
178 
179 /// getGlobalVariable - Look up the specified global variable in the module
180 /// symbol table.  If it does not exist, return null.  The type argument
181 /// should be the underlying type of the global, i.e., it should not have
182 /// the top-level PointerType, which represents the address of the global.
183 /// If AllowLocal is set to true, this function will return types that
184 /// have an local. By default, these types are not returned.
185 ///
186 GlobalVariable *Module::getGlobalVariable(StringRef Name,
187                                           bool AllowLocal) const {
188   if (GlobalVariable *Result =
189       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
190     if (AllowLocal || !Result->hasLocalLinkage())
191       return Result;
192   return nullptr;
193 }
194 
195 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
196 ///   1. If it does not exist, add a declaration of the global and return it.
197 ///   2. Else, the global exists but has the wrong type: return the function
198 ///      with a constantexpr cast to the right type.
199 ///   3. Finally, if the existing global is the correct declaration, return the
200 ///      existing global.
201 Constant *Module::getOrInsertGlobal(
202     StringRef Name, Type *Ty,
203     function_ref<GlobalVariable *()> CreateGlobalCallback) {
204   // See if we have a definition for the specified global already.
205   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
206   if (!GV)
207     GV = CreateGlobalCallback();
208   assert(GV && "The CreateGlobalCallback is expected to create a global");
209 
210   // If the variable exists but has the wrong type, return a bitcast to the
211   // right type.
212   Type *GVTy = GV->getType();
213   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
214   if (GVTy != PTy)
215     return ConstantExpr::getBitCast(GV, PTy);
216 
217   // Otherwise, we just found the existing function or a prototype.
218   return GV;
219 }
220 
221 // Overload to construct a global variable using its constructor's defaults.
222 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
223   return getOrInsertGlobal(Name, Ty, [&] {
224     return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
225                               nullptr, Name);
226   });
227 }
228 
229 //===----------------------------------------------------------------------===//
230 // Methods for easy access to the global variables in the module.
231 //
232 
233 // getNamedAlias - Look up the specified global in the module symbol table.
234 // If it does not exist, return null.
235 //
236 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
237   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
238 }
239 
240 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
241   return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
242 }
243 
244 /// getNamedMetadata - Return the first NamedMDNode in the module with the
245 /// specified name. This method returns null if a NamedMDNode with the
246 /// specified name is not found.
247 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
248   SmallString<256> NameData;
249   StringRef NameRef = Name.toStringRef(NameData);
250   return NamedMDSymTab.lookup(NameRef);
251 }
252 
253 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
254 /// with the specified name. This method returns a new NamedMDNode if a
255 /// NamedMDNode with the specified name is not found.
256 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
257   NamedMDNode *&NMD = NamedMDSymTab[Name];
258   if (!NMD) {
259     NMD = new NamedMDNode(Name);
260     NMD->setParent(this);
261     NamedMDList.push_back(NMD);
262   }
263   return NMD;
264 }
265 
266 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
267 /// delete it.
268 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
269   NamedMDSymTab.erase(NMD->getName());
270   NamedMDList.erase(NMD->getIterator());
271 }
272 
273 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
274   if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
275     uint64_t Val = Behavior->getLimitedValue();
276     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
277       MFB = static_cast<ModFlagBehavior>(Val);
278       return true;
279     }
280   }
281   return false;
282 }
283 
284 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
285 void Module::
286 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
287   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
288   if (!ModFlags) return;
289 
290   for (const MDNode *Flag : ModFlags->operands()) {
291     ModFlagBehavior MFB;
292     if (Flag->getNumOperands() >= 3 &&
293         isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
294         dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
295       // Check the operands of the MDNode before accessing the operands.
296       // The verifier will actually catch these failures.
297       MDString *Key = cast<MDString>(Flag->getOperand(1));
298       Metadata *Val = Flag->getOperand(2);
299       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
300     }
301   }
302 }
303 
304 /// Return the corresponding value if Key appears in module flags, otherwise
305 /// return null.
306 Metadata *Module::getModuleFlag(StringRef Key) const {
307   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
308   getModuleFlagsMetadata(ModuleFlags);
309   for (const ModuleFlagEntry &MFE : ModuleFlags) {
310     if (Key == MFE.Key->getString())
311       return MFE.Val;
312   }
313   return nullptr;
314 }
315 
316 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
317 /// represents module-level flags. This method returns null if there are no
318 /// module-level flags.
319 NamedMDNode *Module::getModuleFlagsMetadata() const {
320   return getNamedMetadata("llvm.module.flags");
321 }
322 
323 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
324 /// represents module-level flags. If module-level flags aren't found, it
325 /// creates the named metadata that contains them.
326 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
327   return getOrInsertNamedMetadata("llvm.module.flags");
328 }
329 
330 /// addModuleFlag - Add a module-level flag to the module-level flags
331 /// metadata. It will create the module-level flags named metadata if it doesn't
332 /// already exist.
333 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
334                            Metadata *Val) {
335   Type *Int32Ty = Type::getInt32Ty(Context);
336   Metadata *Ops[3] = {
337       ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
338       MDString::get(Context, Key), Val};
339   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
340 }
341 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
342                            Constant *Val) {
343   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
344 }
345 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
346                            uint32_t Val) {
347   Type *Int32Ty = Type::getInt32Ty(Context);
348   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
349 }
350 void Module::addModuleFlag(MDNode *Node) {
351   assert(Node->getNumOperands() == 3 &&
352          "Invalid number of operands for module flag!");
353   assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
354          isa<MDString>(Node->getOperand(1)) &&
355          "Invalid operand types for module flag!");
356   getOrInsertModuleFlagsMetadata()->addOperand(Node);
357 }
358 
359 void Module::setDataLayout(StringRef Desc) {
360   DL.reset(Desc);
361 }
362 
363 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
364 
365 const DataLayout &Module::getDataLayout() const { return DL; }
366 
367 DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
368   return cast<DICompileUnit>(CUs->getOperand(Idx));
369 }
370 DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
371   return cast<DICompileUnit>(CUs->getOperand(Idx));
372 }
373 
374 void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
375   while (CUs && (Idx < CUs->getNumOperands()) &&
376          ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
377     ++Idx;
378 }
379 
380 iterator_range<Module::global_object_iterator> Module::global_objects() {
381   return concat<GlobalObject>(functions(), globals());
382 }
383 iterator_range<Module::const_global_object_iterator>
384 Module::global_objects() const {
385   return concat<const GlobalObject>(functions(), globals());
386 }
387 
388 iterator_range<Module::global_value_iterator> Module::global_values() {
389   return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs());
390 }
391 iterator_range<Module::const_global_value_iterator>
392 Module::global_values() const {
393   return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs());
394 }
395 
396 //===----------------------------------------------------------------------===//
397 // Methods to control the materialization of GlobalValues in the Module.
398 //
399 void Module::setMaterializer(GVMaterializer *GVM) {
400   assert(!Materializer &&
401          "Module already has a GVMaterializer.  Call materializeAll"
402          " to clear it out before setting another one.");
403   Materializer.reset(GVM);
404 }
405 
406 Error Module::materialize(GlobalValue *GV) {
407   if (!Materializer)
408     return Error::success();
409 
410   return Materializer->materialize(GV);
411 }
412 
413 Error Module::materializeAll() {
414   if (!Materializer)
415     return Error::success();
416   std::unique_ptr<GVMaterializer> M = std::move(Materializer);
417   return M->materializeModule();
418 }
419 
420 Error Module::materializeMetadata() {
421   if (!Materializer)
422     return Error::success();
423   return Materializer->materializeMetadata();
424 }
425 
426 //===----------------------------------------------------------------------===//
427 // Other module related stuff.
428 //
429 
430 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
431   // If we have a materializer, it is possible that some unread function
432   // uses a type that is currently not visible to a TypeFinder, so ask
433   // the materializer which types it created.
434   if (Materializer)
435     return Materializer->getIdentifiedStructTypes();
436 
437   std::vector<StructType *> Ret;
438   TypeFinder SrcStructTypes;
439   SrcStructTypes.run(*this, true);
440   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
441   return Ret;
442 }
443 
444 // dropAllReferences() - This function causes all the subelements to "let go"
445 // of all references that they are maintaining.  This allows one to 'delete' a
446 // whole module at a time, even though there may be circular references... first
447 // all references are dropped, and all use counts go to zero.  Then everything
448 // is deleted for real.  Note that no operations are valid on an object that
449 // has "dropped all references", except operator delete.
450 //
451 void Module::dropAllReferences() {
452   for (Function &F : *this)
453     F.dropAllReferences();
454 
455   for (GlobalVariable &GV : globals())
456     GV.dropAllReferences();
457 
458   for (GlobalAlias &GA : aliases())
459     GA.dropAllReferences();
460 
461   for (GlobalIFunc &GIF : ifuncs())
462     GIF.dropAllReferences();
463 }
464 
465 unsigned Module::getNumberRegisterParameters() const {
466   auto *Val =
467       cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
468   if (!Val)
469     return 0;
470   return cast<ConstantInt>(Val->getValue())->getZExtValue();
471 }
472 
473 unsigned Module::getDwarfVersion() const {
474   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
475   if (!Val)
476     return 0;
477   return cast<ConstantInt>(Val->getValue())->getZExtValue();
478 }
479 
480 unsigned Module::getCodeViewFlag() const {
481   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
482   if (!Val)
483     return 0;
484   return cast<ConstantInt>(Val->getValue())->getZExtValue();
485 }
486 
487 unsigned Module::getInstructionCount() {
488   unsigned NumInstrs = 0;
489   for (Function &F : FunctionList)
490     NumInstrs += F.getInstructionCount();
491   return NumInstrs;
492 }
493 
494 Comdat *Module::getOrInsertComdat(StringRef Name) {
495   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
496   Entry.second.Name = &Entry;
497   return &Entry.second;
498 }
499 
500 PICLevel::Level Module::getPICLevel() const {
501   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
502 
503   if (!Val)
504     return PICLevel::NotPIC;
505 
506   return static_cast<PICLevel::Level>(
507       cast<ConstantInt>(Val->getValue())->getZExtValue());
508 }
509 
510 void Module::setPICLevel(PICLevel::Level PL) {
511   addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
512 }
513 
514 PIELevel::Level Module::getPIELevel() const {
515   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
516 
517   if (!Val)
518     return PIELevel::Default;
519 
520   return static_cast<PIELevel::Level>(
521       cast<ConstantInt>(Val->getValue())->getZExtValue());
522 }
523 
524 void Module::setPIELevel(PIELevel::Level PL) {
525   addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
526 }
527 
528 Optional<CodeModel::Model> Module::getCodeModel() const {
529   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
530 
531   if (!Val)
532     return None;
533 
534   return static_cast<CodeModel::Model>(
535       cast<ConstantInt>(Val->getValue())->getZExtValue());
536 }
537 
538 void Module::setCodeModel(CodeModel::Model CL) {
539   // Linking object files with different code models is undefined behavior
540   // because the compiler would have to generate additional code (to span
541   // longer jumps) if a larger code model is used with a smaller one.
542   // Therefore we will treat attempts to mix code models as an error.
543   addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
544 }
545 
546 void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) {
547   if (Kind == ProfileSummary::PSK_CSInstr)
548     addModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M);
549   else
550     addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
551 }
552 
553 Metadata *Module::getProfileSummary(bool IsCS) {
554   return (IsCS ? getModuleFlag("CSProfileSummary")
555                : getModuleFlag("ProfileSummary"));
556 }
557 
558 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
559   OwnedMemoryBuffer = std::move(MB);
560 }
561 
562 bool Module::getRtLibUseGOT() const {
563   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
564   return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
565 }
566 
567 void Module::setRtLibUseGOT() {
568   addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
569 }
570 
571 void Module::setSDKVersion(const VersionTuple &V) {
572   SmallVector<unsigned, 3> Entries;
573   Entries.push_back(V.getMajor());
574   if (auto Minor = V.getMinor()) {
575     Entries.push_back(*Minor);
576     if (auto Subminor = V.getSubminor())
577       Entries.push_back(*Subminor);
578     // Ignore the 'build' component as it can't be represented in the object
579     // file.
580   }
581   addModuleFlag(ModFlagBehavior::Warning, "SDK Version",
582                 ConstantDataArray::get(Context, Entries));
583 }
584 
585 VersionTuple Module::getSDKVersion() const {
586   auto *CM = dyn_cast_or_null<ConstantAsMetadata>(getModuleFlag("SDK Version"));
587   if (!CM)
588     return {};
589   auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
590   if (!Arr)
591     return {};
592   auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> {
593     if (Index >= Arr->getNumElements())
594       return None;
595     return (unsigned)Arr->getElementAsInteger(Index);
596   };
597   auto Major = getVersionComponent(0);
598   if (!Major)
599     return {};
600   VersionTuple Result = VersionTuple(*Major);
601   if (auto Minor = getVersionComponent(1)) {
602     Result = VersionTuple(*Major, *Minor);
603     if (auto Subminor = getVersionComponent(2)) {
604       Result = VersionTuple(*Major, *Minor, *Subminor);
605     }
606   }
607   return Result;
608 }
609 
610 GlobalVariable *llvm::collectUsedGlobalVariables(
611     const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
612   const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
613   GlobalVariable *GV = M.getGlobalVariable(Name);
614   if (!GV || !GV->hasInitializer())
615     return GV;
616 
617   const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
618   for (Value *Op : Init->operands()) {
619     GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts());
620     Set.insert(G);
621   }
622   return GV;
623 }
624