Module.cpp 19 KB

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