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/LLVMContext.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/LeakDetector.h"
22 #include "SymbolTableListTraitsImpl.h"
23 #include "llvm/TypeSymbolTable.h"
29 //===----------------------------------------------------------------------===//
30 // Methods to implement the globals and functions lists.
33 GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
34 GlobalVariable *Ret = new GlobalVariable(Type::getInt32Ty(getGlobalContext()),
35 false, GlobalValue::ExternalLinkage);
36 // This should not be garbage monitored.
37 LeakDetector::removeGarbageObject(Ret);
40 GlobalAlias *ilist_traits<GlobalAlias>::createSentinel() {
41 GlobalAlias *Ret = new GlobalAlias(Type::getInt32Ty(getGlobalContext()),
42 GlobalValue::ExternalLinkage);
43 // This should not be garbage monitored.
44 LeakDetector::removeGarbageObject(Ret);
48 // Explicit instantiations of SymbolTableListTraits since some of the methods
49 // are not in the public header file.
50 template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
51 template class llvm::SymbolTableListTraits<Function, Module>;
52 template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
54 //===----------------------------------------------------------------------===//
55 // Primitive Module methods.
58 Module::Module(StringRef MID, LLVMContext& C)
59 : Context(C), ModuleID(MID), DataLayout("") {
60 ValSymTab = new ValueSymbolTable();
61 TypeSymTab = new TypeSymbolTable();
62 NamedMDSymTab = new MDSymbolTable();
77 /// Target endian information...
78 Module::Endianness Module::getEndianness() const {
79 StringRef temp = DataLayout;
80 Module::Endianness ret = AnyEndianness;
82 while (!temp.empty()) {
83 StringRef token = DataLayout;
84 tie(token, temp) = getToken(DataLayout, "-");
86 if (token[0] == 'e') {
88 } else if (token[0] == 'E') {
96 /// Target Pointer Size information...
97 Module::PointerSize Module::getPointerSize() const {
98 StringRef temp = DataLayout;
99 Module::PointerSize ret = AnyPointerSize;
101 while (!temp.empty()) {
102 StringRef token, signalToken;
103 tie(token, temp) = getToken(temp, "-");
104 tie(signalToken, token) = getToken(token, ":");
106 if (signalToken[0] == 'p') {
108 getToken(token, ":").first.getAsInteger(10, size);
119 /// getNamedValue - Return the first global value in the module with
120 /// the specified name, of arbitrary type. This method returns null
121 /// if a global with the specified name is not found.
122 GlobalValue *Module::getNamedValue(StringRef Name) const {
123 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
126 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
127 /// This ID is uniqued across modules in the current LLVMContext.
128 unsigned Module::getMDKindID(StringRef Name) const {
129 return Context.getMDKindID(Name);
132 /// getMDKindNames - Populate client supplied SmallVector with the name for
133 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
134 /// so it is filled in as an empty string.
135 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
136 return Context.getMDKindNames(Result);
140 //===----------------------------------------------------------------------===//
141 // Methods for easy access to the functions in the module.
144 // getOrInsertFunction - Look up the specified function in the module symbol
145 // table. If it does not exist, add a prototype for the function and return
146 // it. This is nice because it allows most passes to get away with not handling
147 // the symbol table directly for this common task.
149 Constant *Module::getOrInsertFunction(StringRef Name,
150 const FunctionType *Ty,
151 AttrListPtr AttributeList) {
152 // See if we have a definition for the specified function already.
153 GlobalValue *F = getNamedValue(Name);
156 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
157 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
158 New->setAttributes(AttributeList);
159 FunctionList.push_back(New);
160 return New; // Return the new prototype.
163 // Okay, the function exists. Does it have externally visible linkage?
164 if (F->hasLocalLinkage()) {
165 // Clear the function's name.
167 // Retry, now there won't be a conflict.
168 Constant *NewF = getOrInsertFunction(Name, Ty);
173 // If the function exists but has the wrong type, return a bitcast to the
175 if (F->getType() != PointerType::getUnqual(Ty))
176 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
178 // Otherwise, we just found the existing function or a prototype.
182 Constant *Module::getOrInsertTargetIntrinsic(StringRef Name,
183 const FunctionType *Ty,
184 AttrListPtr AttributeList) {
185 // See if we have a definition for the specified function already.
186 GlobalValue *F = getNamedValue(Name);
189 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
190 New->setAttributes(AttributeList);
191 FunctionList.push_back(New);
192 return New; // Return the new prototype.
195 // Otherwise, we just found the existing function or a prototype.
199 Constant *Module::getOrInsertFunction(StringRef Name,
200 const FunctionType *Ty) {
201 AttrListPtr AttributeList = AttrListPtr::get((AttributeWithIndex *)0, 0);
202 return getOrInsertFunction(Name, Ty, AttributeList);
205 // getOrInsertFunction - Look up the specified function in the module symbol
206 // table. If it does not exist, add a prototype for the function and return it.
207 // This version of the method takes a null terminated list of function
208 // arguments, which makes it easier for clients to use.
210 Constant *Module::getOrInsertFunction(StringRef Name,
211 AttrListPtr AttributeList,
212 const Type *RetTy, ...) {
214 va_start(Args, RetTy);
216 // Build the list of argument types...
217 std::vector<const Type*> ArgTys;
218 while (const Type *ArgTy = va_arg(Args, const Type*))
219 ArgTys.push_back(ArgTy);
223 // Build the function type and chain to the other getOrInsertFunction...
224 return getOrInsertFunction(Name,
225 FunctionType::get(RetTy, ArgTys, false),
229 Constant *Module::getOrInsertFunction(StringRef Name,
230 const Type *RetTy, ...) {
232 va_start(Args, RetTy);
234 // Build the list of argument types...
235 std::vector<const Type*> ArgTys;
236 while (const Type *ArgTy = va_arg(Args, const Type*))
237 ArgTys.push_back(ArgTy);
241 // Build the function type and chain to the other getOrInsertFunction...
242 return getOrInsertFunction(Name,
243 FunctionType::get(RetTy, ArgTys, false),
244 AttrListPtr::get((AttributeWithIndex *)0, 0));
247 // getFunction - Look up the specified function in the module symbol table.
248 // If it does not exist, return null.
250 Function *Module::getFunction(StringRef Name) const {
251 return dyn_cast_or_null<Function>(getNamedValue(Name));
254 //===----------------------------------------------------------------------===//
255 // Methods for easy access to the global variables in the module.
258 /// getGlobalVariable - Look up the specified global variable in the module
259 /// symbol table. If it does not exist, return null. The type argument
260 /// should be the underlying type of the global, i.e., it should not have
261 /// the top-level PointerType, which represents the address of the global.
262 /// If AllowLocal is set to true, this function will return types that
263 /// have an local. By default, these types are not returned.
265 GlobalVariable *Module::getGlobalVariable(StringRef Name,
266 bool AllowLocal) const {
267 if (GlobalVariable *Result =
268 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
269 if (AllowLocal || !Result->hasLocalLinkage())
274 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
275 /// 1. If it does not exist, add a declaration of the global and return it.
276 /// 2. Else, the global exists but has the wrong type: return the function
277 /// with a constantexpr cast to the right type.
278 /// 3. Finally, if the existing global is the correct delclaration, return the
280 Constant *Module::getOrInsertGlobal(StringRef Name, const Type *Ty) {
281 // See if we have a definition for the specified global already.
282 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
285 GlobalVariable *New =
286 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
288 return New; // Return the new declaration.
291 // If the variable exists but has the wrong type, return a bitcast to the
293 if (GV->getType() != PointerType::getUnqual(Ty))
294 return ConstantExpr::getBitCast(GV, PointerType::getUnqual(Ty));
296 // Otherwise, we just found the existing function or a prototype.
300 //===----------------------------------------------------------------------===//
301 // Methods for easy access to the global variables in the module.
304 // getNamedAlias - Look up the specified global in the module symbol table.
305 // If it does not exist, return null.
307 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
308 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
311 /// getNamedMetadata - Return the first NamedMDNode in the module with the
312 /// specified name. This method returns null if a NamedMDNode with the
313 //// specified name is not found.
314 NamedMDNode *Module::getNamedMetadata(StringRef Name) const {
315 return NamedMDSymTab->lookup(Name);
318 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
319 /// with the specified name. This method returns a new NamedMDNode if a
320 /// NamedMDNode with the specified name is not found.
321 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
322 NamedMDNode *NMD = NamedMDSymTab->lookup(Name);
324 NMD = NamedMDNode::Create(getContext(), Name, NULL, 0, this);
328 //===----------------------------------------------------------------------===//
329 // Methods for easy access to the types in the module.
333 // addTypeName - Insert an entry in the symbol table mapping Str to Type. If
334 // there is already an entry for this name, true is returned and the symbol
335 // table is not modified.
337 bool Module::addTypeName(StringRef Name, const Type *Ty) {
338 TypeSymbolTable &ST = getTypeSymbolTable();
340 if (ST.lookup(Name)) return true; // Already in symtab...
342 // Not in symbol table? Set the name with the Symtab as an argument so the
343 // type knows what to update...
349 /// getTypeByName - Return the type with the specified name in this module, or
350 /// null if there is none by that name.
351 const Type *Module::getTypeByName(StringRef Name) const {
352 const TypeSymbolTable &ST = getTypeSymbolTable();
353 return cast_or_null<Type>(ST.lookup(Name));
356 // getTypeName - If there is at least one entry in the symbol table for the
357 // specified type, return it.
359 std::string Module::getTypeName(const Type *Ty) const {
360 const TypeSymbolTable &ST = getTypeSymbolTable();
362 TypeSymbolTable::const_iterator TI = ST.begin();
363 TypeSymbolTable::const_iterator TE = ST.end();
364 if ( TI == TE ) return ""; // No names for types
366 while (TI != TE && TI->second != Ty)
369 if (TI != TE) // Must have found an entry!
371 return ""; // Must not have found anything...
374 //===----------------------------------------------------------------------===//
375 // Other module related stuff.
379 // dropAllReferences() - This function causes all the subelementss to "let go"
380 // of all references that they are maintaining. This allows one to 'delete' a
381 // whole module at a time, even though there may be circular references... first
382 // all references are dropped, and all use counts go to zero. Then everything
383 // is deleted for real. Note that no operations are valid on an object that
384 // has "dropped all references", except operator delete.
386 void Module::dropAllReferences() {
387 for(Module::iterator I = begin(), E = end(); I != E; ++I)
388 I->dropAllReferences();
390 for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
391 I->dropAllReferences();
393 for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
394 I->dropAllReferences();
397 void Module::addLibrary(StringRef Lib) {
398 for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
401 LibraryList.push_back(Lib);
404 void Module::removeLibrary(StringRef Lib) {
405 LibraryListType::iterator I = LibraryList.begin();
406 LibraryListType::iterator E = LibraryList.end();
409 LibraryList.erase(I);