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 VMCore library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Module.h"
15 #include "llvm/InstrTypes.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GVMaterializer.h"
19 #include "llvm/LLVMContext.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/Support/LeakDetector.h"
25 #include "SymbolTableListTraitsImpl.h"
31 //===----------------------------------------------------------------------===//
32 // Methods to implement the globals and functions lists.
35 // Explicit instantiations of SymbolTableListTraits since some of the methods
36 // are not in the public header file.
37 template class llvm::SymbolTableListTraits
<Function
, Module
>;
38 template class llvm::SymbolTableListTraits
<GlobalVariable
, Module
>;
39 template class llvm::SymbolTableListTraits
<GlobalAlias
, Module
>;
41 //===----------------------------------------------------------------------===//
42 // Primitive Module methods.
45 Module::Module(StringRef MID
, LLVMContext
& C
)
46 : Context(C
), Materializer(NULL
), ModuleID(MID
) {
47 ValSymTab
= new ValueSymbolTable();
48 NamedMDSymTab
= new StringMap
<NamedMDNode
*>();
49 Context
.addModule(this);
53 Context
.removeModule(this);
61 delete static_cast<StringMap
<NamedMDNode
*> *>(NamedMDSymTab
);
64 /// Target endian information.
65 Module::Endianness
Module::getEndianness() const {
66 StringRef temp
= DataLayout
;
67 Module::Endianness ret
= AnyEndianness
;
69 while (!temp
.empty()) {
70 std::pair
<StringRef
, StringRef
> P
= getToken(temp
, "-");
72 StringRef token
= P
.first
;
75 if (token
[0] == 'e') {
77 } else if (token
[0] == 'E') {
85 /// Target Pointer Size information.
86 Module::PointerSize
Module::getPointerSize() const {
87 StringRef temp
= DataLayout
;
88 Module::PointerSize ret
= AnyPointerSize
;
90 while (!temp
.empty()) {
91 std::pair
<StringRef
, StringRef
> TmpP
= getToken(temp
, "-");
93 TmpP
= getToken(TmpP
.first
, ":");
94 StringRef token
= TmpP
.second
, signalToken
= TmpP
.first
;
96 if (signalToken
[0] == 'p') {
98 getToken(token
, ":").first
.getAsInteger(10, size
);
109 /// getNamedValue - Return the first global value in the module with
110 /// the specified name, of arbitrary type. This method returns null
111 /// if a global with the specified name is not found.
112 GlobalValue
*Module::getNamedValue(StringRef Name
) const {
113 return cast_or_null
<GlobalValue
>(getValueSymbolTable().lookup(Name
));
116 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
117 /// This ID is uniqued across modules in the current LLVMContext.
118 unsigned Module::getMDKindID(StringRef Name
) const {
119 return Context
.getMDKindID(Name
);
122 /// getMDKindNames - Populate client supplied SmallVector with the name for
123 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
124 /// so it is filled in as an empty string.
125 void Module::getMDKindNames(SmallVectorImpl
<StringRef
> &Result
) const {
126 return Context
.getMDKindNames(Result
);
130 //===----------------------------------------------------------------------===//
131 // Methods for easy access to the functions in the module.
134 // getOrInsertFunction - Look up the specified function in the module symbol
135 // table. If it does not exist, add a prototype for the function and return
136 // it. This is nice because it allows most passes to get away with not handling
137 // the symbol table directly for this common task.
139 Constant
*Module::getOrInsertFunction(StringRef Name
,
141 AttrListPtr AttributeList
) {
142 // See if we have a definition for the specified function already.
143 GlobalValue
*F
= getNamedValue(Name
);
146 Function
*New
= Function::Create(Ty
, GlobalVariable::ExternalLinkage
, Name
);
147 if (!New
->isIntrinsic()) // Intrinsics get attrs set on construction
148 New
->setAttributes(AttributeList
);
149 FunctionList
.push_back(New
);
150 return New
; // Return the new prototype.
153 // Okay, the function exists. Does it have externally visible linkage?
154 if (F
->hasLocalLinkage()) {
155 // Clear the function's name.
157 // Retry, now there won't be a conflict.
158 Constant
*NewF
= getOrInsertFunction(Name
, Ty
);
163 // If the function exists but has the wrong type, return a bitcast to the
165 if (F
->getType() != PointerType::getUnqual(Ty
))
166 return ConstantExpr::getBitCast(F
, PointerType::getUnqual(Ty
));
168 // Otherwise, we just found the existing function or a prototype.
172 Constant
*Module::getOrInsertTargetIntrinsic(StringRef Name
,
174 AttrListPtr AttributeList
) {
175 // See if we have a definition for the specified function already.
176 GlobalValue
*F
= getNamedValue(Name
);
179 Function
*New
= Function::Create(Ty
, GlobalVariable::ExternalLinkage
, Name
);
180 New
->setAttributes(AttributeList
);
181 FunctionList
.push_back(New
);
182 return New
; // Return the new prototype.
185 // Otherwise, we just found the existing function or a prototype.
189 Constant
*Module::getOrInsertFunction(StringRef Name
,
191 return getOrInsertFunction(Name
, Ty
, AttrListPtr());
194 // getOrInsertFunction - Look up the specified function in the module symbol
195 // table. If it does not exist, add a prototype for the function and return it.
196 // This version of the method takes a null terminated list of function
197 // arguments, which makes it easier for clients to use.
199 Constant
*Module::getOrInsertFunction(StringRef Name
,
200 AttrListPtr AttributeList
,
203 va_start(Args
, RetTy
);
205 // Build the list of argument types...
206 std::vector
<Type
*> ArgTys
;
207 while (Type
*ArgTy
= va_arg(Args
, Type
*))
208 ArgTys
.push_back(ArgTy
);
212 // Build the function type and chain to the other getOrInsertFunction...
213 return getOrInsertFunction(Name
,
214 FunctionType::get(RetTy
, ArgTys
, false),
218 Constant
*Module::getOrInsertFunction(StringRef Name
,
221 va_start(Args
, RetTy
);
223 // Build the list of argument types...
224 std::vector
<Type
*> ArgTys
;
225 while (Type
*ArgTy
= va_arg(Args
, Type
*))
226 ArgTys
.push_back(ArgTy
);
230 // Build the function type and chain to the other getOrInsertFunction...
231 return getOrInsertFunction(Name
,
232 FunctionType::get(RetTy
, ArgTys
, false),
236 // getFunction - Look up the specified function in the module symbol table.
237 // If it does not exist, return null.
239 Function
*Module::getFunction(StringRef Name
) const {
240 return dyn_cast_or_null
<Function
>(getNamedValue(Name
));
243 //===----------------------------------------------------------------------===//
244 // Methods for easy access to the global variables in the module.
247 /// getGlobalVariable - Look up the specified global variable in the module
248 /// symbol table. If it does not exist, return null. The type argument
249 /// should be the underlying type of the global, i.e., it should not have
250 /// the top-level PointerType, which represents the address of the global.
251 /// If AllowLocal is set to true, this function will return types that
252 /// have an local. By default, these types are not returned.
254 GlobalVariable
*Module::getGlobalVariable(StringRef Name
,
255 bool AllowLocal
) const {
256 if (GlobalVariable
*Result
=
257 dyn_cast_or_null
<GlobalVariable
>(getNamedValue(Name
)))
258 if (AllowLocal
|| !Result
->hasLocalLinkage())
263 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
264 /// 1. If it does not exist, add a declaration of the global and return it.
265 /// 2. Else, the global exists but has the wrong type: return the function
266 /// with a constantexpr cast to the right type.
267 /// 3. Finally, if the existing global is the correct delclaration, return the
269 Constant
*Module::getOrInsertGlobal(StringRef Name
, Type
*Ty
) {
270 // See if we have a definition for the specified global already.
271 GlobalVariable
*GV
= dyn_cast_or_null
<GlobalVariable
>(getNamedValue(Name
));
274 GlobalVariable
*New
=
275 new GlobalVariable(*this, Ty
, false, GlobalVariable::ExternalLinkage
,
277 return New
; // Return the new declaration.
280 // If the variable exists but has the wrong type, return a bitcast to the
282 if (GV
->getType() != PointerType::getUnqual(Ty
))
283 return ConstantExpr::getBitCast(GV
, PointerType::getUnqual(Ty
));
285 // Otherwise, we just found the existing function or a prototype.
289 //===----------------------------------------------------------------------===//
290 // Methods for easy access to the global variables in the module.
293 // getNamedAlias - Look up the specified global in the module symbol table.
294 // If it does not exist, return null.
296 GlobalAlias
*Module::getNamedAlias(StringRef Name
) const {
297 return dyn_cast_or_null
<GlobalAlias
>(getNamedValue(Name
));
300 /// getNamedMetadata - Return the first NamedMDNode in the module with the
301 /// specified name. This method returns null if a NamedMDNode with the
302 /// specified name is not found.
303 NamedMDNode
*Module::getNamedMetadata(const Twine
&Name
) const {
304 SmallString
<256> NameData
;
305 StringRef NameRef
= Name
.toStringRef(NameData
);
306 return static_cast<StringMap
<NamedMDNode
*> *>(NamedMDSymTab
)->lookup(NameRef
);
309 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
310 /// with the specified name. This method returns a new NamedMDNode if a
311 /// NamedMDNode with the specified name is not found.
312 NamedMDNode
*Module::getOrInsertNamedMetadata(StringRef Name
) {
314 (*static_cast<StringMap
<NamedMDNode
*> *>(NamedMDSymTab
))[Name
];
316 NMD
= new NamedMDNode(Name
);
317 NMD
->setParent(this);
318 NamedMDList
.push_back(NMD
);
323 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
325 void Module::eraseNamedMetadata(NamedMDNode
*NMD
) {
326 static_cast<StringMap
<NamedMDNode
*> *>(NamedMDSymTab
)->erase(NMD
->getName());
327 NamedMDList
.erase(NMD
);
330 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
332 getModuleFlagsMetadata(SmallVectorImpl
<ModuleFlagEntry
> &Flags
) const {
333 const NamedMDNode
*ModFlags
= getModuleFlagsMetadata();
334 if (!ModFlags
) return;
336 for (unsigned i
= 0, e
= ModFlags
->getNumOperands(); i
!= e
; ++i
) {
337 MDNode
*Flag
= ModFlags
->getOperand(i
);
338 ConstantInt
*Behavior
= cast
<ConstantInt
>(Flag
->getOperand(0));
339 MDString
*Key
= cast
<MDString
>(Flag
->getOperand(1));
340 Value
*Val
= Flag
->getOperand(2);
341 Flags
.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior
->getZExtValue()),
346 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
347 /// represents module-level flags. This method returns null if there are no
348 /// module-level flags.
349 NamedMDNode
*Module::getModuleFlagsMetadata() const {
350 return getNamedMetadata("llvm.module.flags");
353 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
354 /// represents module-level flags. If module-level flags aren't found, it
355 /// creates the named metadata that contains them.
356 NamedMDNode
*Module::getOrInsertModuleFlagsMetadata() {
357 return getOrInsertNamedMetadata("llvm.module.flags");
360 /// addModuleFlag - Add a module-level flag to the module-level flags
361 /// metadata. It will create the module-level flags named metadata if it doesn't
363 void Module::addModuleFlag(ModFlagBehavior Behavior
, StringRef Key
,
365 Type
*Int32Ty
= Type::getInt32Ty(Context
);
367 ConstantInt::get(Int32Ty
, Behavior
), MDString::get(Context
, Key
), Val
369 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context
, Ops
));
371 void Module::addModuleFlag(ModFlagBehavior Behavior
, StringRef Key
,
373 Type
*Int32Ty
= Type::getInt32Ty(Context
);
374 addModuleFlag(Behavior
, Key
, ConstantInt::get(Int32Ty
, Val
));
376 void Module::addModuleFlag(MDNode
*Node
) {
377 assert(Node
->getNumOperands() == 3 &&
378 "Invalid number of operands for module flag!");
379 assert(isa
<ConstantInt
>(Node
->getOperand(0)) &&
380 isa
<MDString
>(Node
->getOperand(1)) &&
381 "Invalid operand types for module flag!");
382 getOrInsertModuleFlagsMetadata()->addOperand(Node
);
385 //===----------------------------------------------------------------------===//
386 // Methods to control the materialization of GlobalValues in the Module.
388 void Module::setMaterializer(GVMaterializer
*GVM
) {
389 assert(!Materializer
&&
390 "Module already has a GVMaterializer. Call MaterializeAllPermanently"
391 " to clear it out before setting another one.");
392 Materializer
.reset(GVM
);
395 bool Module::isMaterializable(const GlobalValue
*GV
) const {
397 return Materializer
->isMaterializable(GV
);
401 bool Module::isDematerializable(const GlobalValue
*GV
) const {
403 return Materializer
->isDematerializable(GV
);
407 bool Module::Materialize(GlobalValue
*GV
, std::string
*ErrInfo
) {
409 return Materializer
->Materialize(GV
, ErrInfo
);
413 void Module::Dematerialize(GlobalValue
*GV
) {
415 return Materializer
->Dematerialize(GV
);
418 bool Module::MaterializeAll(std::string
*ErrInfo
) {
421 return Materializer
->MaterializeModule(this, ErrInfo
);
424 bool Module::MaterializeAllPermanently(std::string
*ErrInfo
) {
425 if (MaterializeAll(ErrInfo
))
427 Materializer
.reset();
431 //===----------------------------------------------------------------------===//
432 // Other module related stuff.
436 // dropAllReferences() - This function causes all the subelements to "let go"
437 // of all references that they are maintaining. This allows one to 'delete' a
438 // whole module at a time, even though there may be circular references... first
439 // all references are dropped, and all use counts go to zero. Then everything
440 // is deleted for real. Note that no operations are valid on an object that
441 // has "dropped all references", except operator delete.
443 void Module::dropAllReferences() {
444 for(Module::iterator I
= begin(), E
= end(); I
!= E
; ++I
)
445 I
->dropAllReferences();
447 for(Module::global_iterator I
= global_begin(), E
= global_end(); I
!= E
; ++I
)
448 I
->dropAllReferences();
450 for(Module::alias_iterator I
= alias_begin(), E
= alias_end(); I
!= E
; ++I
)
451 I
->dropAllReferences();
454 void Module::addLibrary(StringRef Lib
) {
455 for (Module::lib_iterator I
= lib_begin(), E
= lib_end(); I
!= E
; ++I
)
458 LibraryList
.push_back(Lib
);
461 void Module::removeLibrary(StringRef Lib
) {
462 LibraryListType::iterator I
= LibraryList
.begin();
463 LibraryListType::iterator E
= LibraryList
.end();
466 LibraryList
.erase(I
);