Module.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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/TypeFinder.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), 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. }
  59. RandomNumberGenerator *Module::createRNG(const Pass* P) const {
  60. SmallString<32> Salt(P->getPassName());
  61. // This RNG is guaranteed to produce the same random stream only
  62. // when the Module ID and thus the input filename is the same. This
  63. // might be problematic if the input filename extension changes
  64. // (e.g. from .c to .bc or .ll).
  65. //
  66. // We could store this salt in NamedMetadata, but this would make
  67. // the parameter non-const. This would unfortunately make this
  68. // interface unusable by any Machine passes, since they only have a
  69. // const reference to their IR Module. Alternatively we can always
  70. // store salt metadata from the Module constructor.
  71. Salt += sys::path::filename(getModuleIdentifier());
  72. return new RandomNumberGenerator(Salt);
  73. }
  74. /// getNamedValue - Return the first global value in the module with
  75. /// the specified name, of arbitrary type. This method returns null
  76. /// if a global with the specified name is not found.
  77. GlobalValue *Module::getNamedValue(StringRef Name) const {
  78. return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
  79. }
  80. /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
  81. /// This ID is uniqued across modules in the current LLVMContext.
  82. unsigned Module::getMDKindID(StringRef Name) const {
  83. return Context.getMDKindID(Name);
  84. }
  85. /// getMDKindNames - Populate client supplied SmallVector with the name for
  86. /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
  87. /// so it is filled in as an empty string.
  88. void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
  89. return Context.getMDKindNames(Result);
  90. }
  91. //===----------------------------------------------------------------------===//
  92. // Methods for easy access to the functions in the module.
  93. //
  94. // getOrInsertFunction - Look up the specified function in the module symbol
  95. // table. If it does not exist, add a prototype for the function and return
  96. // it. This is nice because it allows most passes to get away with not handling
  97. // the symbol table directly for this common task.
  98. //
  99. Constant *Module::getOrInsertFunction(StringRef Name,
  100. FunctionType *Ty,
  101. AttributeSet AttributeList) {
  102. // See if we have a definition for the specified function already.
  103. GlobalValue *F = getNamedValue(Name);
  104. if (!F) {
  105. // Nope, add it
  106. Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
  107. if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
  108. New->setAttributes(AttributeList);
  109. FunctionList.push_back(New);
  110. return New; // Return the new prototype.
  111. }
  112. // If the function exists but has the wrong type, return a bitcast to the
  113. // right type.
  114. if (F->getType() != PointerType::getUnqual(Ty))
  115. return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
  116. // Otherwise, we just found the existing function or a prototype.
  117. return F;
  118. }
  119. Constant *Module::getOrInsertFunction(StringRef Name,
  120. FunctionType *Ty) {
  121. return getOrInsertFunction(Name, Ty, AttributeSet());
  122. }
  123. // getOrInsertFunction - Look up the specified function in the module symbol
  124. // table. If it does not exist, add a prototype for the function and return it.
  125. // This version of the method takes a null terminated list of function
  126. // arguments, which makes it easier for clients to use.
  127. //
  128. Constant *Module::getOrInsertFunction(StringRef Name,
  129. AttributeSet AttributeList,
  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. AttributeList);
  142. }
  143. Constant *Module::getOrInsertFunction(StringRef Name,
  144. Type *RetTy, ...) {
  145. va_list Args;
  146. va_start(Args, RetTy);
  147. // Build the list of argument types...
  148. std::vector<Type*> ArgTys;
  149. while (Type *ArgTy = va_arg(Args, Type*))
  150. ArgTys.push_back(ArgTy);
  151. va_end(Args);
  152. // Build the function type and chain to the other getOrInsertFunction...
  153. return getOrInsertFunction(Name,
  154. FunctionType::get(RetTy, ArgTys, false),
  155. AttributeSet());
  156. }
  157. // getFunction - Look up the specified function in the module symbol table.
  158. // If it does not exist, return null.
  159. //
  160. Function *Module::getFunction(StringRef Name) const {
  161. return dyn_cast_or_null<Function>(getNamedValue(Name));
  162. }
  163. //===----------------------------------------------------------------------===//
  164. // Methods for easy access to the global variables in the module.
  165. //
  166. /// getGlobalVariable - Look up the specified global variable in the module
  167. /// symbol table. If it does not exist, return null. The type argument
  168. /// should be the underlying type of the global, i.e., it should not have
  169. /// the top-level PointerType, which represents the address of the global.
  170. /// If AllowLocal is set to true, this function will return types that
  171. /// have an local. By default, these types are not returned.
  172. ///
  173. GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
  174. if (GlobalVariable *Result =
  175. dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
  176. if (AllowLocal || !Result->hasLocalLinkage())
  177. return Result;
  178. return nullptr;
  179. }
  180. /// getOrInsertGlobal - Look up the specified global in the module symbol table.
  181. /// 1. If it does not exist, add a declaration of the global and return it.
  182. /// 2. Else, the global exists but has the wrong type: return the function
  183. /// with a constantexpr cast to the right type.
  184. /// 3. Finally, if the existing global is the correct declaration, return the
  185. /// existing global.
  186. Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
  187. // See if we have a definition for the specified global already.
  188. GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
  189. if (!GV) {
  190. // Nope, add it
  191. GlobalVariable *New =
  192. new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
  193. nullptr, Name);
  194. return New; // Return the new declaration.
  195. }
  196. // If the variable exists but has the wrong type, return a bitcast to the
  197. // right type.
  198. Type *GVTy = GV->getType();
  199. PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
  200. if (GVTy != PTy)
  201. return ConstantExpr::getBitCast(GV, PTy);
  202. // Otherwise, we just found the existing function or a prototype.
  203. return GV;
  204. }
  205. //===----------------------------------------------------------------------===//
  206. // Methods for easy access to the global variables in the module.
  207. //
  208. // getNamedAlias - Look up the specified global in the module symbol table.
  209. // If it does not exist, return null.
  210. //
  211. GlobalAlias *Module::getNamedAlias(StringRef Name) const {
  212. return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
  213. }
  214. /// getNamedMetadata - Return the first NamedMDNode in the module with the
  215. /// specified name. This method returns null if a NamedMDNode with the
  216. /// specified name is not found.
  217. NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
  218. SmallString<256> NameData;
  219. StringRef NameRef = Name.toStringRef(NameData);
  220. return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
  221. }
  222. /// getOrInsertNamedMetadata - Return the first named MDNode in the module
  223. /// with the specified name. This method returns a new NamedMDNode if a
  224. /// NamedMDNode with the specified name is not found.
  225. NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
  226. NamedMDNode *&NMD =
  227. (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
  228. if (!NMD) {
  229. NMD = new NamedMDNode(Name);
  230. NMD->setParent(this);
  231. NamedMDList.push_back(NMD);
  232. }
  233. return NMD;
  234. }
  235. /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
  236. /// delete it.
  237. void Module::eraseNamedMetadata(NamedMDNode *NMD) {
  238. static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
  239. NamedMDList.erase(NMD);
  240. }
  241. bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
  242. if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
  243. uint64_t Val = Behavior->getLimitedValue();
  244. if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
  245. MFB = static_cast<ModFlagBehavior>(Val);
  246. return true;
  247. }
  248. }
  249. return false;
  250. }
  251. /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
  252. void Module::
  253. getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
  254. const NamedMDNode *ModFlags = getModuleFlagsMetadata();
  255. if (!ModFlags) return;
  256. for (const MDNode *Flag : ModFlags->operands()) {
  257. ModFlagBehavior MFB;
  258. if (Flag->getNumOperands() >= 3 &&
  259. isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
  260. dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
  261. // Check the operands of the MDNode before accessing the operands.
  262. // The verifier will actually catch these failures.
  263. MDString *Key = cast<MDString>(Flag->getOperand(1));
  264. Metadata *Val = Flag->getOperand(2);
  265. Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
  266. }
  267. }
  268. }
  269. /// Return the corresponding value if Key appears in module flags, otherwise
  270. /// return null.
  271. Metadata *Module::getModuleFlag(StringRef Key) const {
  272. SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
  273. getModuleFlagsMetadata(ModuleFlags);
  274. for (const ModuleFlagEntry &MFE : ModuleFlags) {
  275. if (Key == MFE.Key->getString())
  276. return MFE.Val;
  277. }
  278. return nullptr;
  279. }
  280. /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
  281. /// represents module-level flags. This method returns null if there are no
  282. /// module-level flags.
  283. NamedMDNode *Module::getModuleFlagsMetadata() const {
  284. return getNamedMetadata("llvm.module.flags");
  285. }
  286. /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
  287. /// represents module-level flags. If module-level flags aren't found, it
  288. /// creates the named metadata that contains them.
  289. NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
  290. return getOrInsertNamedMetadata("llvm.module.flags");
  291. }
  292. /// addModuleFlag - Add a module-level flag to the module-level flags
  293. /// metadata. It will create the module-level flags named metadata if it doesn't
  294. /// already exist.
  295. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  296. Metadata *Val) {
  297. Type *Int32Ty = Type::getInt32Ty(Context);
  298. Metadata *Ops[3] = {
  299. ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
  300. MDString::get(Context, Key), Val};
  301. getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
  302. }
  303. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  304. Constant *Val) {
  305. addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
  306. }
  307. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  308. uint32_t Val) {
  309. Type *Int32Ty = Type::getInt32Ty(Context);
  310. addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
  311. }
  312. void Module::addModuleFlag(MDNode *Node) {
  313. assert(Node->getNumOperands() == 3 &&
  314. "Invalid number of operands for module flag!");
  315. assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
  316. isa<MDString>(Node->getOperand(1)) &&
  317. "Invalid operand types for module flag!");
  318. getOrInsertModuleFlagsMetadata()->addOperand(Node);
  319. }
  320. void Module::setDataLayout(StringRef Desc) {
  321. DL.reset(Desc);
  322. }
  323. void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
  324. const DataLayout &Module::getDataLayout() const { return DL; }
  325. //===----------------------------------------------------------------------===//
  326. // Methods to control the materialization of GlobalValues in the Module.
  327. //
  328. void Module::setMaterializer(GVMaterializer *GVM) {
  329. assert(!Materializer &&
  330. "Module already has a GVMaterializer. Call MaterializeAllPermanently"
  331. " to clear it out before setting another one.");
  332. Materializer.reset(GVM);
  333. }
  334. bool Module::isDematerializable(const GlobalValue *GV) const {
  335. if (Materializer)
  336. return Materializer->isDematerializable(GV);
  337. return false;
  338. }
  339. std::error_code Module::materialize(GlobalValue *GV) {
  340. if (!Materializer)
  341. return std::error_code();
  342. return Materializer->materialize(GV);
  343. }
  344. void Module::Dematerialize(GlobalValue *GV) {
  345. if (Materializer)
  346. return Materializer->Dematerialize(GV);
  347. }
  348. std::error_code Module::materializeAll() {
  349. if (!Materializer)
  350. return std::error_code();
  351. return Materializer->MaterializeModule(this);
  352. }
  353. std::error_code Module::materializeAllPermanently() {
  354. if (std::error_code EC = materializeAll())
  355. return EC;
  356. Materializer.reset();
  357. return std::error_code();
  358. }
  359. //===----------------------------------------------------------------------===//
  360. // Other module related stuff.
  361. //
  362. std::vector<StructType *> Module::getIdentifiedStructTypes() const {
  363. // If we have a materializer, it is possible that some unread function
  364. // uses a type that is currently not visible to a TypeFinder, so ask
  365. // the materializer which types it created.
  366. if (Materializer)
  367. return Materializer->getIdentifiedStructTypes();
  368. std::vector<StructType *> Ret;
  369. TypeFinder SrcStructTypes;
  370. SrcStructTypes.run(*this, true);
  371. Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
  372. return Ret;
  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 (Function &F : *this)
  383. F.dropAllReferences();
  384. for (GlobalVariable &GV : globals())
  385. GV.dropAllReferences();
  386. for (GlobalAlias &GA : aliases())
  387. GA.dropAllReferences();
  388. }
  389. unsigned Module::getDwarfVersion() const {
  390. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
  391. if (!Val)
  392. return dwarf::DWARF_VERSION;
  393. return cast<ConstantInt>(Val->getValue())->getZExtValue();
  394. }
  395. Comdat *Module::getOrInsertComdat(StringRef Name) {
  396. auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
  397. Entry.second.Name = &Entry;
  398. return &Entry.second;
  399. }
  400. PICLevel::Level Module::getPICLevel() const {
  401. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
  402. if (Val == NULL)
  403. return PICLevel::Default;
  404. return static_cast<PICLevel::Level>(
  405. cast<ConstantInt>(Val->getValue())->getZExtValue());
  406. }
  407. void Module::setPICLevel(PICLevel::Level PL) {
  408. addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);
  409. }