Module.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. //===-- Module.cpp - Implement the Module class ---------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Module class for the IR library.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/IR/Module.h"
  14. #include "SymbolTableListTraitsImpl.h"
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallString.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/GVMaterializer.h"
  20. #include "llvm/IR/Constants.h"
  21. #include "llvm/IR/DerivedTypes.h"
  22. #include "llvm/IR/InstrTypes.h"
  23. #include "llvm/IR/LLVMContext.h"
  24. #include "llvm/Support/LeakDetector.h"
  25. #include <algorithm>
  26. #include <cstdarg>
  27. #include <cstdlib>
  28. using namespace llvm;
  29. //===----------------------------------------------------------------------===//
  30. // Methods to implement the globals and functions lists.
  31. //
  32. // Explicit instantiations of SymbolTableListTraits since some of the methods
  33. // are not in the public header file.
  34. template class llvm::SymbolTableListTraits<Function, Module>;
  35. template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
  36. template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
  37. //===----------------------------------------------------------------------===//
  38. // Primitive Module methods.
  39. //
  40. Module::Module(StringRef MID, LLVMContext& C)
  41. : Context(C), Materializer(NULL), ModuleID(MID) {
  42. ValSymTab = new ValueSymbolTable();
  43. NamedMDSymTab = new StringMap<NamedMDNode *>();
  44. Context.addModule(this);
  45. }
  46. Module::~Module() {
  47. Context.removeModule(this);
  48. dropAllReferences();
  49. GlobalList.clear();
  50. FunctionList.clear();
  51. AliasList.clear();
  52. NamedMDList.clear();
  53. delete ValSymTab;
  54. delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
  55. }
  56. /// getNamedValue - Return the first global value in the module with
  57. /// the specified name, of arbitrary type. This method returns null
  58. /// if a global with the specified name is not found.
  59. GlobalValue *Module::getNamedValue(StringRef Name) const {
  60. return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
  61. }
  62. /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
  63. /// This ID is uniqued across modules in the current LLVMContext.
  64. unsigned Module::getMDKindID(StringRef Name) const {
  65. return Context.getMDKindID(Name);
  66. }
  67. /// getMDKindNames - Populate client supplied SmallVector with the name for
  68. /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
  69. /// so it is filled in as an empty string.
  70. void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
  71. return Context.getMDKindNames(Result);
  72. }
  73. //===----------------------------------------------------------------------===//
  74. // Methods for easy access to the functions in the module.
  75. //
  76. // getOrInsertFunction - Look up the specified function in the module symbol
  77. // table. If it does not exist, add a prototype for the function and return
  78. // it. This is nice because it allows most passes to get away with not handling
  79. // the symbol table directly for this common task.
  80. //
  81. Constant *Module::getOrInsertFunction(StringRef Name,
  82. FunctionType *Ty,
  83. AttributeSet AttributeList) {
  84. // See if we have a definition for the specified function already.
  85. GlobalValue *F = getNamedValue(Name);
  86. if (F == 0) {
  87. // Nope, add it
  88. Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
  89. if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
  90. New->setAttributes(AttributeList);
  91. FunctionList.push_back(New);
  92. return New; // Return the new prototype.
  93. }
  94. // Okay, the function exists. Does it have externally visible linkage?
  95. if (F->hasLocalLinkage()) {
  96. // Clear the function's name.
  97. F->setName("");
  98. // Retry, now there won't be a conflict.
  99. Constant *NewF = getOrInsertFunction(Name, Ty);
  100. F->setName(Name);
  101. return NewF;
  102. }
  103. // If the function exists but has the wrong type, return a bitcast to the
  104. // right type.
  105. if (F->getType() != PointerType::getUnqual(Ty))
  106. return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
  107. // Otherwise, we just found the existing function or a prototype.
  108. return F;
  109. }
  110. Constant *Module::getOrInsertFunction(StringRef Name,
  111. FunctionType *Ty) {
  112. return getOrInsertFunction(Name, Ty, AttributeSet());
  113. }
  114. // getOrInsertFunction - Look up the specified function in the module symbol
  115. // table. If it does not exist, add a prototype for the function and return it.
  116. // This version of the method takes a null terminated list of function
  117. // arguments, which makes it easier for clients to use.
  118. //
  119. Constant *Module::getOrInsertFunction(StringRef Name,
  120. AttributeSet AttributeList,
  121. Type *RetTy, ...) {
  122. va_list Args;
  123. va_start(Args, RetTy);
  124. // Build the list of argument types...
  125. std::vector<Type*> ArgTys;
  126. while (Type *ArgTy = va_arg(Args, Type*))
  127. ArgTys.push_back(ArgTy);
  128. va_end(Args);
  129. // Build the function type and chain to the other getOrInsertFunction...
  130. return getOrInsertFunction(Name,
  131. FunctionType::get(RetTy, ArgTys, false),
  132. AttributeList);
  133. }
  134. Constant *Module::getOrInsertFunction(StringRef Name,
  135. Type *RetTy, ...) {
  136. va_list Args;
  137. va_start(Args, RetTy);
  138. // Build the list of argument types...
  139. std::vector<Type*> ArgTys;
  140. while (Type *ArgTy = va_arg(Args, Type*))
  141. ArgTys.push_back(ArgTy);
  142. va_end(Args);
  143. // Build the function type and chain to the other getOrInsertFunction...
  144. return getOrInsertFunction(Name,
  145. FunctionType::get(RetTy, ArgTys, false),
  146. AttributeSet());
  147. }
  148. // getFunction - Look up the specified function in the module symbol table.
  149. // If it does not exist, return null.
  150. //
  151. Function *Module::getFunction(StringRef Name) const {
  152. return dyn_cast_or_null<Function>(getNamedValue(Name));
  153. }
  154. //===----------------------------------------------------------------------===//
  155. // Methods for easy access to the global variables in the module.
  156. //
  157. /// getGlobalVariable - Look up the specified global variable in the module
  158. /// symbol table. If it does not exist, return null. The type argument
  159. /// should be the underlying type of the global, i.e., it should not have
  160. /// the top-level PointerType, which represents the address of the global.
  161. /// If AllowLocal is set to true, this function will return types that
  162. /// have an local. By default, these types are not returned.
  163. ///
  164. GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
  165. if (GlobalVariable *Result =
  166. dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
  167. if (AllowLocal || !Result->hasLocalLinkage())
  168. return Result;
  169. return 0;
  170. }
  171. /// getOrInsertGlobal - Look up the specified global in the module symbol table.
  172. /// 1. If it does not exist, add a declaration of the global and return it.
  173. /// 2. Else, the global exists but has the wrong type: return the function
  174. /// with a constantexpr cast to the right type.
  175. /// 3. Finally, if the existing global is the correct declaration, return the
  176. /// existing global.
  177. Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
  178. // See if we have a definition for the specified global already.
  179. GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
  180. if (GV == 0) {
  181. // Nope, add it
  182. GlobalVariable *New =
  183. new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
  184. 0, Name);
  185. return New; // Return the new declaration.
  186. }
  187. // If the variable exists but has the wrong type, return a bitcast to the
  188. // right type.
  189. Type *GVTy = GV->getType();
  190. PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
  191. if (GVTy != PTy)
  192. return ConstantExpr::getBitCast(GV, PTy);
  193. // Otherwise, we just found the existing function or a prototype.
  194. return GV;
  195. }
  196. //===----------------------------------------------------------------------===//
  197. // Methods for easy access to the global variables in the module.
  198. //
  199. // getNamedAlias - Look up the specified global in the module symbol table.
  200. // If it does not exist, return null.
  201. //
  202. GlobalAlias *Module::getNamedAlias(StringRef Name) const {
  203. return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
  204. }
  205. /// getNamedMetadata - Return the first NamedMDNode in the module with the
  206. /// specified name. This method returns null if a NamedMDNode with the
  207. /// specified name is not found.
  208. NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
  209. SmallString<256> NameData;
  210. StringRef NameRef = Name.toStringRef(NameData);
  211. return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
  212. }
  213. /// getOrInsertNamedMetadata - Return the first named MDNode in the module
  214. /// with the specified name. This method returns a new NamedMDNode if a
  215. /// NamedMDNode with the specified name is not found.
  216. NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
  217. NamedMDNode *&NMD =
  218. (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
  219. if (!NMD) {
  220. NMD = new NamedMDNode(Name);
  221. NMD->setParent(this);
  222. NamedMDList.push_back(NMD);
  223. }
  224. return NMD;
  225. }
  226. /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
  227. /// delete it.
  228. void Module::eraseNamedMetadata(NamedMDNode *NMD) {
  229. static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
  230. NamedMDList.erase(NMD);
  231. }
  232. /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
  233. void Module::
  234. getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
  235. const NamedMDNode *ModFlags = getModuleFlagsMetadata();
  236. if (!ModFlags) return;
  237. for (unsigned i = 0, e = ModFlags->getNumOperands(); i != e; ++i) {
  238. MDNode *Flag = ModFlags->getOperand(i);
  239. if (Flag->getNumOperands() >= 3 && isa<ConstantInt>(Flag->getOperand(0)) &&
  240. isa<MDString>(Flag->getOperand(1))) {
  241. // Check the operands of the MDNode before accessing the operands.
  242. // The verifier will actually catch these failures.
  243. ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0));
  244. MDString *Key = cast<MDString>(Flag->getOperand(1));
  245. Value *Val = Flag->getOperand(2);
  246. Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue()),
  247. Key, Val));
  248. }
  249. }
  250. }
  251. /// Return the corresponding value if Key appears in module flags, otherwise
  252. /// return null.
  253. Value *Module::getModuleFlag(StringRef Key) const {
  254. SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
  255. getModuleFlagsMetadata(ModuleFlags);
  256. for (unsigned I = 0, E = ModuleFlags.size(); I < E; ++I) {
  257. const ModuleFlagEntry &MFE = ModuleFlags[I];
  258. if (Key == MFE.Key->getString())
  259. return MFE.Val;
  260. }
  261. return 0;
  262. }
  263. /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
  264. /// represents module-level flags. This method returns null if there are no
  265. /// module-level flags.
  266. NamedMDNode *Module::getModuleFlagsMetadata() const {
  267. return getNamedMetadata("llvm.module.flags");
  268. }
  269. /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
  270. /// represents module-level flags. If module-level flags aren't found, it
  271. /// creates the named metadata that contains them.
  272. NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
  273. return getOrInsertNamedMetadata("llvm.module.flags");
  274. }
  275. /// addModuleFlag - Add a module-level flag to the module-level flags
  276. /// metadata. It will create the module-level flags named metadata if it doesn't
  277. /// already exist.
  278. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  279. Value *Val) {
  280. Type *Int32Ty = Type::getInt32Ty(Context);
  281. Value *Ops[3] = {
  282. ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
  283. };
  284. getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
  285. }
  286. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  287. uint32_t Val) {
  288. Type *Int32Ty = Type::getInt32Ty(Context);
  289. addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
  290. }
  291. void Module::addModuleFlag(MDNode *Node) {
  292. assert(Node->getNumOperands() == 3 &&
  293. "Invalid number of operands for module flag!");
  294. assert(isa<ConstantInt>(Node->getOperand(0)) &&
  295. isa<MDString>(Node->getOperand(1)) &&
  296. "Invalid operand types for module flag!");
  297. getOrInsertModuleFlagsMetadata()->addOperand(Node);
  298. }
  299. //===----------------------------------------------------------------------===//
  300. // Methods to control the materialization of GlobalValues in the Module.
  301. //
  302. void Module::setMaterializer(GVMaterializer *GVM) {
  303. assert(!Materializer &&
  304. "Module already has a GVMaterializer. Call MaterializeAllPermanently"
  305. " to clear it out before setting another one.");
  306. Materializer.reset(GVM);
  307. }
  308. bool Module::isMaterializable(const GlobalValue *GV) const {
  309. if (Materializer)
  310. return Materializer->isMaterializable(GV);
  311. return false;
  312. }
  313. bool Module::isDematerializable(const GlobalValue *GV) const {
  314. if (Materializer)
  315. return Materializer->isDematerializable(GV);
  316. return false;
  317. }
  318. bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
  319. if (!Materializer)
  320. return false;
  321. error_code EC = Materializer->Materialize(GV);
  322. if (!EC)
  323. return false;
  324. if (ErrInfo)
  325. *ErrInfo = EC.message();
  326. return true;
  327. }
  328. void Module::Dematerialize(GlobalValue *GV) {
  329. if (Materializer)
  330. return Materializer->Dematerialize(GV);
  331. }
  332. error_code Module::materializeAll() {
  333. if (!Materializer)
  334. return error_code::success();
  335. return Materializer->MaterializeModule(this);
  336. }
  337. error_code Module::materializeAllPermanently() {
  338. if (error_code EC = materializeAll())
  339. return EC;
  340. Materializer.reset();
  341. return error_code::success();
  342. }
  343. //===----------------------------------------------------------------------===//
  344. // Other module related stuff.
  345. //
  346. // dropAllReferences() - This function causes all the subelements to "let go"
  347. // of all references that they are maintaining. This allows one to 'delete' a
  348. // whole module at a time, even though there may be circular references... first
  349. // all references are dropped, and all use counts go to zero. Then everything
  350. // is deleted for real. Note that no operations are valid on an object that
  351. // has "dropped all references", except operator delete.
  352. //
  353. void Module::dropAllReferences() {
  354. for(Module::iterator I = begin(), E = end(); I != E; ++I)
  355. I->dropAllReferences();
  356. for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
  357. I->dropAllReferences();
  358. for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
  359. I->dropAllReferences();
  360. }