Module.cpp 17 KB

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