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