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/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/IR/Attributes.h"
22 #include "llvm/IR/Comdat.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DebugInfoMetadata.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GVMaterializer.h"
29 #include "llvm/IR/GlobalAlias.h"
30 #include "llvm/IR/GlobalIFunc.h"
31 #include "llvm/IR/GlobalValue.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Metadata.h"
35 #include "llvm/IR/ModuleSummaryIndex.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/Support/Casting.h"
42 #include "llvm/Support/CodeGen.h"
43 #include "llvm/Support/Error.h"
44 #include "llvm/Support/MemoryBuffer.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/RandomNumberGenerator.h"
47 #include "llvm/Support/VersionTuple.h"
48 #include <algorithm>
49 #include <cassert>
50 #include <cstdint>
51 #include <memory>
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       Materializer(), ModuleID(std::string(MID)),
75       SourceFileName(std::string(MID)), DL("") {
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);
153     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
154       New->setAttributes(AttributeList);
155     FunctionList.push_back(New);
156     return {Ty, New}; // Return the new prototype.
157   }
158 
159   // If the function exists but has the wrong type, return a bitcast to the
160   // right type.
161   auto *PTy = PointerType::get(Ty, F->getAddressSpace());
162   if (F->getType() != PTy)
163     return {Ty, ConstantExpr::getBitCast(F, PTy)};
164 
165   // Otherwise, we just found the existing function or a prototype.
166   return {Ty, F};
167 }
168 
169 FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) {
170   return getOrInsertFunction(Name, Ty, AttributeList());
171 }
172 
173 // getFunction - Look up the specified function in the module symbol table.
174 // If it does not exist, return null.
175 //
176 Function *Module::getFunction(StringRef Name) const {
177   return dyn_cast_or_null<Function>(getNamedValue(Name));
178 }
179 
180 //===----------------------------------------------------------------------===//
181 // Methods for easy access to the global variables in the module.
182 //
183 
184 /// getGlobalVariable - Look up the specified global variable in the module
185 /// symbol table.  If it does not exist, return null.  The type argument
186 /// should be the underlying type of the global, i.e., it should not have
187 /// the top-level PointerType, which represents the address of the global.
188 /// If AllowLocal is set to true, this function will return types that
189 /// have an local. By default, these types are not returned.
190 ///
191 GlobalVariable *Module::getGlobalVariable(StringRef Name,
192                                           bool AllowLocal) const {
193   if (GlobalVariable *Result =
194       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
195     if (AllowLocal || !Result->hasLocalLinkage())
196       return Result;
197   return nullptr;
198 }
199 
200 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
201 ///   1. If it does not exist, add a declaration of the global and return it.
202 ///   2. Else, the global exists but has the wrong type: return the function
203 ///      with a constantexpr cast to the right type.
204 ///   3. Finally, if the existing global is the correct declaration, return the
205 ///      existing global.
206 Constant *Module::getOrInsertGlobal(
207     StringRef Name, Type *Ty,
208     function_ref<GlobalVariable *()> CreateGlobalCallback) {
209   // See if we have a definition for the specified global already.
210   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
211   if (!GV)
212     GV = CreateGlobalCallback();
213   assert(GV && "The CreateGlobalCallback is expected to create a global");
214 
215   // If the variable exists but has the wrong type, return a bitcast to the
216   // right type.
217   Type *GVTy = GV->getType();
218   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
219   if (GVTy != PTy)
220     return ConstantExpr::getBitCast(GV, PTy);
221 
222   // Otherwise, we just found the existing function or a prototype.
223   return GV;
224 }
225 
226 // Overload to construct a global variable using its constructor's defaults.
227 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
228   return getOrInsertGlobal(Name, Ty, [&] {
229     return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
230                               nullptr, Name);
231   });
232 }
233 
234 //===----------------------------------------------------------------------===//
235 // Methods for easy access to the global variables in the module.
236 //
237 
238 // getNamedAlias - Look up the specified global in the module symbol table.
239 // If it does not exist, return null.
240 //
241 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
242   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
243 }
244 
245 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
246   return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
247 }
248 
249 /// getNamedMetadata - Return the first NamedMDNode in the module with the
250 /// specified name. This method returns null if a NamedMDNode with the
251 /// specified name is not found.
252 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
253   SmallString<256> NameData;
254   StringRef NameRef = Name.toStringRef(NameData);
255   return NamedMDSymTab.lookup(NameRef);
256 }
257 
258 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
259 /// with the specified name. This method returns a new NamedMDNode if a
260 /// NamedMDNode with the specified name is not found.
261 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
262   NamedMDNode *&NMD = 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   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 bool Module::isValidModuleFlag(const MDNode &ModFlag, ModFlagBehavior &MFB,
290                                MDString *&Key, Metadata *&Val) {
291   if (ModFlag.getNumOperands() < 3)
292     return false;
293   if (!isValidModFlagBehavior(ModFlag.getOperand(0), MFB))
294     return false;
295   MDString *K = dyn_cast_or_null<MDString>(ModFlag.getOperand(1));
296   if (!K)
297     return false;
298   Key = K;
299   Val = ModFlag.getOperand(2);
300   return true;
301 }
302 
303 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
304 void Module::
305 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
306   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
307   if (!ModFlags) return;
308 
309   for (const MDNode *Flag : ModFlags->operands()) {
310     ModFlagBehavior MFB;
311     MDString *Key = nullptr;
312     Metadata *Val = nullptr;
313     if (isValidModuleFlag(*Flag, MFB, Key, Val)) {
314       // Check the operands of the MDNode before accessing the operands.
315       // The verifier will actually catch these failures.
316       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
317     }
318   }
319 }
320 
321 /// Return the corresponding value if Key appears in module flags, otherwise
322 /// return null.
323 Metadata *Module::getModuleFlag(StringRef Key) const {
324   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
325   getModuleFlagsMetadata(ModuleFlags);
326   for (const ModuleFlagEntry &MFE : ModuleFlags) {
327     if (Key == MFE.Key->getString())
328       return MFE.Val;
329   }
330   return nullptr;
331 }
332 
333 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
334 /// represents module-level flags. This method returns null if there are no
335 /// module-level flags.
336 NamedMDNode *Module::getModuleFlagsMetadata() const {
337   return getNamedMetadata("llvm.module.flags");
338 }
339 
340 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
341 /// represents module-level flags. If module-level flags aren't found, it
342 /// creates the named metadata that contains them.
343 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
344   return getOrInsertNamedMetadata("llvm.module.flags");
345 }
346 
347 /// addModuleFlag - Add a module-level flag to the module-level flags
348 /// metadata. It will create the module-level flags named metadata if it doesn't
349 /// already exist.
350 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
351                            Metadata *Val) {
352   Type *Int32Ty = Type::getInt32Ty(Context);
353   Metadata *Ops[3] = {
354       ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
355       MDString::get(Context, Key), Val};
356   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
357 }
358 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
359                            Constant *Val) {
360   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
361 }
362 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
363                            uint32_t Val) {
364   Type *Int32Ty = Type::getInt32Ty(Context);
365   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
366 }
367 void Module::addModuleFlag(MDNode *Node) {
368   assert(Node->getNumOperands() == 3 &&
369          "Invalid number of operands for module flag!");
370   assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
371          isa<MDString>(Node->getOperand(1)) &&
372          "Invalid operand types for module flag!");
373   getOrInsertModuleFlagsMetadata()->addOperand(Node);
374 }
375 
376 void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
377                            Metadata *Val) {
378   NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata();
379   // Replace the flag if it already exists.
380   for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
381     MDNode *Flag = ModFlags->getOperand(I);
382     ModFlagBehavior MFB;
383     MDString *K = nullptr;
384     Metadata *V = nullptr;
385     if (isValidModuleFlag(*Flag, MFB, K, V) && K->getString() == Key) {
386       Flag->replaceOperandWith(2, Val);
387       return;
388     }
389   }
390   addModuleFlag(Behavior, Key, Val);
391 }
392 
393 void Module::setDataLayout(StringRef Desc) {
394   DL.reset(Desc);
395 }
396 
397 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
398 
399 const DataLayout &Module::getDataLayout() const { return DL; }
400 
401 DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
402   return cast<DICompileUnit>(CUs->getOperand(Idx));
403 }
404 DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
405   return cast<DICompileUnit>(CUs->getOperand(Idx));
406 }
407 
408 void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
409   while (CUs && (Idx < CUs->getNumOperands()) &&
410          ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
411     ++Idx;
412 }
413 
414 iterator_range<Module::global_object_iterator> Module::global_objects() {
415   return concat<GlobalObject>(functions(), globals());
416 }
417 iterator_range<Module::const_global_object_iterator>
418 Module::global_objects() const {
419   return concat<const GlobalObject>(functions(), globals());
420 }
421 
422 iterator_range<Module::global_value_iterator> Module::global_values() {
423   return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs());
424 }
425 iterator_range<Module::const_global_value_iterator>
426 Module::global_values() const {
427   return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs());
428 }
429 
430 //===----------------------------------------------------------------------===//
431 // Methods to control the materialization of GlobalValues in the Module.
432 //
433 void Module::setMaterializer(GVMaterializer *GVM) {
434   assert(!Materializer &&
435          "Module already has a GVMaterializer.  Call materializeAll"
436          " to clear it out before setting another one.");
437   Materializer.reset(GVM);
438 }
439 
440 Error Module::materialize(GlobalValue *GV) {
441   if (!Materializer)
442     return Error::success();
443 
444   return Materializer->materialize(GV);
445 }
446 
447 Error Module::materializeAll() {
448   if (!Materializer)
449     return Error::success();
450   std::unique_ptr<GVMaterializer> M = std::move(Materializer);
451   return M->materializeModule();
452 }
453 
454 Error Module::materializeMetadata() {
455   if (!Materializer)
456     return Error::success();
457   return Materializer->materializeMetadata();
458 }
459 
460 //===----------------------------------------------------------------------===//
461 // Other module related stuff.
462 //
463 
464 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
465   // If we have a materializer, it is possible that some unread function
466   // uses a type that is currently not visible to a TypeFinder, so ask
467   // the materializer which types it created.
468   if (Materializer)
469     return Materializer->getIdentifiedStructTypes();
470 
471   std::vector<StructType *> Ret;
472   TypeFinder SrcStructTypes;
473   SrcStructTypes.run(*this, true);
474   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
475   return Ret;
476 }
477 
478 std::string Module::getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id,
479                                            const FunctionType *Proto) {
480   auto Encode = [&BaseName](unsigned Suffix) {
481     return (Twine(BaseName) + "." + Twine(Suffix)).str();
482   };
483 
484   {
485     // fast path - the prototype is already known
486     auto UinItInserted = UniquedIntrinsicNames.insert({{Id, Proto}, 0});
487     if (!UinItInserted.second)
488       return Encode(UinItInserted.first->second);
489   }
490 
491   // Not known yet. A new entry was created with index 0. Check if there already
492   // exists a matching declaration, or select a new entry.
493 
494   // Start looking for names with the current known maximum count (or 0).
495   auto NiidItInserted = CurrentIntrinsicIds.insert({BaseName, 0});
496   unsigned Count = NiidItInserted.first->second;
497 
498   // This might be slow if a whole population of intrinsics already existed, but
499   // we cache the values for later usage.
500   std::string NewName;
501   while (true) {
502     NewName = Encode(Count);
503     GlobalValue *F = getNamedValue(NewName);
504     if (!F) {
505       // Reserve this entry for the new proto
506       UniquedIntrinsicNames[{Id, Proto}] = Count;
507       break;
508     }
509 
510     // A declaration with this name already exists. Remember it.
511     FunctionType *FT = dyn_cast<FunctionType>(F->getValueType());
512     auto UinItInserted = UniquedIntrinsicNames.insert({{Id, FT}, Count});
513     if (FT == Proto) {
514       // It was a declaration for our prototype. This entry was allocated in the
515       // beginning. Update the count to match the existing declaration.
516       UinItInserted.first->second = Count;
517       break;
518     }
519 
520     ++Count;
521   }
522 
523   NiidItInserted.first->second = Count + 1;
524 
525   return NewName;
526 }
527 
528 // dropAllReferences() - This function causes all the subelements to "let go"
529 // of all references that they are maintaining.  This allows one to 'delete' a
530 // whole module at a time, even though there may be circular references... first
531 // all references are dropped, and all use counts go to zero.  Then everything
532 // is deleted for real.  Note that no operations are valid on an object that
533 // has "dropped all references", except operator delete.
534 //
535 void Module::dropAllReferences() {
536   for (Function &F : *this)
537     F.dropAllReferences();
538 
539   for (GlobalVariable &GV : globals())
540     GV.dropAllReferences();
541 
542   for (GlobalAlias &GA : aliases())
543     GA.dropAllReferences();
544 
545   for (GlobalIFunc &GIF : ifuncs())
546     GIF.dropAllReferences();
547 }
548 
549 unsigned Module::getNumberRegisterParameters() const {
550   auto *Val =
551       cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
552   if (!Val)
553     return 0;
554   return cast<ConstantInt>(Val->getValue())->getZExtValue();
555 }
556 
557 unsigned Module::getDwarfVersion() const {
558   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
559   if (!Val)
560     return 0;
561   return cast<ConstantInt>(Val->getValue())->getZExtValue();
562 }
563 
564 bool Module::isDwarf64() const {
565   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("DWARF64"));
566   return Val && cast<ConstantInt>(Val->getValue())->isOne();
567 }
568 
569 unsigned Module::getCodeViewFlag() const {
570   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
571   if (!Val)
572     return 0;
573   return cast<ConstantInt>(Val->getValue())->getZExtValue();
574 }
575 
576 unsigned Module::getInstructionCount() const {
577   unsigned NumInstrs = 0;
578   for (const Function &F : FunctionList)
579     NumInstrs += F.getInstructionCount();
580   return NumInstrs;
581 }
582 
583 Comdat *Module::getOrInsertComdat(StringRef Name) {
584   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
585   Entry.second.Name = &Entry;
586   return &Entry.second;
587 }
588 
589 PICLevel::Level Module::getPICLevel() const {
590   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
591 
592   if (!Val)
593     return PICLevel::NotPIC;
594 
595   return static_cast<PICLevel::Level>(
596       cast<ConstantInt>(Val->getValue())->getZExtValue());
597 }
598 
599 void Module::setPICLevel(PICLevel::Level PL) {
600   addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
601 }
602 
603 PIELevel::Level Module::getPIELevel() const {
604   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
605 
606   if (!Val)
607     return PIELevel::Default;
608 
609   return static_cast<PIELevel::Level>(
610       cast<ConstantInt>(Val->getValue())->getZExtValue());
611 }
612 
613 void Module::setPIELevel(PIELevel::Level PL) {
614   addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
615 }
616 
617 Optional<CodeModel::Model> Module::getCodeModel() const {
618   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
619 
620   if (!Val)
621     return None;
622 
623   return static_cast<CodeModel::Model>(
624       cast<ConstantInt>(Val->getValue())->getZExtValue());
625 }
626 
627 void Module::setCodeModel(CodeModel::Model CL) {
628   // Linking object files with different code models is undefined behavior
629   // because the compiler would have to generate additional code (to span
630   // longer jumps) if a larger code model is used with a smaller one.
631   // Therefore we will treat attempts to mix code models as an error.
632   addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
633 }
634 
635 void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) {
636   if (Kind == ProfileSummary::PSK_CSInstr)
637     setModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M);
638   else
639     setModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
640 }
641 
642 Metadata *Module::getProfileSummary(bool IsCS) const {
643   return (IsCS ? getModuleFlag("CSProfileSummary")
644                : getModuleFlag("ProfileSummary"));
645 }
646 
647 bool Module::getSemanticInterposition() const {
648   Metadata *MF = getModuleFlag("SemanticInterposition");
649 
650   auto *Val = cast_or_null<ConstantAsMetadata>(MF);
651   if (!Val)
652     return false;
653 
654   return cast<ConstantInt>(Val->getValue())->getZExtValue();
655 }
656 
657 void Module::setSemanticInterposition(bool SI) {
658   addModuleFlag(ModFlagBehavior::Error, "SemanticInterposition", SI);
659 }
660 
661 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
662   OwnedMemoryBuffer = std::move(MB);
663 }
664 
665 bool Module::getRtLibUseGOT() const {
666   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
667   return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
668 }
669 
670 void Module::setRtLibUseGOT() {
671   addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
672 }
673 
674 bool Module::getUwtable() const {
675   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("uwtable"));
676   return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
677 }
678 
679 void Module::setUwtable() { addModuleFlag(ModFlagBehavior::Max, "uwtable", 1); }
680 
681 FramePointerKind Module::getFramePointer() const {
682   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("frame-pointer"));
683   return static_cast<FramePointerKind>(
684       Val ? cast<ConstantInt>(Val->getValue())->getZExtValue() : 0);
685 }
686 
687 void Module::setFramePointer(FramePointerKind Kind) {
688   addModuleFlag(ModFlagBehavior::Max, "frame-pointer", static_cast<int>(Kind));
689 }
690 
691 StringRef Module::getStackProtectorGuard() const {
692   Metadata *MD = getModuleFlag("stack-protector-guard");
693   if (auto *MDS = dyn_cast_or_null<MDString>(MD))
694     return MDS->getString();
695   return {};
696 }
697 
698 void Module::setStackProtectorGuard(StringRef Kind) {
699   MDString *ID = MDString::get(getContext(), Kind);
700   addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard", ID);
701 }
702 
703 StringRef Module::getStackProtectorGuardReg() const {
704   Metadata *MD = getModuleFlag("stack-protector-guard-reg");
705   if (auto *MDS = dyn_cast_or_null<MDString>(MD))
706     return MDS->getString();
707   return {};
708 }
709 
710 void Module::setStackProtectorGuardReg(StringRef Reg) {
711   MDString *ID = MDString::get(getContext(), Reg);
712   addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-reg", ID);
713 }
714 
715 int Module::getStackProtectorGuardOffset() const {
716   Metadata *MD = getModuleFlag("stack-protector-guard-offset");
717   if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
718     return CI->getSExtValue();
719   return INT_MAX;
720 }
721 
722 void Module::setStackProtectorGuardOffset(int Offset) {
723   addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-offset", Offset);
724 }
725 
726 unsigned Module::getOverrideStackAlignment() const {
727   Metadata *MD = getModuleFlag("override-stack-alignment");
728   if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
729     return CI->getZExtValue();
730   return 0;
731 }
732 
733 void Module::setOverrideStackAlignment(unsigned Align) {
734   addModuleFlag(ModFlagBehavior::Error, "override-stack-alignment", Align);
735 }
736 
737 void Module::setSDKVersion(const VersionTuple &V) {
738   SmallVector<unsigned, 3> Entries;
739   Entries.push_back(V.getMajor());
740   if (auto Minor = V.getMinor()) {
741     Entries.push_back(*Minor);
742     if (auto Subminor = V.getSubminor())
743       Entries.push_back(*Subminor);
744     // Ignore the 'build' component as it can't be represented in the object
745     // file.
746   }
747   addModuleFlag(ModFlagBehavior::Warning, "SDK Version",
748                 ConstantDataArray::get(Context, Entries));
749 }
750 
751 static VersionTuple getSDKVersionMD(Metadata *MD) {
752   auto *CM = dyn_cast_or_null<ConstantAsMetadata>(MD);
753   if (!CM)
754     return {};
755   auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
756   if (!Arr)
757     return {};
758   auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> {
759     if (Index >= Arr->getNumElements())
760       return None;
761     return (unsigned)Arr->getElementAsInteger(Index);
762   };
763   auto Major = getVersionComponent(0);
764   if (!Major)
765     return {};
766   VersionTuple Result = VersionTuple(*Major);
767   if (auto Minor = getVersionComponent(1)) {
768     Result = VersionTuple(*Major, *Minor);
769     if (auto Subminor = getVersionComponent(2)) {
770       Result = VersionTuple(*Major, *Minor, *Subminor);
771     }
772   }
773   return Result;
774 }
775 
776 VersionTuple Module::getSDKVersion() const {
777   return getSDKVersionMD(getModuleFlag("SDK Version"));
778 }
779 
780 GlobalVariable *llvm::collectUsedGlobalVariables(
781     const Module &M, SmallVectorImpl<GlobalValue *> &Vec, bool CompilerUsed) {
782   const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
783   GlobalVariable *GV = M.getGlobalVariable(Name);
784   if (!GV || !GV->hasInitializer())
785     return GV;
786 
787   const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
788   for (Value *Op : Init->operands()) {
789     GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts());
790     Vec.push_back(G);
791   }
792   return GV;
793 }
794 
795 void Module::setPartialSampleProfileRatio(const ModuleSummaryIndex &Index) {
796   if (auto *SummaryMD = getProfileSummary(/*IsCS*/ false)) {
797     std::unique_ptr<ProfileSummary> ProfileSummary(
798         ProfileSummary::getFromMD(SummaryMD));
799     if (ProfileSummary) {
800       if (ProfileSummary->getKind() != ProfileSummary::PSK_Sample ||
801           !ProfileSummary->isPartialProfile())
802         return;
803       uint64_t BlockCount = Index.getBlockCount();
804       uint32_t NumCounts = ProfileSummary->getNumCounts();
805       if (!NumCounts)
806         return;
807       double Ratio = (double)BlockCount / NumCounts;
808       ProfileSummary->setPartialProfileRatio(Ratio);
809       setProfileSummary(ProfileSummary->getMD(getContext()),
810                         ProfileSummary::PSK_Sample);
811     }
812   }
813 }
814 
815 StringRef Module::getDarwinTargetVariantTriple() const {
816   if (const auto *MD = getModuleFlag("darwin.target_variant.triple"))
817     return cast<MDString>(MD)->getString();
818   return "";
819 }
820 
821 VersionTuple Module::getDarwinTargetVariantSDKVersion() const {
822   return getSDKVersionMD(getModuleFlag("darwin.target_variant.SDK Version"));
823 }
824