Module.cpp 18 KB

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