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
Module(StringRef MID,LLVMContext & C)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
~Module()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
createRNG(const Pass * P) const92 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.
getNamedValue(StringRef Name) const113 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.
getMDKindID(StringRef Name) const119 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.
getMDKindNames(SmallVectorImpl<StringRef> & Result) const126 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
127 return Context.getMDKindNames(Result);
128 }
129
getOperandBundleTags(SmallVectorImpl<StringRef> & Result) const130 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 //
getOrInsertFunction(StringRef Name,FunctionType * Ty,AttributeList AttributeList)143 FunctionCallee 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 {Ty, 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 {Ty, ConstantExpr::getBitCast(F, PTy)};
162
163 // Otherwise, we just found the existing function or a prototype.
164 return {Ty, F};
165 }
166
getOrInsertFunction(StringRef Name,FunctionType * Ty)167 FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) {
168 return getOrInsertFunction(Name, Ty, AttributeList());
169 }
170
171 // getFunction - Look up the specified function in the module symbol table.
172 // If it does not exist, return null.
173 //
getFunction(StringRef Name) const174 Function *Module::getFunction(StringRef Name) const {
175 return dyn_cast_or_null<Function>(getNamedValue(Name));
176 }
177
178 //===----------------------------------------------------------------------===//
179 // Methods for easy access to the global variables in the module.
180 //
181
182 /// getGlobalVariable - Look up the specified global variable in the module
183 /// symbol table. If it does not exist, return null. The type argument
184 /// should be the underlying type of the global, i.e., it should not have
185 /// the top-level PointerType, which represents the address of the global.
186 /// If AllowLocal is set to true, this function will return types that
187 /// have an local. By default, these types are not returned.
188 ///
getGlobalVariable(StringRef Name,bool AllowLocal) const189 GlobalVariable *Module::getGlobalVariable(StringRef Name,
190 bool AllowLocal) const {
191 if (GlobalVariable *Result =
192 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
193 if (AllowLocal || !Result->hasLocalLinkage())
194 return Result;
195 return nullptr;
196 }
197
198 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
199 /// 1. If it does not exist, add a declaration of the global and return it.
200 /// 2. Else, the global exists but has the wrong type: return the function
201 /// with a constantexpr cast to the right type.
202 /// 3. Finally, if the existing global is the correct declaration, return the
203 /// existing global.
getOrInsertGlobal(StringRef Name,Type * Ty,function_ref<GlobalVariable * ()> CreateGlobalCallback)204 Constant *Module::getOrInsertGlobal(
205 StringRef Name, Type *Ty,
206 function_ref<GlobalVariable *()> CreateGlobalCallback) {
207 // See if we have a definition for the specified global already.
208 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
209 if (!GV)
210 GV = CreateGlobalCallback();
211 assert(GV && "The CreateGlobalCallback is expected to create a global");
212
213 // If the variable exists but has the wrong type, return a bitcast to the
214 // right type.
215 Type *GVTy = GV->getType();
216 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
217 if (GVTy != PTy)
218 return ConstantExpr::getBitCast(GV, PTy);
219
220 // Otherwise, we just found the existing function or a prototype.
221 return GV;
222 }
223
224 // Overload to construct a global variable using its constructor's defaults.
getOrInsertGlobal(StringRef Name,Type * Ty)225 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
226 return getOrInsertGlobal(Name, Ty, [&] {
227 return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
228 nullptr, Name);
229 });
230 }
231
232 //===----------------------------------------------------------------------===//
233 // Methods for easy access to the global variables in the module.
234 //
235
236 // getNamedAlias - Look up the specified global in the module symbol table.
237 // If it does not exist, return null.
238 //
getNamedAlias(StringRef Name) const239 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
240 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
241 }
242
getNamedIFunc(StringRef Name) const243 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
244 return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
245 }
246
247 /// getNamedMetadata - Return the first NamedMDNode in the module with the
248 /// specified name. This method returns null if a NamedMDNode with the
249 /// specified name is not found.
getNamedMetadata(const Twine & Name) const250 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
251 SmallString<256> NameData;
252 StringRef NameRef = Name.toStringRef(NameData);
253 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
254 }
255
256 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
257 /// with the specified name. This method returns a new NamedMDNode if a
258 /// NamedMDNode with the specified name is not found.
getOrInsertNamedMetadata(StringRef Name)259 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
260 NamedMDNode *&NMD =
261 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
262 if (!NMD) {
263 NMD = new NamedMDNode(Name);
264 NMD->setParent(this);
265 NamedMDList.push_back(NMD);
266 }
267 return NMD;
268 }
269
270 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
271 /// delete it.
eraseNamedMetadata(NamedMDNode * NMD)272 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
273 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
274 NamedMDList.erase(NMD->getIterator());
275 }
276
isValidModFlagBehavior(Metadata * MD,ModFlagBehavior & MFB)277 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
278 if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
279 uint64_t Val = Behavior->getLimitedValue();
280 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
281 MFB = static_cast<ModFlagBehavior>(Val);
282 return true;
283 }
284 }
285 return false;
286 }
287
288 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
289 void Module::
getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> & Flags) const290 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
291 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
292 if (!ModFlags) return;
293
294 for (const MDNode *Flag : ModFlags->operands()) {
295 ModFlagBehavior MFB;
296 if (Flag->getNumOperands() >= 3 &&
297 isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
298 dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
299 // Check the operands of the MDNode before accessing the operands.
300 // The verifier will actually catch these failures.
301 MDString *Key = cast<MDString>(Flag->getOperand(1));
302 Metadata *Val = Flag->getOperand(2);
303 Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
304 }
305 }
306 }
307
308 /// Return the corresponding value if Key appears in module flags, otherwise
309 /// return null.
getModuleFlag(StringRef Key) const310 Metadata *Module::getModuleFlag(StringRef Key) const {
311 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
312 getModuleFlagsMetadata(ModuleFlags);
313 for (const ModuleFlagEntry &MFE : ModuleFlags) {
314 if (Key == MFE.Key->getString())
315 return MFE.Val;
316 }
317 return nullptr;
318 }
319
320 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
321 /// represents module-level flags. This method returns null if there are no
322 /// module-level flags.
getModuleFlagsMetadata() const323 NamedMDNode *Module::getModuleFlagsMetadata() const {
324 return getNamedMetadata("llvm.module.flags");
325 }
326
327 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
328 /// represents module-level flags. If module-level flags aren't found, it
329 /// creates the named metadata that contains them.
getOrInsertModuleFlagsMetadata()330 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
331 return getOrInsertNamedMetadata("llvm.module.flags");
332 }
333
334 /// addModuleFlag - Add a module-level flag to the module-level flags
335 /// metadata. It will create the module-level flags named metadata if it doesn't
336 /// already exist.
addModuleFlag(ModFlagBehavior Behavior,StringRef Key,Metadata * Val)337 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
338 Metadata *Val) {
339 Type *Int32Ty = Type::getInt32Ty(Context);
340 Metadata *Ops[3] = {
341 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
342 MDString::get(Context, Key), Val};
343 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
344 }
addModuleFlag(ModFlagBehavior Behavior,StringRef Key,Constant * Val)345 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
346 Constant *Val) {
347 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
348 }
addModuleFlag(ModFlagBehavior Behavior,StringRef Key,uint32_t Val)349 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
350 uint32_t Val) {
351 Type *Int32Ty = Type::getInt32Ty(Context);
352 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
353 }
addModuleFlag(MDNode * Node)354 void Module::addModuleFlag(MDNode *Node) {
355 assert(Node->getNumOperands() == 3 &&
356 "Invalid number of operands for module flag!");
357 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
358 isa<MDString>(Node->getOperand(1)) &&
359 "Invalid operand types for module flag!");
360 getOrInsertModuleFlagsMetadata()->addOperand(Node);
361 }
362
setDataLayout(StringRef Desc)363 void Module::setDataLayout(StringRef Desc) {
364 DL.reset(Desc);
365 }
366
setDataLayout(const DataLayout & Other)367 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
368
getDataLayout() const369 const DataLayout &Module::getDataLayout() const { return DL; }
370
operator *() const371 DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
372 return cast<DICompileUnit>(CUs->getOperand(Idx));
373 }
operator ->() const374 DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
375 return cast<DICompileUnit>(CUs->getOperand(Idx));
376 }
377
SkipNoDebugCUs()378 void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
379 while (CUs && (Idx < CUs->getNumOperands()) &&
380 ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
381 ++Idx;
382 }
383
global_objects()384 iterator_range<Module::global_object_iterator> Module::global_objects() {
385 return concat<GlobalObject>(functions(), globals());
386 }
387 iterator_range<Module::const_global_object_iterator>
global_objects() const388 Module::global_objects() const {
389 return concat<const GlobalObject>(functions(), globals());
390 }
391
global_values()392 iterator_range<Module::global_value_iterator> Module::global_values() {
393 return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs());
394 }
395 iterator_range<Module::const_global_value_iterator>
global_values() const396 Module::global_values() const {
397 return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs());
398 }
399
400 //===----------------------------------------------------------------------===//
401 // Methods to control the materialization of GlobalValues in the Module.
402 //
setMaterializer(GVMaterializer * GVM)403 void Module::setMaterializer(GVMaterializer *GVM) {
404 assert(!Materializer &&
405 "Module already has a GVMaterializer. Call materializeAll"
406 " to clear it out before setting another one.");
407 Materializer.reset(GVM);
408 }
409
materialize(GlobalValue * GV)410 Error Module::materialize(GlobalValue *GV) {
411 if (!Materializer)
412 return Error::success();
413
414 return Materializer->materialize(GV);
415 }
416
materializeAll()417 Error Module::materializeAll() {
418 if (!Materializer)
419 return Error::success();
420 std::unique_ptr<GVMaterializer> M = std::move(Materializer);
421 return M->materializeModule();
422 }
423
materializeMetadata()424 Error Module::materializeMetadata() {
425 if (!Materializer)
426 return Error::success();
427 return Materializer->materializeMetadata();
428 }
429
430 //===----------------------------------------------------------------------===//
431 // Other module related stuff.
432 //
433
getIdentifiedStructTypes() const434 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
435 // If we have a materializer, it is possible that some unread function
436 // uses a type that is currently not visible to a TypeFinder, so ask
437 // the materializer which types it created.
438 if (Materializer)
439 return Materializer->getIdentifiedStructTypes();
440
441 std::vector<StructType *> Ret;
442 TypeFinder SrcStructTypes;
443 SrcStructTypes.run(*this, true);
444 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
445 return Ret;
446 }
447
448 // dropAllReferences() - This function causes all the subelements to "let go"
449 // of all references that they are maintaining. This allows one to 'delete' a
450 // whole module at a time, even though there may be circular references... first
451 // all references are dropped, and all use counts go to zero. Then everything
452 // is deleted for real. Note that no operations are valid on an object that
453 // has "dropped all references", except operator delete.
454 //
dropAllReferences()455 void Module::dropAllReferences() {
456 for (Function &F : *this)
457 F.dropAllReferences();
458
459 for (GlobalVariable &GV : globals())
460 GV.dropAllReferences();
461
462 for (GlobalAlias &GA : aliases())
463 GA.dropAllReferences();
464
465 for (GlobalIFunc &GIF : ifuncs())
466 GIF.dropAllReferences();
467 }
468
getNumberRegisterParameters() const469 unsigned Module::getNumberRegisterParameters() const {
470 auto *Val =
471 cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
472 if (!Val)
473 return 0;
474 return cast<ConstantInt>(Val->getValue())->getZExtValue();
475 }
476
getDwarfVersion() const477 unsigned Module::getDwarfVersion() const {
478 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
479 if (!Val)
480 return 0;
481 return cast<ConstantInt>(Val->getValue())->getZExtValue();
482 }
483
getCodeViewFlag() const484 unsigned Module::getCodeViewFlag() const {
485 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
486 if (!Val)
487 return 0;
488 return cast<ConstantInt>(Val->getValue())->getZExtValue();
489 }
490
getInstructionCount()491 unsigned Module::getInstructionCount() {
492 unsigned NumInstrs = 0;
493 for (Function &F : FunctionList)
494 NumInstrs += F.getInstructionCount();
495 return NumInstrs;
496 }
497
getOrInsertComdat(StringRef Name)498 Comdat *Module::getOrInsertComdat(StringRef Name) {
499 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
500 Entry.second.Name = &Entry;
501 return &Entry.second;
502 }
503
getPICLevel() const504 PICLevel::Level Module::getPICLevel() const {
505 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
506
507 if (!Val)
508 return PICLevel::NotPIC;
509
510 return static_cast<PICLevel::Level>(
511 cast<ConstantInt>(Val->getValue())->getZExtValue());
512 }
513
setPICLevel(PICLevel::Level PL)514 void Module::setPICLevel(PICLevel::Level PL) {
515 addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
516 }
517
getPIELevel() const518 PIELevel::Level Module::getPIELevel() const {
519 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
520
521 if (!Val)
522 return PIELevel::Default;
523
524 return static_cast<PIELevel::Level>(
525 cast<ConstantInt>(Val->getValue())->getZExtValue());
526 }
527
setPIELevel(PIELevel::Level PL)528 void Module::setPIELevel(PIELevel::Level PL) {
529 addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
530 }
531
getCodeModel() const532 Optional<CodeModel::Model> Module::getCodeModel() const {
533 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
534
535 if (!Val)
536 return None;
537
538 return static_cast<CodeModel::Model>(
539 cast<ConstantInt>(Val->getValue())->getZExtValue());
540 }
541
setCodeModel(CodeModel::Model CL)542 void Module::setCodeModel(CodeModel::Model CL) {
543 // Linking object files with different code models is undefined behavior
544 // because the compiler would have to generate additional code (to span
545 // longer jumps) if a larger code model is used with a smaller one.
546 // Therefore we will treat attempts to mix code models as an error.
547 addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
548 }
549
setProfileSummary(Metadata * M,ProfileSummary::Kind Kind)550 void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) {
551 if (Kind == ProfileSummary::PSK_CSInstr)
552 addModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M);
553 else
554 addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
555 }
556
getProfileSummary(bool IsCS)557 Metadata *Module::getProfileSummary(bool IsCS) {
558 return (IsCS ? getModuleFlag("CSProfileSummary")
559 : getModuleFlag("ProfileSummary"));
560 }
561
setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB)562 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
563 OwnedMemoryBuffer = std::move(MB);
564 }
565
getRtLibUseGOT() const566 bool Module::getRtLibUseGOT() const {
567 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
568 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
569 }
570
setRtLibUseGOT()571 void Module::setRtLibUseGOT() {
572 addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
573 }
574
setSDKVersion(const VersionTuple & V)575 void Module::setSDKVersion(const VersionTuple &V) {
576 SmallVector<unsigned, 3> Entries;
577 Entries.push_back(V.getMajor());
578 if (auto Minor = V.getMinor()) {
579 Entries.push_back(*Minor);
580 if (auto Subminor = V.getSubminor())
581 Entries.push_back(*Subminor);
582 // Ignore the 'build' component as it can't be represented in the object
583 // file.
584 }
585 addModuleFlag(ModFlagBehavior::Warning, "SDK Version",
586 ConstantDataArray::get(Context, Entries));
587 }
588
getSDKVersion() const589 VersionTuple Module::getSDKVersion() const {
590 auto *CM = dyn_cast_or_null<ConstantAsMetadata>(getModuleFlag("SDK Version"));
591 if (!CM)
592 return {};
593 auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
594 if (!Arr)
595 return {};
596 auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> {
597 if (Index >= Arr->getNumElements())
598 return None;
599 return (unsigned)Arr->getElementAsInteger(Index);
600 };
601 auto Major = getVersionComponent(0);
602 if (!Major)
603 return {};
604 VersionTuple Result = VersionTuple(*Major);
605 if (auto Minor = getVersionComponent(1)) {
606 Result = VersionTuple(*Major, *Minor);
607 if (auto Subminor = getVersionComponent(2)) {
608 Result = VersionTuple(*Major, *Minor, *Subminor);
609 }
610 }
611 return Result;
612 }
613
collectUsedGlobalVariables(const Module & M,SmallPtrSetImpl<GlobalValue * > & Set,bool CompilerUsed)614 GlobalVariable *llvm::collectUsedGlobalVariables(
615 const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
616 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
617 GlobalVariable *GV = M.getGlobalVariable(Name);
618 if (!GV || !GV->hasInitializer())
619 return GV;
620
621 const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
622 for (Value *Op : Init->operands()) {
623 GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts());
624 Set.insert(G);
625 }
626 return GV;
627 }
628