1 //===-- Module.cpp - Implement the Module class ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Module class for the IR library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/Module.h"
15 #include "SymbolTableListTraitsImpl.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/GVMaterializer.h"
23 #include "llvm/IR/InstrTypes.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/TypeFinder.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/RandomNumberGenerator.h"
35 //===----------------------------------------------------------------------===//
36 // Methods to implement the globals and functions lists.
39 // Explicit instantiations of SymbolTableListTraits since some of the methods
40 // are not in the public header file.
41 template class llvm::SymbolTableListTraits<Function>;
42 template class llvm::SymbolTableListTraits<GlobalVariable>;
43 template class llvm::SymbolTableListTraits<GlobalAlias>;
45 //===----------------------------------------------------------------------===//
46 // Primitive Module methods.
49 Module::Module(StringRef MID, LLVMContext &C)
50 : Context(C), Materializer(), ModuleID(MID), DL("") {
51 ValSymTab = new ValueSymbolTable();
52 NamedMDSymTab = new StringMap<NamedMDNode *>();
53 Context.addModule(this);
57 Context.removeModule(this);
64 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
67 RandomNumberGenerator *Module::createRNG(const Pass* P) const {
68 SmallString<32> Salt(P->getPassName());
70 // This RNG is guaranteed to produce the same random stream only
71 // when the Module ID and thus the input filename is the same. This
72 // might be problematic if the input filename extension changes
73 // (e.g. from .c to .bc or .ll).
75 // We could store this salt in NamedMetadata, but this would make
76 // the parameter non-const. This would unfortunately make this
77 // interface unusable by any Machine passes, since they only have a
78 // const reference to their IR Module. Alternatively we can always
79 // store salt metadata from the Module constructor.
80 Salt += sys::path::filename(getModuleIdentifier());
82 return new RandomNumberGenerator(Salt);
85 /// getNamedValue - Return the first global value in the module with
86 /// the specified name, of arbitrary type. This method returns null
87 /// if a global with the specified name is not found.
88 GlobalValue *Module::getNamedValue(StringRef Name) const {
89 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
92 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
93 /// This ID is uniqued across modules in the current LLVMContext.
94 unsigned Module::getMDKindID(StringRef Name) const {
95 return Context.getMDKindID(Name);
98 /// getMDKindNames - Populate client supplied SmallVector with the name for
99 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
100 /// so it is filled in as an empty string.
101 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
102 return Context.getMDKindNames(Result);
105 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
106 return Context.getOperandBundleTags(Result);
109 //===----------------------------------------------------------------------===//
110 // Methods for easy access to the functions in the module.
113 // getOrInsertFunction - Look up the specified function in the module symbol
114 // table. If it does not exist, add a prototype for the function and return
115 // it. This is nice because it allows most passes to get away with not handling
116 // the symbol table directly for this common task.
118 Constant *Module::getOrInsertFunction(StringRef Name,
120 AttributeSet AttributeList) {
121 // See if we have a definition for the specified function already.
122 GlobalValue *F = getNamedValue(Name);
125 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
126 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
127 New->setAttributes(AttributeList);
128 FunctionList.push_back(New);
129 return New; // Return the new prototype.
132 // If the function exists but has the wrong type, return a bitcast to the
134 if (F->getType() != PointerType::getUnqual(Ty))
135 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
137 // Otherwise, we just found the existing function or a prototype.
141 Constant *Module::getOrInsertFunction(StringRef Name,
143 return getOrInsertFunction(Name, Ty, AttributeSet());
146 // getOrInsertFunction - Look up the specified function in the module symbol
147 // table. If it does not exist, add a prototype for the function and return it.
148 // This version of the method takes a null terminated list of function
149 // arguments, which makes it easier for clients to use.
151 Constant *Module::getOrInsertFunction(StringRef Name,
152 AttributeSet AttributeList,
155 va_start(Args, RetTy);
157 // Build the list of argument types...
158 std::vector<Type*> ArgTys;
159 while (Type *ArgTy = va_arg(Args, Type*))
160 ArgTys.push_back(ArgTy);
164 // Build the function type and chain to the other getOrInsertFunction...
165 return getOrInsertFunction(Name,
166 FunctionType::get(RetTy, ArgTys, false),
170 Constant *Module::getOrInsertFunction(StringRef Name,
173 va_start(Args, RetTy);
175 // Build the list of argument types...
176 std::vector<Type*> ArgTys;
177 while (Type *ArgTy = va_arg(Args, Type*))
178 ArgTys.push_back(ArgTy);
182 // Build the function type and chain to the other getOrInsertFunction...
183 return getOrInsertFunction(Name,
184 FunctionType::get(RetTy, ArgTys, false),
188 // getFunction - Look up the specified function in the module symbol table.
189 // If it does not exist, return null.
191 Function *Module::getFunction(StringRef Name) const {
192 return dyn_cast_or_null<Function>(getNamedValue(Name));
195 //===----------------------------------------------------------------------===//
196 // Methods for easy access to the global variables in the module.
199 /// getGlobalVariable - Look up the specified global variable in the module
200 /// symbol table. If it does not exist, return null. The type argument
201 /// should be the underlying type of the global, i.e., it should not have
202 /// the top-level PointerType, which represents the address of the global.
203 /// If AllowLocal is set to true, this function will return types that
204 /// have an local. By default, these types are not returned.
206 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
207 if (GlobalVariable *Result =
208 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
209 if (AllowLocal || !Result->hasLocalLinkage())
214 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
215 /// 1. If it does not exist, add a declaration of the global and return it.
216 /// 2. Else, the global exists but has the wrong type: return the function
217 /// with a constantexpr cast to the right type.
218 /// 3. Finally, if the existing global is the correct declaration, return the
220 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
221 // See if we have a definition for the specified global already.
222 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
225 GlobalVariable *New =
226 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
228 return New; // Return the new declaration.
231 // If the variable exists but has the wrong type, return a bitcast to the
233 Type *GVTy = GV->getType();
234 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
236 return ConstantExpr::getBitCast(GV, PTy);
238 // Otherwise, we just found the existing function or a prototype.
242 //===----------------------------------------------------------------------===//
243 // Methods for easy access to the global variables in the module.
246 // getNamedAlias - Look up the specified global in the module symbol table.
247 // If it does not exist, return null.
249 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
250 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
253 /// getNamedMetadata - Return the first NamedMDNode in the module with the
254 /// specified name. This method returns null if a NamedMDNode with the
255 /// specified name is not found.
256 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
257 SmallString<256> NameData;
258 StringRef NameRef = Name.toStringRef(NameData);
259 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
262 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
263 /// with the specified name. This method returns a new NamedMDNode if a
264 /// NamedMDNode with the specified name is not found.
265 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
267 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
269 NMD = new NamedMDNode(Name);
270 NMD->setParent(this);
271 NamedMDList.push_back(NMD);
276 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
278 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
279 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
280 NamedMDList.erase(NMD->getIterator());
283 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
284 if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
285 uint64_t Val = Behavior->getLimitedValue();
286 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
287 MFB = static_cast<ModFlagBehavior>(Val);
294 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
296 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
297 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
298 if (!ModFlags) return;
300 for (const MDNode *Flag : ModFlags->operands()) {
302 if (Flag->getNumOperands() >= 3 &&
303 isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
304 dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
305 // Check the operands of the MDNode before accessing the operands.
306 // The verifier will actually catch these failures.
307 MDString *Key = cast<MDString>(Flag->getOperand(1));
308 Metadata *Val = Flag->getOperand(2);
309 Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
314 /// Return the corresponding value if Key appears in module flags, otherwise
316 Metadata *Module::getModuleFlag(StringRef Key) const {
317 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
318 getModuleFlagsMetadata(ModuleFlags);
319 for (const ModuleFlagEntry &MFE : ModuleFlags) {
320 if (Key == MFE.Key->getString())
326 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
327 /// represents module-level flags. This method returns null if there are no
328 /// module-level flags.
329 NamedMDNode *Module::getModuleFlagsMetadata() const {
330 return getNamedMetadata("llvm.module.flags");
333 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
334 /// represents module-level flags. If module-level flags aren't found, it
335 /// creates the named metadata that contains them.
336 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
337 return getOrInsertNamedMetadata("llvm.module.flags");
340 /// addModuleFlag - Add a module-level flag to the module-level flags
341 /// metadata. It will create the module-level flags named metadata if it doesn't
343 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
345 Type *Int32Ty = Type::getInt32Ty(Context);
347 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
348 MDString::get(Context, Key), Val};
349 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
351 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
353 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
355 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
357 Type *Int32Ty = Type::getInt32Ty(Context);
358 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
360 void Module::addModuleFlag(MDNode *Node) {
361 assert(Node->getNumOperands() == 3 &&
362 "Invalid number of operands for module flag!");
363 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
364 isa<MDString>(Node->getOperand(1)) &&
365 "Invalid operand types for module flag!");
366 getOrInsertModuleFlagsMetadata()->addOperand(Node);
369 void Module::setDataLayout(StringRef Desc) {
373 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
375 const DataLayout &Module::getDataLayout() const { return DL; }
377 //===----------------------------------------------------------------------===//
378 // Methods to control the materialization of GlobalValues in the Module.
380 void Module::setMaterializer(GVMaterializer *GVM) {
381 assert(!Materializer &&
382 "Module already has a GVMaterializer. Call MaterializeAllPermanently"
383 " to clear it out before setting another one.");
384 Materializer.reset(GVM);
387 bool Module::isDematerializable(const GlobalValue *GV) const {
389 return Materializer->isDematerializable(GV);
393 std::error_code Module::materialize(GlobalValue *GV) {
395 return std::error_code();
397 return Materializer->materialize(GV);
400 void Module::dematerialize(GlobalValue *GV) {
402 return Materializer->dematerialize(GV);
405 std::error_code Module::materializeAll() {
407 return std::error_code();
408 return Materializer->materializeModule(this);
411 std::error_code Module::materializeAllPermanently() {
412 if (std::error_code EC = materializeAll())
415 Materializer.reset();
416 return std::error_code();
419 std::error_code Module::materializeMetadata() {
421 return std::error_code();
422 return Materializer->materializeMetadata();
425 //===----------------------------------------------------------------------===//
426 // Other module related stuff.
429 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
430 // If we have a materializer, it is possible that some unread function
431 // uses a type that is currently not visible to a TypeFinder, so ask
432 // the materializer which types it created.
434 return Materializer->getIdentifiedStructTypes();
436 std::vector<StructType *> Ret;
437 TypeFinder SrcStructTypes;
438 SrcStructTypes.run(*this, true);
439 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
443 // dropAllReferences() - This function causes all the subelements to "let go"
444 // of all references that they are maintaining. This allows one to 'delete' a
445 // whole module at a time, even though there may be circular references... first
446 // all references are dropped, and all use counts go to zero. Then everything
447 // is deleted for real. Note that no operations are valid on an object that
448 // has "dropped all references", except operator delete.
450 void Module::dropAllReferences() {
451 for (Function &F : *this)
452 F.dropAllReferences();
454 for (GlobalVariable &GV : globals())
455 GV.dropAllReferences();
457 for (GlobalAlias &GA : aliases())
458 GA.dropAllReferences();
461 unsigned Module::getDwarfVersion() const {
462 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
465 return cast<ConstantInt>(Val->getValue())->getZExtValue();
468 unsigned Module::getCodeViewFlag() const {
469 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
472 return cast<ConstantInt>(Val->getValue())->getZExtValue();
475 Comdat *Module::getOrInsertComdat(StringRef Name) {
476 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
477 Entry.second.Name = &Entry;
478 return &Entry.second;
481 PICLevel::Level Module::getPICLevel() const {
482 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
485 return PICLevel::Default;
487 return static_cast<PICLevel::Level>(
488 cast<ConstantInt>(Val->getValue())->getZExtValue());
491 void Module::setPICLevel(PICLevel::Level PL) {
492 addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);