blob: 93f27304424ffddb313213006e27ee74cc9bef1b [file] [log] [blame]
Eugene Zelenkodc6cb602017-05-10 23:41:30 +00001//===- Module.cpp - Implement the Module class ----------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
Chandler Carruthc2c50cd2013-01-02 09:10:48 +000010// This file implements the Module class for the IR library.
Chris Lattner00950542001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chandler Carruthe3e43d92017-06-06 11:49:48 +000014#include "llvm/IR/Module.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000015#include "SymbolTableListTraitsImpl.h"
Caroline Ticea53c5202018-09-21 18:41:31 +000016#include "llvm/ADT/Optional.h"
Teresa Johnson89c5c632016-04-20 14:39:45 +000017#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/SmallString.h"
Eugene Zelenkodc6cb602017-05-10 23:41:30 +000019#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringMap.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/IR/Attributes.h"
24#include "llvm/IR/Comdat.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
Eugene Zelenkodc6cb602017-05-10 23:41:30 +000026#include "llvm/IR/DataLayout.h"
Adrian Prantl48bb8b42016-04-08 22:43:03 +000027#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruthe3e43d92017-06-06 11:49:48 +000028#include "llvm/IR/DerivedTypes.h"
Eugene Zelenkodc6cb602017-05-10 23:41:30 +000029#include "llvm/IR/Function.h"
Chandler Carruthe3e43d92017-06-06 11:49:48 +000030#include "llvm/IR/GVMaterializer.h"
Eugene Zelenkodc6cb602017-05-10 23:41:30 +000031#include "llvm/IR/GlobalAlias.h"
32#include "llvm/IR/GlobalIFunc.h"
33#include "llvm/IR/GlobalValue.h"
34#include "llvm/IR/GlobalVariable.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000035#include "llvm/IR/LLVMContext.h"
Eugene Zelenkodc6cb602017-05-10 23:41:30 +000036#include "llvm/IR/Metadata.h"
Eugene Zelenkodc6cb602017-05-10 23:41:30 +000037#include "llvm/IR/SymbolTableListTraits.h"
38#include "llvm/IR/Type.h"
Rafael Espindolaeee41db2014-12-03 07:18:23 +000039#include "llvm/IR/TypeFinder.h"
Eugene Zelenkodc6cb602017-05-10 23:41:30 +000040#include "llvm/IR/Value.h"
41#include "llvm/IR/ValueSymbolTable.h"
42#include "llvm/Pass.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/CodeGen.h"
Peter Collingbourne76c218e2016-11-09 17:49:19 +000045#include "llvm/Support/Error.h"
Peter Collingbourne5498e182016-11-08 06:03:43 +000046#include "llvm/Support/MemoryBuffer.h"
JF Bastienb4840d72014-06-25 15:21:42 +000047#include "llvm/Support/Path.h"
48#include "llvm/Support/RandomNumberGenerator.h"
Alex Lorenz6592c092018-12-14 01:14:10 +000049#include "llvm/Support/VersionTuple.h"
Chris Lattner7e708292002-06-25 16:13:24 +000050#include <algorithm>
Eugene Zelenkodc6cb602017-05-10 23:41:30 +000051#include <cassert>
52#include <cstdint>
53#include <memory>
54#include <utility>
55#include <vector>
Hans Wennborg4d651e42015-10-06 23:24:35 +000056
Chris Lattner31f84992003-11-21 20:23:48 +000057using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000058
Chris Lattner60837822003-12-31 08:43:01 +000059//===----------------------------------------------------------------------===//
Misha Brukmanaf76cfb2004-04-21 18:27:56 +000060// Methods to implement the globals and functions lists.
Chris Lattner60837822003-12-31 08:43:01 +000061//
62
Chris Lattner7e708292002-06-25 16:13:24 +000063// Explicit instantiations of SymbolTableListTraits since some of the methods
Chris Lattnercc041ba2006-01-24 04:13:11 +000064// are not in the public header file.
Duncan P. N. Exon Smith2a8bcfa2015-10-07 20:05:10 +000065template class llvm::SymbolTableListTraits<Function>;
66template class llvm::SymbolTableListTraits<GlobalVariable>;
67template class llvm::SymbolTableListTraits<GlobalAlias>;
Dmitry Polukhinba492232016-04-07 12:32:19 +000068template class llvm::SymbolTableListTraits<GlobalIFunc>;
Chris Lattner00950542001-06-06 20:29:01 +000069
Chris Lattner60837822003-12-31 08:43:01 +000070//===----------------------------------------------------------------------===//
71// Primitive Module methods.
72//
Chris Lattnerdd6dfbc2001-10-13 06:58:40 +000073
Rafael Espindolaaab87fe2014-02-25 20:01:08 +000074Module::Module(StringRef MID, LLVMContext &C)
Teresa Johnson00601602016-02-10 21:55:02 +000075 : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") {
Reid Spenceref9b9a72007-02-05 20:47:22 +000076 ValSymTab = new ValueSymbolTable();
Dan Gohman17aa92c2010-07-21 23:38:33 +000077 NamedMDSymTab = new StringMap<NamedMDNode *>();
Owen Anderson30268be2010-09-08 18:03:32 +000078 Context.addModule(this);
Chris Lattner00950542001-06-06 20:29:01 +000079}
80
81Module::~Module() {
Owen Anderson30268be2010-09-08 18:03:32 +000082 Context.removeModule(this);
Chris Lattner00950542001-06-06 20:29:01 +000083 dropAllReferences();
Chris Lattner7e708292002-06-25 16:13:24 +000084 GlobalList.clear();
Chris Lattner7e708292002-06-25 16:13:24 +000085 FunctionList.clear();
Anton Korobeynikov8b0a8c82007-04-25 14:27:10 +000086 AliasList.clear();
Dmitry Polukhinba492232016-04-07 12:32:19 +000087 IFuncList.clear();
Devang Patel28bc9d82009-07-29 17:16:17 +000088 NamedMDList.clear();
Reid Spencer78d033e2007-01-06 07:24:44 +000089 delete ValSymTab;
Dan Gohman17aa92c2010-07-21 23:38:33 +000090 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
Chris Lattner00950542001-06-06 20:29:01 +000091}
92
Serge Gueltonfbec1c92017-07-12 08:03:44 +000093std::unique_ptr<RandomNumberGenerator> Module::createRNG(const Pass* P) const {
JF Bastien544f63e2014-12-17 18:12:10 +000094 SmallString<32> Salt(P->getPassName());
95
96 // This RNG is guaranteed to produce the same random stream only
97 // when the Module ID and thus the input filename is the same. This
98 // might be problematic if the input filename extension changes
99 // (e.g. from .c to .bc or .ll).
100 //
101 // We could store this salt in NamedMetadata, but this would make
102 // the parameter non-const. This would unfortunately make this
103 // interface unusable by any Machine passes, since they only have a
104 // const reference to their IR Module. Alternatively we can always
105 // store salt metadata from the Module constructor.
106 Salt += sys::path::filename(getModuleIdentifier());
107
Serge Guelton624678f2017-07-18 08:36:22 +0000108 return std::unique_ptr<RandomNumberGenerator>(new RandomNumberGenerator(Salt));
JF Bastien544f63e2014-12-17 18:12:10 +0000109}
110
Daniel Dunbarf56ec642009-03-06 22:04:43 +0000111/// getNamedValue - Return the first global value in the module with
112/// the specified name, of arbitrary type. This method returns null
113/// if a global with the specified name is not found.
Daniel Dunbar2928c832009-11-06 10:58:06 +0000114GlobalValue *Module::getNamedValue(StringRef Name) const {
Daniel Dunbarf56ec642009-03-06 22:04:43 +0000115 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
116}
117
Chris Lattner08113472009-12-29 09:01:33 +0000118/// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
119/// This ID is uniqued across modules in the current LLVMContext.
120unsigned Module::getMDKindID(StringRef Name) const {
121 return Context.getMDKindID(Name);
122}
123
124/// getMDKindNames - Populate client supplied SmallVector with the name for
125/// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
126/// so it is filled in as an empty string.
127void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
128 return Context.getMDKindNames(Result);
129}
130
Sanjoy Das5b674c02015-09-24 19:14:18 +0000131void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
132 return Context.getOperandBundleTags(Result);
133}
Chris Lattner08113472009-12-29 09:01:33 +0000134
Chris Lattner60837822003-12-31 08:43:01 +0000135//===----------------------------------------------------------------------===//
136// Methods for easy access to the functions in the module.
137//
138
Reid Spenceref9b9a72007-02-05 20:47:22 +0000139// getOrInsertFunction - Look up the specified function in the module symbol
140// table. If it does not exist, add a prototype for the function and return
141// it. This is nice because it allows most passes to get away with not handling
142// the symbol table directly for this common task.
143//
Reid Kleckner67077702017-03-21 16:57:19 +0000144Constant *Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
145 AttributeList AttributeList) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000146 // See if we have a definition for the specified function already.
Daniel Dunbarf56ec642009-03-06 22:04:43 +0000147 GlobalValue *F = getNamedValue(Name);
Craig Topperec0f0bc2014-04-09 06:08:46 +0000148 if (!F) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000149 // Nope, add it
Alexander Richardson47ff67b2018-08-23 09:25:17 +0000150 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage,
151 DL.getProgramAddressSpace(), Name);
Nick Lewycky1186bf12009-01-04 22:54:40 +0000152 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
153 New->setAttributes(AttributeList);
Chris Lattner6056c492002-03-29 03:44:18 +0000154 FunctionList.push_back(New);
Chris Lattner70d13052007-01-07 08:09:25 +0000155 return New; // Return the new prototype.
Chris Lattner6056c492002-03-29 03:44:18 +0000156 }
Chris Lattner70d13052007-01-07 08:09:25 +0000157
Chris Lattner70d13052007-01-07 08:09:25 +0000158 // If the function exists but has the wrong type, return a bitcast to the
159 // right type.
Alexander Richardson47ff67b2018-08-23 09:25:17 +0000160 auto *PTy = PointerType::get(Ty, F->getAddressSpace());
161 if (F->getType() != PTy)
162 return ConstantExpr::getBitCast(F, PTy);
Bill Wendling85d043d2012-04-23 00:23:33 +0000163
Chris Lattner70d13052007-01-07 08:09:25 +0000164 // Otherwise, we just found the existing function or a prototype.
Bill Wendling85d043d2012-04-23 00:23:33 +0000165 return F;
Chris Lattner6056c492002-03-29 03:44:18 +0000166}
167
Daniel Dunbar2928c832009-11-06 10:58:06 +0000168Constant *Module::getOrInsertFunction(StringRef Name,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000169 FunctionType *Ty) {
Reid Kleckner67077702017-03-21 16:57:19 +0000170 return getOrInsertFunction(Name, Ty, AttributeList());
Nick Lewycky1186bf12009-01-04 22:54:40 +0000171}
172
Chris Lattner6056c492002-03-29 03:44:18 +0000173// getFunction - Look up the specified function in the module symbol table.
174// If it does not exist, return null.
175//
Daniel Dunbar2928c832009-11-06 10:58:06 +0000176Function *Module::getFunction(StringRef Name) const {
Daniel Dunbarf56ec642009-03-06 22:04:43 +0000177 return dyn_cast_or_null<Function>(getNamedValue(Name));
Chris Lattnerbb0e2482008-06-27 21:09:10 +0000178}
179
Chris Lattner60837822003-12-31 08:43:01 +0000180//===----------------------------------------------------------------------===//
181// Methods for easy access to the global variables in the module.
182//
183
184/// getGlobalVariable - Look up the specified global variable in the module
Chris Lattner30614672005-12-05 05:30:21 +0000185/// symbol table. If it does not exist, return null. The type argument
186/// should be the underlying type of the global, i.e., it should not have
187/// the top-level PointerType, which represents the address of the global.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000188/// If AllowLocal is set to true, this function will return types that
189/// have an local. By default, these types are not returned.
Chris Lattner60837822003-12-31 08:43:01 +0000190///
Craig Topper306a7df2017-03-27 05:47:03 +0000191GlobalVariable *Module::getGlobalVariable(StringRef Name,
192 bool AllowLocal) const {
Bill Wendling85d043d2012-04-23 00:23:33 +0000193 if (GlobalVariable *Result =
Daniel Dunbarf56ec642009-03-06 22:04:43 +0000194 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
195 if (AllowLocal || !Result->hasLocalLinkage())
Chris Lattner60837822003-12-31 08:43:01 +0000196 return Result;
Craig Topperec0f0bc2014-04-09 06:08:46 +0000197 return nullptr;
Chris Lattner60837822003-12-31 08:43:01 +0000198}
199
Bill Wendlingb4b130f2008-11-05 23:42:27 +0000200/// getOrInsertGlobal - Look up the specified global in the module symbol table.
201/// 1. If it does not exist, add a declaration of the global and return it.
202/// 2. Else, the global exists but has the wrong type: return the function
203/// with a constantexpr cast to the right type.
Matt Arsenaultf625c142013-09-28 01:08:00 +0000204/// 3. Finally, if the existing global is the correct declaration, return the
Bill Wendlingb4b130f2008-11-05 23:42:27 +0000205/// existing global.
Philip Pfaffe60162312019-01-02 15:41:47 +0000206Constant *Module::getOrInsertGlobal(
207 StringRef Name, Type *Ty,
208 function_ref<GlobalVariable *()> CreateGlobalCallback) {
Bill Wendlingb7c2c122008-11-04 22:51:24 +0000209 // See if we have a definition for the specified global already.
Daniel Dunbarf56ec642009-03-06 22:04:43 +0000210 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
Philip Pfaffe60162312019-01-02 15:41:47 +0000211 if (!GV)
212 GV = CreateGlobalCallback();
213 assert(GV && "The CreateGlobalCallback is expected to create a global");
Bill Wendlingb7c2c122008-11-04 22:51:24 +0000214
215 // If the variable exists but has the wrong type, return a bitcast to the
216 // right type.
Matt Arsenault2ebcd572013-09-30 21:23:03 +0000217 Type *GVTy = GV->getType();
218 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
Matt Arsenaultb1d70af2013-09-30 23:31:50 +0000219 if (GVTy != PTy)
Matt Arsenault2ebcd572013-09-30 21:23:03 +0000220 return ConstantExpr::getBitCast(GV, PTy);
Bill Wendling85d043d2012-04-23 00:23:33 +0000221
Bill Wendlingb7c2c122008-11-04 22:51:24 +0000222 // Otherwise, we just found the existing function or a prototype.
223 return GV;
224}
225
Philip Pfaffe60162312019-01-02 15:41:47 +0000226// Overload to construct a global variable using its constructor's defaults.
227Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
228 return getOrInsertGlobal(Name, Ty, [&] {
229 return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
230 nullptr, Name);
231 });
232}
233
Chris Lattner60837822003-12-31 08:43:01 +0000234//===----------------------------------------------------------------------===//
Anton Korobeynikov8b0a8c82007-04-25 14:27:10 +0000235// Methods for easy access to the global variables in the module.
236//
237
238// getNamedAlias - Look up the specified global in the module symbol table.
239// If it does not exist, return null.
240//
Daniel Dunbar2928c832009-11-06 10:58:06 +0000241GlobalAlias *Module::getNamedAlias(StringRef Name) const {
Daniel Dunbarf56ec642009-03-06 22:04:43 +0000242 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
Anton Korobeynikov8b0a8c82007-04-25 14:27:10 +0000243}
244
Dmitry Polukhinba492232016-04-07 12:32:19 +0000245GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
246 return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
247}
248
Devang Patel49fe6c92009-07-30 23:59:04 +0000249/// getNamedMetadata - Return the first NamedMDNode in the module with the
Bill Wendling85d043d2012-04-23 00:23:33 +0000250/// specified name. This method returns null if a NamedMDNode with the
Bob Wilson54eee522010-06-19 05:33:57 +0000251/// specified name is not found.
Devang Patela762b092010-06-22 01:19:38 +0000252NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
Devang Patel2f7d5292010-06-16 00:53:55 +0000253 SmallString<256> NameData;
254 StringRef NameRef = Name.toStringRef(NameData);
Dan Gohman17aa92c2010-07-21 23:38:33 +0000255 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
Devang Patel2f7d5292010-06-16 00:53:55 +0000256}
257
Bill Wendling85d043d2012-04-23 00:23:33 +0000258/// getOrInsertNamedMetadata - Return the first named MDNode in the module
259/// with the specified name. This method returns a new NamedMDNode if a
Devang Patel49fe6c92009-07-30 23:59:04 +0000260/// NamedMDNode with the specified name is not found.
Daniel Dunbar2928c832009-11-06 10:58:06 +0000261NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
Dan Gohman17aa92c2010-07-21 23:38:33 +0000262 NamedMDNode *&NMD =
263 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
264 if (!NMD) {
265 NMD = new NamedMDNode(Name);
266 NMD->setParent(this);
267 NamedMDList.push_back(NMD);
268 }
Devang Patel49fe6c92009-07-30 23:59:04 +0000269 return NMD;
270}
271
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000272/// eraseNamedMetadata - Remove the given NamedMDNode from this module and
273/// delete it.
Dan Gohman17aa92c2010-07-21 23:38:33 +0000274void Module::eraseNamedMetadata(NamedMDNode *NMD) {
275 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
Duncan P. N. Exon Smitheac30952015-10-08 23:49:46 +0000276 NamedMDList.erase(NMD->getIterator());
Dan Gohman17aa92c2010-07-21 23:38:33 +0000277}
278
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000279bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
David Majnemerf9376222015-02-11 09:13:06 +0000280 if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
Alexey Samsonove769dc32014-09-08 19:16:28 +0000281 uint64_t Val = Behavior->getLimitedValue();
282 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
283 MFB = static_cast<ModFlagBehavior>(Val);
284 return true;
285 }
286 }
287 return false;
288}
289
Bill Wendlingf20f2812012-02-15 22:34:20 +0000290/// getModuleFlagsMetadata - Returns the module flags in the provided vector.
291void Module::
292getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
293 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
294 if (!ModFlags) return;
295
Duncan P. N. Exon Smith5bf8ade2014-11-11 21:30:22 +0000296 for (const MDNode *Flag : ModFlags->operands()) {
Alexey Samsonove769dc32014-09-08 19:16:28 +0000297 ModFlagBehavior MFB;
298 if (Flag->getNumOperands() >= 3 &&
299 isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
David Majnemerf9376222015-02-11 09:13:06 +0000300 dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
Manman Ren7d318bd2013-12-02 21:29:56 +0000301 // Check the operands of the MDNode before accessing the operands.
302 // The verifier will actually catch these failures.
Manman Ren7d318bd2013-12-02 21:29:56 +0000303 MDString *Key = cast<MDString>(Flag->getOperand(1));
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000304 Metadata *Val = Flag->getOperand(2);
Alexey Samsonove769dc32014-09-08 19:16:28 +0000305 Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
Manman Ren7d318bd2013-12-02 21:29:56 +0000306 }
Bill Wendlingf20f2812012-02-15 22:34:20 +0000307 }
308}
309
Manman Renc8cfaa12013-07-16 23:21:16 +0000310/// Return the corresponding value if Key appears in module flags, otherwise
311/// return null.
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000312Metadata *Module::getModuleFlag(StringRef Key) const {
Manman Renc8cfaa12013-07-16 23:21:16 +0000313 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
314 getModuleFlagsMetadata(ModuleFlags);
Benjamin Kramer6e9eeab2014-03-10 15:03:06 +0000315 for (const ModuleFlagEntry &MFE : ModuleFlags) {
Manman Renc8cfaa12013-07-16 23:21:16 +0000316 if (Key == MFE.Key->getString())
317 return MFE.Val;
318 }
Craig Topperec0f0bc2014-04-09 06:08:46 +0000319 return nullptr;
Manman Renc8cfaa12013-07-16 23:21:16 +0000320}
321
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000322/// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
323/// represents module-level flags. This method returns null if there are no
324/// module-level flags.
325NamedMDNode *Module::getModuleFlagsMetadata() const {
326 return getNamedMetadata("llvm.module.flags");
327}
328
329/// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
330/// represents module-level flags. If module-level flags aren't found, it
331/// creates the named metadata that contains them.
332NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
333 return getOrInsertNamedMetadata("llvm.module.flags");
334}
335
336/// addModuleFlag - Add a module-level flag to the module-level flags
337/// metadata. It will create the module-level flags named metadata if it doesn't
338/// already exist.
Bill Wendlinge6bd7a82012-02-16 10:28:10 +0000339void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000340 Metadata *Val) {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000341 Type *Int32Ty = Type::getInt32Ty(Context);
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000342 Metadata *Ops[3] = {
343 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
344 MDString::get(Context, Key), Val};
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000345 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
346}
Bill Wendlinge6bd7a82012-02-16 10:28:10 +0000347void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000348 Constant *Val) {
349 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
350}
351void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000352 uint32_t Val) {
353 Type *Int32Ty = Type::getInt32Ty(Context);
354 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
355}
356void Module::addModuleFlag(MDNode *Node) {
357 assert(Node->getNumOperands() == 3 &&
358 "Invalid number of operands for module flag!");
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000359 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000360 isa<MDString>(Node->getOperand(1)) &&
361 "Invalid operand types for module flag!");
362 getOrInsertModuleFlagsMetadata()->addOperand(Node);
363}
Chris Lattnerf33fa6f2002-04-13 18:58:33 +0000364
Rafael Espindolaaab87fe2014-02-25 20:01:08 +0000365void Module::setDataLayout(StringRef Desc) {
Rafael Espindola3f0a9af2014-02-25 22:23:04 +0000366 DL.reset(Desc);
Rafael Espindolaaab87fe2014-02-25 20:01:08 +0000367}
368
Mehdi Aminic94da202015-03-04 18:43:29 +0000369void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
Rafael Espindolaaab87fe2014-02-25 20:01:08 +0000370
Mehdi Aminic94da202015-03-04 18:43:29 +0000371const DataLayout &Module::getDataLayout() const { return DL; }
Rafael Espindolaaab87fe2014-02-25 20:01:08 +0000372
Adrian Prantl48bb8b42016-04-08 22:43:03 +0000373DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
374 return cast<DICompileUnit>(CUs->getOperand(Idx));
375}
376DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
377 return cast<DICompileUnit>(CUs->getOperand(Idx));
378}
379
380void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
381 while (CUs && (Idx < CUs->getNumOperands()) &&
382 ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
383 ++Idx;
384}
385
Chris Lattner60837822003-12-31 08:43:01 +0000386//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000387// Methods to control the materialization of GlobalValues in the Module.
388//
389void Module::setMaterializer(GVMaterializer *GVM) {
390 assert(!Materializer &&
Rafael Espindola838f8a42015-12-18 20:13:39 +0000391 "Module already has a GVMaterializer. Call materializeAll"
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000392 " to clear it out before setting another one.");
393 Materializer.reset(GVM);
394}
395
Peter Collingbourne76c218e2016-11-09 17:49:19 +0000396Error Module::materialize(GlobalValue *GV) {
Rafael Espindolaaf9e8e62013-11-05 19:36:34 +0000397 if (!Materializer)
Peter Collingbourne76c218e2016-11-09 17:49:19 +0000398 return Error::success();
Rafael Espindolaaf9e8e62013-11-05 19:36:34 +0000399
Rafael Espindolac4982842014-10-24 22:50:48 +0000400 return Materializer->materialize(GV);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000401}
402
Peter Collingbourne76c218e2016-11-09 17:49:19 +0000403Error Module::materializeAll() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000404 if (!Materializer)
Peter Collingbourne76c218e2016-11-09 17:49:19 +0000405 return Error::success();
Rafael Espindola17920c22016-01-15 19:00:20 +0000406 std::unique_ptr<GVMaterializer> M = std::move(Materializer);
407 return M->materializeModule();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000408}
409
Peter Collingbourne76c218e2016-11-09 17:49:19 +0000410Error Module::materializeMetadata() {
Rafael Espindoladc6141a2015-03-13 21:54:20 +0000411 if (!Materializer)
Peter Collingbourne76c218e2016-11-09 17:49:19 +0000412 return Error::success();
Rafael Espindoladc6141a2015-03-13 21:54:20 +0000413 return Materializer->materializeMetadata();
414}
415
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000416//===----------------------------------------------------------------------===//
Chris Lattner60837822003-12-31 08:43:01 +0000417// Other module related stuff.
418//
419
Rafael Espindolaeee41db2014-12-03 07:18:23 +0000420std::vector<StructType *> Module::getIdentifiedStructTypes() const {
421 // If we have a materializer, it is possible that some unread function
422 // uses a type that is currently not visible to a TypeFinder, so ask
423 // the materializer which types it created.
424 if (Materializer)
425 return Materializer->getIdentifiedStructTypes();
426
427 std::vector<StructType *> Ret;
428 TypeFinder SrcStructTypes;
429 SrcStructTypes.run(*this, true);
430 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
431 return Ret;
432}
Chris Lattner60837822003-12-31 08:43:01 +0000433
Eric Christophercf84d862012-04-16 23:54:31 +0000434// dropAllReferences() - This function causes all the subelements to "let go"
Chris Lattner9da07152002-08-17 23:32:47 +0000435// of all references that they are maintaining. This allows one to 'delete' a
436// whole module at a time, even though there may be circular references... first
437// all references are dropped, and all use counts go to zero. Then everything
Misha Brukman6b634522003-10-10 17:54:14 +0000438// is deleted for real. Note that no operations are valid on an object that
Chris Lattner9da07152002-08-17 23:32:47 +0000439// has "dropped all references", except operator delete.
Chris Lattner00950542001-06-06 20:29:01 +0000440//
441void Module::dropAllReferences() {
David Majnemer82342682014-07-03 16:12:55 +0000442 for (Function &F : *this)
443 F.dropAllReferences();
Chris Lattnerdd6dfbc2001-10-13 06:58:40 +0000444
David Majnemer82342682014-07-03 16:12:55 +0000445 for (GlobalVariable &GV : globals())
446 GV.dropAllReferences();
Anton Korobeynikova80e1182007-04-28 13:45:00 +0000447
David Majnemer82342682014-07-03 16:12:55 +0000448 for (GlobalAlias &GA : aliases())
449 GA.dropAllReferences();
Dmitry Polukhinba492232016-04-07 12:32:19 +0000450
451 for (GlobalIFunc &GIF : ifuncs())
452 GIF.dropAllReferences();
Chris Lattner00950542001-06-06 20:29:01 +0000453}
Diego Novillo0a0d6202014-04-17 22:33:50 +0000454
Nirav Dave11fdc782017-03-18 00:44:07 +0000455unsigned Module::getNumberRegisterParameters() const {
456 auto *Val =
457 cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
458 if (!Val)
459 return 0;
460 return cast<ConstantInt>(Val->getValue())->getZExtValue();
461}
462
Diego Novillo0a0d6202014-04-17 22:33:50 +0000463unsigned Module::getDwarfVersion() const {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000464 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
Diego Novillo0a0d6202014-04-17 22:33:50 +0000465 if (!Val)
Reid Klecknerdefbd1f2015-08-05 22:26:20 +0000466 return 0;
467 return cast<ConstantInt>(Val->getValue())->getZExtValue();
468}
469
470unsigned Module::getCodeViewFlag() const {
471 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
472 if (!Val)
473 return 0;
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000474 return cast<ConstantInt>(Val->getValue())->getZExtValue();
Diego Novillo0a0d6202014-04-17 22:33:50 +0000475}
David Majnemerc8a11692014-06-27 18:19:56 +0000476
Jessica Paquette849da552018-05-18 17:26:39 +0000477unsigned Module::getInstructionCount() {
478 unsigned NumInstrs = 0;
479 for (Function &F : FunctionList)
480 NumInstrs += F.getInstructionCount();
481 return NumInstrs;
482}
483
David Majnemerc8a11692014-06-27 18:19:56 +0000484Comdat *Module::getOrInsertComdat(StringRef Name) {
David Blaikie1d4f28c2014-11-19 05:49:42 +0000485 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
David Majnemerc8a11692014-06-27 18:19:56 +0000486 Entry.second.Name = &Entry;
487 return &Entry.second;
488}
Justin Hibbits893f22f2014-11-07 04:46:10 +0000489
490PICLevel::Level Module::getPICLevel() const {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000491 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
Justin Hibbits893f22f2014-11-07 04:46:10 +0000492
Hans Wennborg4d651e42015-10-06 23:24:35 +0000493 if (!Val)
Davide Italianod2e71962016-06-17 18:07:14 +0000494 return PICLevel::NotPIC;
Justin Hibbits893f22f2014-11-07 04:46:10 +0000495
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000496 return static_cast<PICLevel::Level>(
497 cast<ConstantInt>(Val->getValue())->getZExtValue());
Justin Hibbits893f22f2014-11-07 04:46:10 +0000498}
499
500void Module::setPICLevel(PICLevel::Level PL) {
Teresa Johnson1fd5bb92017-05-23 00:08:00 +0000501 addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
Justin Hibbits893f22f2014-11-07 04:46:10 +0000502}
Easwaran Raman52c4f7d2015-12-03 20:57:37 +0000503
Sriraman Tallamd41672f2016-04-28 18:15:44 +0000504PIELevel::Level Module::getPIELevel() const {
505 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
506
507 if (!Val)
508 return PIELevel::Default;
509
510 return static_cast<PIELevel::Level>(
511 cast<ConstantInt>(Val->getValue())->getZExtValue());
512}
513
514void Module::setPIELevel(PIELevel::Level PL) {
Teresa Johnson1fd5bb92017-05-23 00:08:00 +0000515 addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
Sriraman Tallamd41672f2016-04-28 18:15:44 +0000516}
517
Caroline Ticea53c5202018-09-21 18:41:31 +0000518Optional<CodeModel::Model> Module::getCodeModel() const {
519 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
520
521 if (!Val)
522 return None;
523
524 return static_cast<CodeModel::Model>(
525 cast<ConstantInt>(Val->getValue())->getZExtValue());
526}
527
528void Module::setCodeModel(CodeModel::Model CL) {
529 // Linking object files with different code models is undefined behavior
530 // because the compiler would have to generate additional code (to span
531 // longer jumps) if a larger code model is used with a smaller one.
532 // Therefore we will treat attempts to mix code models as an error.
533 addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
534}
535
Easwaran Ramanaf640bf2016-03-18 21:29:30 +0000536void Module::setProfileSummary(Metadata *M) {
537 addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
538}
539
540Metadata *Module::getProfileSummary() {
541 return getModuleFlag("ProfileSummary");
542}
Teresa Johnson89c5c632016-04-20 14:39:45 +0000543
Peter Collingbourne5498e182016-11-08 06:03:43 +0000544void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
545 OwnedMemoryBuffer = std::move(MB);
546}
547
Sriraman Tallam11fc5bb2018-02-23 21:32:06 +0000548bool Module::getRtLibUseGOT() const {
549 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
550 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
551}
552
553void Module::setRtLibUseGOT() {
554 addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
555}
556
Alex Lorenz6592c092018-12-14 01:14:10 +0000557void Module::setSDKVersion(const VersionTuple &V) {
558 SmallVector<unsigned, 3> Entries;
559 Entries.push_back(V.getMajor());
560 if (auto Minor = V.getMinor()) {
561 Entries.push_back(*Minor);
562 if (auto Subminor = V.getSubminor())
563 Entries.push_back(*Subminor);
564 // Ignore the 'build' component as it can't be represented in the object
565 // file.
566 }
567 addModuleFlag(ModFlagBehavior::Warning, "SDK Version",
568 ConstantDataArray::get(Context, Entries));
569}
570
571VersionTuple Module::getSDKVersion() const {
572 auto *CM = dyn_cast_or_null<ConstantAsMetadata>(getModuleFlag("SDK Version"));
573 if (!CM)
574 return {};
575 auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
576 if (!Arr)
577 return {};
578 auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> {
579 if (Index >= Arr->getNumElements())
580 return None;
581 return (unsigned)Arr->getElementAsInteger(Index);
582 };
583 auto Major = getVersionComponent(0);
584 if (!Major)
585 return {};
586 VersionTuple Result = VersionTuple(*Major);
587 if (auto Minor = getVersionComponent(1)) {
588 Result = VersionTuple(*Major, *Minor);
589 if (auto Subminor = getVersionComponent(2)) {
590 Result = VersionTuple(*Major, *Minor, *Subminor);
591 }
592 }
593 return Result;
594}
595
Teresa Johnson89c5c632016-04-20 14:39:45 +0000596GlobalVariable *llvm::collectUsedGlobalVariables(
597 const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
598 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
599 GlobalVariable *GV = M.getGlobalVariable(Name);
600 if (!GV || !GV->hasInitializer())
601 return GV;
602
603 const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
604 for (Value *Op : Init->operands()) {
605 GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
606 Set.insert(G);
607 }
608 return GV;
609}