Module.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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,
  108. FunctionType *Ty,
  109. AttributeSet AttributeList) {
  110. // See if we have a definition for the specified function already.
  111. GlobalValue *F = getNamedValue(Name);
  112. if (!F) {
  113. // Nope, add it
  114. Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
  115. if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
  116. New->setAttributes(AttributeList);
  117. FunctionList.push_back(New);
  118. return New; // Return the new prototype.
  119. }
  120. // If the function exists but has the wrong type, return a bitcast to the
  121. // right type.
  122. if (F->getType() != PointerType::getUnqual(Ty))
  123. return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
  124. // Otherwise, we just found the existing function or a prototype.
  125. return F;
  126. }
  127. Constant *Module::getOrInsertFunction(StringRef Name,
  128. FunctionType *Ty) {
  129. return getOrInsertFunction(Name, Ty, AttributeSet());
  130. }
  131. // getOrInsertFunction - Look up the specified function in the module symbol
  132. // table. If it does not exist, add a prototype for the function and return it.
  133. // This version of the method takes a null terminated list of function
  134. // arguments, which makes it easier for clients to use.
  135. //
  136. Constant *Module::getOrInsertFunction(StringRef Name,
  137. AttributeSet AttributeList,
  138. Type *RetTy, ...) {
  139. va_list Args;
  140. va_start(Args, RetTy);
  141. // Build the list of argument types...
  142. std::vector<Type*> ArgTys;
  143. while (Type *ArgTy = va_arg(Args, Type*))
  144. ArgTys.push_back(ArgTy);
  145. va_end(Args);
  146. // Build the function type and chain to the other getOrInsertFunction...
  147. return getOrInsertFunction(Name,
  148. FunctionType::get(RetTy, ArgTys, false),
  149. AttributeList);
  150. }
  151. Constant *Module::getOrInsertFunction(StringRef Name,
  152. Type *RetTy, ...) {
  153. va_list Args;
  154. va_start(Args, RetTy);
  155. // Build the list of argument types...
  156. std::vector<Type*> ArgTys;
  157. while (Type *ArgTy = va_arg(Args, Type*))
  158. ArgTys.push_back(ArgTy);
  159. va_end(Args);
  160. // Build the function type and chain to the other getOrInsertFunction...
  161. return getOrInsertFunction(Name,
  162. FunctionType::get(RetTy, ArgTys, false),
  163. AttributeSet());
  164. }
  165. // getFunction - Look up the specified function in the module symbol table.
  166. // If it does not exist, return null.
  167. //
  168. Function *Module::getFunction(StringRef Name) const {
  169. return dyn_cast_or_null<Function>(getNamedValue(Name));
  170. }
  171. //===----------------------------------------------------------------------===//
  172. // Methods for easy access to the global variables in the module.
  173. //
  174. /// getGlobalVariable - Look up the specified global variable in the module
  175. /// symbol table. If it does not exist, return null. The type argument
  176. /// should be the underlying type of the global, i.e., it should not have
  177. /// the top-level PointerType, which represents the address of the global.
  178. /// If AllowLocal is set to true, this function will return types that
  179. /// have an local. By default, these types are not returned.
  180. ///
  181. GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
  182. if (GlobalVariable *Result =
  183. dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
  184. if (AllowLocal || !Result->hasLocalLinkage())
  185. return Result;
  186. return nullptr;
  187. }
  188. /// getOrInsertGlobal - Look up the specified global in the module symbol table.
  189. /// 1. If it does not exist, add a declaration of the global and return it.
  190. /// 2. Else, the global exists but has the wrong type: return the function
  191. /// with a constantexpr cast to the right type.
  192. /// 3. Finally, if the existing global is the correct declaration, return the
  193. /// existing global.
  194. Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
  195. // See if we have a definition for the specified global already.
  196. GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
  197. if (!GV) {
  198. // Nope, add it
  199. GlobalVariable *New =
  200. new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
  201. nullptr, Name);
  202. return New; // Return the new declaration.
  203. }
  204. // If the variable exists but has the wrong type, return a bitcast to the
  205. // right type.
  206. Type *GVTy = GV->getType();
  207. PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
  208. if (GVTy != PTy)
  209. return ConstantExpr::getBitCast(GV, PTy);
  210. // Otherwise, we just found the existing function or a prototype.
  211. return GV;
  212. }
  213. //===----------------------------------------------------------------------===//
  214. // Methods for easy access to the global variables in the module.
  215. //
  216. // getNamedAlias - Look up the specified global in the module symbol table.
  217. // If it does not exist, return null.
  218. //
  219. GlobalAlias *Module::getNamedAlias(StringRef Name) const {
  220. return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
  221. }
  222. GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
  223. return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
  224. }
  225. /// getNamedMetadata - Return the first NamedMDNode in the module with the
  226. /// specified name. This method returns null if a NamedMDNode with the
  227. /// specified name is not found.
  228. NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
  229. SmallString<256> NameData;
  230. StringRef NameRef = Name.toStringRef(NameData);
  231. return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
  232. }
  233. /// getOrInsertNamedMetadata - Return the first named MDNode in the module
  234. /// with the specified name. This method returns a new NamedMDNode if a
  235. /// NamedMDNode with the specified name is not found.
  236. NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
  237. NamedMDNode *&NMD =
  238. (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
  239. if (!NMD) {
  240. NMD = new NamedMDNode(Name);
  241. NMD->setParent(this);
  242. NamedMDList.push_back(NMD);
  243. }
  244. return NMD;
  245. }
  246. /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
  247. /// delete it.
  248. void Module::eraseNamedMetadata(NamedMDNode *NMD) {
  249. static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
  250. NamedMDList.erase(NMD->getIterator());
  251. }
  252. bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
  253. if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
  254. uint64_t Val = Behavior->getLimitedValue();
  255. if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
  256. MFB = static_cast<ModFlagBehavior>(Val);
  257. return true;
  258. }
  259. }
  260. return false;
  261. }
  262. /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
  263. void Module::
  264. getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
  265. const NamedMDNode *ModFlags = getModuleFlagsMetadata();
  266. if (!ModFlags) return;
  267. for (const MDNode *Flag : ModFlags->operands()) {
  268. ModFlagBehavior MFB;
  269. if (Flag->getNumOperands() >= 3 &&
  270. isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
  271. dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
  272. // Check the operands of the MDNode before accessing the operands.
  273. // The verifier will actually catch these failures.
  274. MDString *Key = cast<MDString>(Flag->getOperand(1));
  275. Metadata *Val = Flag->getOperand(2);
  276. Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
  277. }
  278. }
  279. }
  280. /// Return the corresponding value if Key appears in module flags, otherwise
  281. /// return null.
  282. Metadata *Module::getModuleFlag(StringRef Key) const {
  283. SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
  284. getModuleFlagsMetadata(ModuleFlags);
  285. for (const ModuleFlagEntry &MFE : ModuleFlags) {
  286. if (Key == MFE.Key->getString())
  287. return MFE.Val;
  288. }
  289. return nullptr;
  290. }
  291. /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
  292. /// represents module-level flags. This method returns null if there are no
  293. /// module-level flags.
  294. NamedMDNode *Module::getModuleFlagsMetadata() const {
  295. return getNamedMetadata("llvm.module.flags");
  296. }
  297. /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
  298. /// represents module-level flags. If module-level flags aren't found, it
  299. /// creates the named metadata that contains them.
  300. NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
  301. return getOrInsertNamedMetadata("llvm.module.flags");
  302. }
  303. /// addModuleFlag - Add a module-level flag to the module-level flags
  304. /// metadata. It will create the module-level flags named metadata if it doesn't
  305. /// already exist.
  306. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  307. Metadata *Val) {
  308. Type *Int32Ty = Type::getInt32Ty(Context);
  309. Metadata *Ops[3] = {
  310. ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
  311. MDString::get(Context, Key), Val};
  312. getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
  313. }
  314. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  315. Constant *Val) {
  316. addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
  317. }
  318. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  319. uint32_t Val) {
  320. Type *Int32Ty = Type::getInt32Ty(Context);
  321. addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
  322. }
  323. void Module::addModuleFlag(MDNode *Node) {
  324. assert(Node->getNumOperands() == 3 &&
  325. "Invalid number of operands for module flag!");
  326. assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
  327. isa<MDString>(Node->getOperand(1)) &&
  328. "Invalid operand types for module flag!");
  329. getOrInsertModuleFlagsMetadata()->addOperand(Node);
  330. }
  331. void Module::setDataLayout(StringRef Desc) {
  332. DL.reset(Desc);
  333. }
  334. void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
  335. const DataLayout &Module::getDataLayout() const { return DL; }
  336. DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
  337. return cast<DICompileUnit>(CUs->getOperand(Idx));
  338. }
  339. DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
  340. return cast<DICompileUnit>(CUs->getOperand(Idx));
  341. }
  342. void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
  343. while (CUs && (Idx < CUs->getNumOperands()) &&
  344. ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
  345. ++Idx;
  346. }
  347. //===----------------------------------------------------------------------===//
  348. // Methods to control the materialization of GlobalValues in the Module.
  349. //
  350. void Module::setMaterializer(GVMaterializer *GVM) {
  351. assert(!Materializer &&
  352. "Module already has a GVMaterializer. Call materializeAll"
  353. " to clear it out before setting another one.");
  354. Materializer.reset(GVM);
  355. }
  356. Error Module::materialize(GlobalValue *GV) {
  357. if (!Materializer)
  358. return Error::success();
  359. return Materializer->materialize(GV);
  360. }
  361. Error Module::materializeAll() {
  362. if (!Materializer)
  363. return Error::success();
  364. std::unique_ptr<GVMaterializer> M = std::move(Materializer);
  365. return M->materializeModule();
  366. }
  367. Error Module::materializeMetadata() {
  368. if (!Materializer)
  369. return Error::success();
  370. return Materializer->materializeMetadata();
  371. }
  372. //===----------------------------------------------------------------------===//
  373. // Other module related stuff.
  374. //
  375. std::vector<StructType *> Module::getIdentifiedStructTypes() const {
  376. // If we have a materializer, it is possible that some unread function
  377. // uses a type that is currently not visible to a TypeFinder, so ask
  378. // the materializer which types it created.
  379. if (Materializer)
  380. return Materializer->getIdentifiedStructTypes();
  381. std::vector<StructType *> Ret;
  382. TypeFinder SrcStructTypes;
  383. SrcStructTypes.run(*this, true);
  384. Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
  385. return Ret;
  386. }
  387. // dropAllReferences() - This function causes all the subelements to "let go"
  388. // of all references that they are maintaining. This allows one to 'delete' a
  389. // whole module at a time, even though there may be circular references... first
  390. // all references are dropped, and all use counts go to zero. Then everything
  391. // is deleted for real. Note that no operations are valid on an object that
  392. // has "dropped all references", except operator delete.
  393. //
  394. void Module::dropAllReferences() {
  395. for (Function &F : *this)
  396. F.dropAllReferences();
  397. for (GlobalVariable &GV : globals())
  398. GV.dropAllReferences();
  399. for (GlobalAlias &GA : aliases())
  400. GA.dropAllReferences();
  401. for (GlobalIFunc &GIF : ifuncs())
  402. GIF.dropAllReferences();
  403. }
  404. unsigned Module::getDwarfVersion() const {
  405. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
  406. if (!Val)
  407. return 0;
  408. return cast<ConstantInt>(Val->getValue())->getZExtValue();
  409. }
  410. unsigned Module::getCodeViewFlag() const {
  411. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
  412. if (!Val)
  413. return 0;
  414. return cast<ConstantInt>(Val->getValue())->getZExtValue();
  415. }
  416. Comdat *Module::getOrInsertComdat(StringRef Name) {
  417. auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
  418. Entry.second.Name = &Entry;
  419. return &Entry.second;
  420. }
  421. PICLevel::Level Module::getPICLevel() const {
  422. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
  423. if (!Val)
  424. return PICLevel::NotPIC;
  425. return static_cast<PICLevel::Level>(
  426. cast<ConstantInt>(Val->getValue())->getZExtValue());
  427. }
  428. void Module::setPICLevel(PICLevel::Level PL) {
  429. addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);
  430. }
  431. PIELevel::Level Module::getPIELevel() const {
  432. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
  433. if (!Val)
  434. return PIELevel::Default;
  435. return static_cast<PIELevel::Level>(
  436. cast<ConstantInt>(Val->getValue())->getZExtValue());
  437. }
  438. void Module::setPIELevel(PIELevel::Level PL) {
  439. addModuleFlag(ModFlagBehavior::Error, "PIE Level", PL);
  440. }
  441. void Module::setProfileSummary(Metadata *M) {
  442. addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
  443. }
  444. Metadata *Module::getProfileSummary() {
  445. return getModuleFlag("ProfileSummary");
  446. }
  447. void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
  448. OwnedMemoryBuffer = std::move(MB);
  449. }
  450. GlobalVariable *llvm::collectUsedGlobalVariables(
  451. const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
  452. const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
  453. GlobalVariable *GV = M.getGlobalVariable(Name);
  454. if (!GV || !GV->hasInitializer())
  455. return GV;
  456. const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
  457. for (Value *Op : Init->operands()) {
  458. GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
  459. Set.insert(G);
  460. }
  461. return GV;
  462. }