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