Module.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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/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/Constants.h"
  20. #include "llvm/DerivedTypes.h"
  21. #include "llvm/GVMaterializer.h"
  22. #include "llvm/InstrTypes.h"
  23. #include "llvm/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. /// Target endian information.
  57. Module::Endianness Module::getEndianness() const {
  58. StringRef temp = DataLayout;
  59. Module::Endianness ret = AnyEndianness;
  60. while (!temp.empty()) {
  61. std::pair<StringRef, StringRef> P = getToken(temp, "-");
  62. StringRef token = P.first;
  63. temp = P.second;
  64. if (token[0] == 'e') {
  65. ret = LittleEndian;
  66. } else if (token[0] == 'E') {
  67. ret = BigEndian;
  68. }
  69. }
  70. return ret;
  71. }
  72. /// Target Pointer Size information.
  73. Module::PointerSize Module::getPointerSize() const {
  74. StringRef temp = DataLayout;
  75. Module::PointerSize ret = AnyPointerSize;
  76. while (!temp.empty()) {
  77. std::pair<StringRef, StringRef> TmpP = getToken(temp, "-");
  78. temp = TmpP.second;
  79. TmpP = getToken(TmpP.first, ":");
  80. StringRef token = TmpP.second, signalToken = TmpP.first;
  81. if (signalToken[0] == 'p') {
  82. int size = 0;
  83. getToken(token, ":").first.getAsInteger(10, size);
  84. if (size == 32)
  85. ret = Pointer32;
  86. else if (size == 64)
  87. ret = Pointer64;
  88. }
  89. }
  90. return ret;
  91. }
  92. /// getNamedValue - Return the first global value in the module with
  93. /// the specified name, of arbitrary type. This method returns null
  94. /// if a global with the specified name is not found.
  95. GlobalValue *Module::getNamedValue(StringRef Name) const {
  96. return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
  97. }
  98. /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
  99. /// This ID is uniqued across modules in the current LLVMContext.
  100. unsigned Module::getMDKindID(StringRef Name) const {
  101. return Context.getMDKindID(Name);
  102. }
  103. /// getMDKindNames - Populate client supplied SmallVector with the name for
  104. /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
  105. /// so it is filled in as an empty string.
  106. void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
  107. return Context.getMDKindNames(Result);
  108. }
  109. //===----------------------------------------------------------------------===//
  110. // Methods for easy access to the functions in the module.
  111. //
  112. // getOrInsertFunction - Look up the specified function in the module symbol
  113. // table. If it does not exist, add a prototype for the function and return
  114. // it. This is nice because it allows most passes to get away with not handling
  115. // the symbol table directly for this common task.
  116. //
  117. Constant *Module::getOrInsertFunction(StringRef Name,
  118. FunctionType *Ty,
  119. AttributeSet AttributeList) {
  120. // See if we have a definition for the specified function already.
  121. GlobalValue *F = getNamedValue(Name);
  122. if (F == 0) {
  123. // Nope, add it
  124. Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
  125. if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
  126. New->setAttributes(AttributeList);
  127. FunctionList.push_back(New);
  128. return New; // Return the new prototype.
  129. }
  130. // Okay, the function exists. Does it have externally visible linkage?
  131. if (F->hasLocalLinkage()) {
  132. // Clear the function's name.
  133. F->setName("");
  134. // Retry, now there won't be a conflict.
  135. Constant *NewF = getOrInsertFunction(Name, Ty);
  136. F->setName(Name);
  137. return NewF;
  138. }
  139. // If the function exists but has the wrong type, return a bitcast to the
  140. // right type.
  141. if (F->getType() != PointerType::getUnqual(Ty))
  142. return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
  143. // Otherwise, we just found the existing function or a prototype.
  144. return F;
  145. }
  146. Constant *Module::getOrInsertTargetIntrinsic(StringRef Name,
  147. FunctionType *Ty,
  148. AttributeSet AttributeList) {
  149. // See if we have a definition for the specified function already.
  150. GlobalValue *F = getNamedValue(Name);
  151. if (F == 0) {
  152. // Nope, add it
  153. Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
  154. New->setAttributes(AttributeList);
  155. FunctionList.push_back(New);
  156. return New; // Return the new prototype.
  157. }
  158. // Otherwise, we just found the existing function or a prototype.
  159. return F;
  160. }
  161. Constant *Module::getOrInsertFunction(StringRef Name,
  162. FunctionType *Ty) {
  163. return getOrInsertFunction(Name, Ty, AttributeSet());
  164. }
  165. // getOrInsertFunction - Look up the specified function in the module symbol
  166. // table. If it does not exist, add a prototype for the function and return it.
  167. // This version of the method takes a null terminated list of function
  168. // arguments, which makes it easier for clients to use.
  169. //
  170. Constant *Module::getOrInsertFunction(StringRef Name,
  171. AttributeSet AttributeList,
  172. Type *RetTy, ...) {
  173. va_list Args;
  174. 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);
  179. va_end(Args);
  180. // Build the function type and chain to the other getOrInsertFunction...
  181. return getOrInsertFunction(Name,
  182. FunctionType::get(RetTy, ArgTys, false),
  183. AttributeList);
  184. }
  185. Constant *Module::getOrInsertFunction(StringRef Name,
  186. Type *RetTy, ...) {
  187. va_list Args;
  188. va_start(Args, RetTy);
  189. // Build the list of argument types...
  190. std::vector<Type*> ArgTys;
  191. while (Type *ArgTy = va_arg(Args, Type*))
  192. ArgTys.push_back(ArgTy);
  193. va_end(Args);
  194. // Build the function type and chain to the other getOrInsertFunction...
  195. return getOrInsertFunction(Name,
  196. FunctionType::get(RetTy, ArgTys, false),
  197. AttributeSet());
  198. }
  199. // getFunction - Look up the specified function in the module symbol table.
  200. // If it does not exist, return null.
  201. //
  202. Function *Module::getFunction(StringRef Name) const {
  203. return dyn_cast_or_null<Function>(getNamedValue(Name));
  204. }
  205. //===----------------------------------------------------------------------===//
  206. // Methods for easy access to the global variables in the module.
  207. //
  208. /// getGlobalVariable - Look up the specified global variable in the module
  209. /// symbol table. If it does not exist, return null. The type argument
  210. /// should be the underlying type of the global, i.e., it should not have
  211. /// the top-level PointerType, which represents the address of the global.
  212. /// If AllowLocal is set to true, this function will return types that
  213. /// have an local. By default, these types are not returned.
  214. ///
  215. GlobalVariable *Module::getGlobalVariable(StringRef Name,
  216. bool AllowLocal) const {
  217. if (GlobalVariable *Result =
  218. dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
  219. if (AllowLocal || !Result->hasLocalLinkage())
  220. return Result;
  221. return 0;
  222. }
  223. /// getOrInsertGlobal - Look up the specified global in the module symbol table.
  224. /// 1. If it does not exist, add a declaration of the global and return it.
  225. /// 2. Else, the global exists but has the wrong type: return the function
  226. /// with a constantexpr cast to the right type.
  227. /// 3. Finally, if the existing global is the correct delclaration, return the
  228. /// existing global.
  229. Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
  230. // See if we have a definition for the specified global already.
  231. GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
  232. if (GV == 0) {
  233. // Nope, add it
  234. GlobalVariable *New =
  235. new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
  236. 0, Name);
  237. return New; // Return the new declaration.
  238. }
  239. // If the variable exists but has the wrong type, return a bitcast to the
  240. // right type.
  241. if (GV->getType() != PointerType::getUnqual(Ty))
  242. return ConstantExpr::getBitCast(GV, PointerType::getUnqual(Ty));
  243. // Otherwise, we just found the existing function or a prototype.
  244. return GV;
  245. }
  246. //===----------------------------------------------------------------------===//
  247. // Methods for easy access to the global variables in the module.
  248. //
  249. // getNamedAlias - Look up the specified global in the module symbol table.
  250. // If it does not exist, return null.
  251. //
  252. GlobalAlias *Module::getNamedAlias(StringRef Name) const {
  253. return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
  254. }
  255. /// getNamedMetadata - Return the first NamedMDNode in the module with the
  256. /// specified name. This method returns null if a NamedMDNode with the
  257. /// specified name is not found.
  258. NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
  259. SmallString<256> NameData;
  260. StringRef NameRef = Name.toStringRef(NameData);
  261. return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
  262. }
  263. /// getOrInsertNamedMetadata - Return the first named MDNode in the module
  264. /// with the specified name. This method returns a new NamedMDNode if a
  265. /// NamedMDNode with the specified name is not found.
  266. NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
  267. NamedMDNode *&NMD =
  268. (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
  269. if (!NMD) {
  270. NMD = new NamedMDNode(Name);
  271. NMD->setParent(this);
  272. NamedMDList.push_back(NMD);
  273. }
  274. return NMD;
  275. }
  276. /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
  277. /// delete it.
  278. void Module::eraseNamedMetadata(NamedMDNode *NMD) {
  279. static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
  280. NamedMDList.erase(NMD);
  281. }
  282. /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
  283. void Module::
  284. getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
  285. const NamedMDNode *ModFlags = getModuleFlagsMetadata();
  286. if (!ModFlags) return;
  287. for (unsigned i = 0, e = ModFlags->getNumOperands(); i != e; ++i) {
  288. MDNode *Flag = ModFlags->getOperand(i);
  289. ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0));
  290. MDString *Key = cast<MDString>(Flag->getOperand(1));
  291. Value *Val = Flag->getOperand(2);
  292. Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue()),
  293. Key, Val));
  294. }
  295. }
  296. /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
  297. /// represents module-level flags. This method returns null if there are no
  298. /// module-level flags.
  299. NamedMDNode *Module::getModuleFlagsMetadata() const {
  300. return getNamedMetadata("llvm.module.flags");
  301. }
  302. /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
  303. /// represents module-level flags. If module-level flags aren't found, it
  304. /// creates the named metadata that contains them.
  305. NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
  306. return getOrInsertNamedMetadata("llvm.module.flags");
  307. }
  308. /// addModuleFlag - Add a module-level flag to the module-level flags
  309. /// metadata. It will create the module-level flags named metadata if it doesn't
  310. /// already exist.
  311. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  312. Value *Val) {
  313. Type *Int32Ty = Type::getInt32Ty(Context);
  314. Value *Ops[3] = {
  315. ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
  316. };
  317. getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
  318. }
  319. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  320. uint32_t Val) {
  321. Type *Int32Ty = Type::getInt32Ty(Context);
  322. addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
  323. }
  324. void Module::addModuleFlag(MDNode *Node) {
  325. assert(Node->getNumOperands() == 3 &&
  326. "Invalid number of operands for module flag!");
  327. assert(isa<ConstantInt>(Node->getOperand(0)) &&
  328. isa<MDString>(Node->getOperand(1)) &&
  329. "Invalid operand types for module flag!");
  330. getOrInsertModuleFlagsMetadata()->addOperand(Node);
  331. }
  332. //===----------------------------------------------------------------------===//
  333. // Methods to control the materialization of GlobalValues in the Module.
  334. //
  335. void Module::setMaterializer(GVMaterializer *GVM) {
  336. assert(!Materializer &&
  337. "Module already has a GVMaterializer. Call MaterializeAllPermanently"
  338. " to clear it out before setting another one.");
  339. Materializer.reset(GVM);
  340. }
  341. bool Module::isMaterializable(const GlobalValue *GV) const {
  342. if (Materializer)
  343. return Materializer->isMaterializable(GV);
  344. return false;
  345. }
  346. bool Module::isDematerializable(const GlobalValue *GV) const {
  347. if (Materializer)
  348. return Materializer->isDematerializable(GV);
  349. return false;
  350. }
  351. bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
  352. if (Materializer)
  353. return Materializer->Materialize(GV, ErrInfo);
  354. return false;
  355. }
  356. void Module::Dematerialize(GlobalValue *GV) {
  357. if (Materializer)
  358. return Materializer->Dematerialize(GV);
  359. }
  360. bool Module::MaterializeAll(std::string *ErrInfo) {
  361. if (!Materializer)
  362. return false;
  363. return Materializer->MaterializeModule(this, ErrInfo);
  364. }
  365. bool Module::MaterializeAllPermanently(std::string *ErrInfo) {
  366. if (MaterializeAll(ErrInfo))
  367. return true;
  368. Materializer.reset();
  369. return false;
  370. }
  371. //===----------------------------------------------------------------------===//
  372. // Other module related stuff.
  373. //
  374. // dropAllReferences() - This function causes all the subelements to "let go"
  375. // of all references that they are maintaining. This allows one to 'delete' a
  376. // whole module at a time, even though there may be circular references... first
  377. // all references are dropped, and all use counts go to zero. Then everything
  378. // is deleted for real. Note that no operations are valid on an object that
  379. // has "dropped all references", except operator delete.
  380. //
  381. void Module::dropAllReferences() {
  382. for(Module::iterator I = begin(), E = end(); I != E; ++I)
  383. I->dropAllReferences();
  384. for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
  385. I->dropAllReferences();
  386. for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
  387. I->dropAllReferences();
  388. }