Module.cpp 16 KB

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