IR: MDNode => Value: Add Instruction::getMDNode()
[oota-llvm.git] / lib / IR / Module.cpp
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
14 #include "llvm/IR/Module.h"
15 #include "SymbolTableListTraitsImpl.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/GVMaterializer.h"
23 #include "llvm/IR/InstrTypes.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/LeakDetector.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/RandomNumberGenerator.h"
29 #include <algorithm>
30 #include <cstdarg>
31 #include <cstdlib>
32 using namespace llvm;
33
34 //===----------------------------------------------------------------------===//
35 // Methods to implement the globals and functions lists.
36 //
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, Module>;
41 template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
42 template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
43
44 //===----------------------------------------------------------------------===//
45 // Primitive Module methods.
46 //
47
48 Module::Module(StringRef MID, LLVMContext &C)
49     : Context(C), Materializer(), ModuleID(MID), RNG(nullptr), DL("") {
50   ValSymTab = new ValueSymbolTable();
51   NamedMDSymTab = new StringMap<NamedMDNode *>();
52   Context.addModule(this);
53 }
54
55 Module::~Module() {
56   Context.removeModule(this);
57   dropAllReferences();
58   GlobalList.clear();
59   FunctionList.clear();
60   AliasList.clear();
61   NamedMDList.clear();
62   delete ValSymTab;
63   delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
64   delete RNG;
65 }
66
67 /// getNamedValue - Return the first global value in the module with
68 /// the specified name, of arbitrary type.  This method returns null
69 /// if a global with the specified name is not found.
70 GlobalValue *Module::getNamedValue(StringRef Name) const {
71   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
72 }
73
74 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
75 /// This ID is uniqued across modules in the current LLVMContext.
76 unsigned Module::getMDKindID(StringRef Name) const {
77   return Context.getMDKindID(Name);
78 }
79
80 /// getMDKindNames - Populate client supplied SmallVector with the name for
81 /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
82 /// so it is filled in as an empty string.
83 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
84   return Context.getMDKindNames(Result);
85 }
86
87
88 //===----------------------------------------------------------------------===//
89 // Methods for easy access to the functions in the module.
90 //
91
92 // getOrInsertFunction - Look up the specified function in the module symbol
93 // table.  If it does not exist, add a prototype for the function and return
94 // it.  This is nice because it allows most passes to get away with not handling
95 // the symbol table directly for this common task.
96 //
97 Constant *Module::getOrInsertFunction(StringRef Name,
98                                       FunctionType *Ty,
99                                       AttributeSet AttributeList) {
100   // See if we have a definition for the specified function already.
101   GlobalValue *F = getNamedValue(Name);
102   if (!F) {
103     // Nope, add it
104     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
105     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
106       New->setAttributes(AttributeList);
107     FunctionList.push_back(New);
108     return New;                    // Return the new prototype.
109   }
110
111   // If the function exists but has the wrong type, return a bitcast to the
112   // right type.
113   if (F->getType() != PointerType::getUnqual(Ty))
114     return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
115
116   // Otherwise, we just found the existing function or a prototype.
117   return F;
118 }
119
120 Constant *Module::getOrInsertFunction(StringRef Name,
121                                       FunctionType *Ty) {
122   return getOrInsertFunction(Name, Ty, AttributeSet());
123 }
124
125 // getOrInsertFunction - Look up the specified function in the module symbol
126 // table.  If it does not exist, add a prototype for the function and return it.
127 // This version of the method takes a null terminated list of function
128 // arguments, which makes it easier for clients to use.
129 //
130 Constant *Module::getOrInsertFunction(StringRef Name,
131                                       AttributeSet AttributeList,
132                                       Type *RetTy, ...) {
133   va_list Args;
134   va_start(Args, RetTy);
135
136   // Build the list of argument types...
137   std::vector<Type*> ArgTys;
138   while (Type *ArgTy = va_arg(Args, Type*))
139     ArgTys.push_back(ArgTy);
140
141   va_end(Args);
142
143   // Build the function type and chain to the other getOrInsertFunction...
144   return getOrInsertFunction(Name,
145                              FunctionType::get(RetTy, ArgTys, false),
146                              AttributeList);
147 }
148
149 Constant *Module::getOrInsertFunction(StringRef Name,
150                                       Type *RetTy, ...) {
151   va_list Args;
152   va_start(Args, RetTy);
153
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
159   va_end(Args);
160
161   // Build the function type and chain to the other getOrInsertFunction...
162   return getOrInsertFunction(Name,
163                              FunctionType::get(RetTy, ArgTys, false),
164                              AttributeSet());
165 }
166
167 // getFunction - Look up the specified function in the module symbol table.
168 // If it does not exist, return null.
169 //
170 Function *Module::getFunction(StringRef Name) const {
171   return dyn_cast_or_null<Function>(getNamedValue(Name));
172 }
173
174 //===----------------------------------------------------------------------===//
175 // Methods for easy access to the global variables in the module.
176 //
177
178 /// getGlobalVariable - Look up the specified global variable in the module
179 /// symbol table.  If it does not exist, return null.  The type argument
180 /// should be the underlying type of the global, i.e., it should not have
181 /// the top-level PointerType, which represents the address of the global.
182 /// If AllowLocal is set to true, this function will return types that
183 /// have an local. By default, these types are not returned.
184 ///
185 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
186   if (GlobalVariable *Result =
187       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
188     if (AllowLocal || !Result->hasLocalLinkage())
189       return Result;
190   return nullptr;
191 }
192
193 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
194 ///   1. If it does not exist, add a declaration of the global and return it.
195 ///   2. Else, the global exists but has the wrong type: return the function
196 ///      with a constantexpr cast to the right type.
197 ///   3. Finally, if the existing global is the correct declaration, return the
198 ///      existing global.
199 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
200   // See if we have a definition for the specified global already.
201   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
202   if (!GV) {
203     // Nope, add it
204     GlobalVariable *New =
205       new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
206                          nullptr, Name);
207      return New;                    // Return the new declaration.
208   }
209
210   // If the variable exists but has the wrong type, return a bitcast to the
211   // right type.
212   Type *GVTy = GV->getType();
213   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
214   if (GVTy != PTy)
215     return ConstantExpr::getBitCast(GV, PTy);
216
217   // Otherwise, we just found the existing function or a prototype.
218   return GV;
219 }
220
221 //===----------------------------------------------------------------------===//
222 // Methods for easy access to the global variables in the module.
223 //
224
225 // getNamedAlias - Look up the specified global in the module symbol table.
226 // If it does not exist, return null.
227 //
228 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
229   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
230 }
231
232 /// getNamedMetadata - Return the first NamedMDNode in the module with the
233 /// specified name. This method returns null if a NamedMDNode with the
234 /// specified name is not found.
235 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
236   SmallString<256> NameData;
237   StringRef NameRef = Name.toStringRef(NameData);
238   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
239 }
240
241 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
242 /// with the specified name. This method returns a new NamedMDNode if a
243 /// NamedMDNode with the specified name is not found.
244 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
245   NamedMDNode *&NMD =
246     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
247   if (!NMD) {
248     NMD = new NamedMDNode(Name);
249     NMD->setParent(this);
250     NamedMDList.push_back(NMD);
251   }
252   return NMD;
253 }
254
255 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
256 /// delete it.
257 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
258   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
259   NamedMDList.erase(NMD);
260 }
261
262 bool Module::isValidModFlagBehavior(Value *V, ModFlagBehavior &MFB) {
263   if (ConstantInt *Behavior = dyn_cast<ConstantInt>(V)) {
264     uint64_t Val = Behavior->getLimitedValue();
265     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
266       MFB = static_cast<ModFlagBehavior>(Val);
267       return true;
268     }
269   }
270   return false;
271 }
272
273 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
274 void Module::
275 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
276   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
277   if (!ModFlags) return;
278
279   for (const MDNode *Flag : ModFlags->operands()) {
280     ModFlagBehavior MFB;
281     if (Flag->getNumOperands() >= 3 &&
282         isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
283         isa<MDString>(Flag->getOperand(1))) {
284       // Check the operands of the MDNode before accessing the operands.
285       // The verifier will actually catch these failures.
286       MDString *Key = cast<MDString>(Flag->getOperand(1));
287       Value *Val = Flag->getOperand(2);
288       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
289     }
290   }
291 }
292
293 /// Return the corresponding value if Key appears in module flags, otherwise
294 /// return null.
295 Value *Module::getModuleFlag(StringRef Key) const {
296   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
297   getModuleFlagsMetadata(ModuleFlags);
298   for (const ModuleFlagEntry &MFE : ModuleFlags) {
299     if (Key == MFE.Key->getString())
300       return MFE.Val;
301   }
302   return nullptr;
303 }
304
305 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
306 /// represents module-level flags. This method returns null if there are no
307 /// module-level flags.
308 NamedMDNode *Module::getModuleFlagsMetadata() const {
309   return getNamedMetadata("llvm.module.flags");
310 }
311
312 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
313 /// represents module-level flags. If module-level flags aren't found, it
314 /// creates the named metadata that contains them.
315 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
316   return getOrInsertNamedMetadata("llvm.module.flags");
317 }
318
319 /// addModuleFlag - Add a module-level flag to the module-level flags
320 /// metadata. It will create the module-level flags named metadata if it doesn't
321 /// already exist.
322 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
323                            Value *Val) {
324   Type *Int32Ty = Type::getInt32Ty(Context);
325   Value *Ops[3] = {
326     ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
327   };
328   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
329 }
330 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
331                            uint32_t Val) {
332   Type *Int32Ty = Type::getInt32Ty(Context);
333   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
334 }
335 void Module::addModuleFlag(MDNode *Node) {
336   assert(Node->getNumOperands() == 3 &&
337          "Invalid number of operands for module flag!");
338   assert(isa<ConstantInt>(Node->getOperand(0)) &&
339          isa<MDString>(Node->getOperand(1)) &&
340          "Invalid operand types for module flag!");
341   getOrInsertModuleFlagsMetadata()->addOperand(Node);
342 }
343
344 void Module::setDataLayout(StringRef Desc) {
345   DL.reset(Desc);
346
347   if (Desc.empty()) {
348     DataLayoutStr = "";
349   } else {
350     DataLayoutStr = DL.getStringRepresentation();
351     // DataLayoutStr is now equivalent to Desc, but since the representation
352     // is not unique, they may not be identical.
353   }
354 }
355
356 void Module::setDataLayout(const DataLayout *Other) {
357   if (!Other) {
358     DataLayoutStr = "";
359     DL.reset("");
360   } else {
361     DL = *Other;
362     DataLayoutStr = DL.getStringRepresentation();
363   }
364 }
365
366 const DataLayout *Module::getDataLayout() const {
367   if (DataLayoutStr.empty())
368     return nullptr;
369   return &DL;
370 }
371
372 // We want reproducible builds, but ModuleID may be a full path so we just use
373 // the filename to salt the RNG (although it is not guaranteed to be unique).
374 RandomNumberGenerator &Module::getRNG() const {
375   if (RNG == nullptr) {
376     StringRef Salt = sys::path::filename(ModuleID);
377     RNG = new RandomNumberGenerator(Salt);
378   }
379   return *RNG;
380 }
381
382 //===----------------------------------------------------------------------===//
383 // Methods to control the materialization of GlobalValues in the Module.
384 //
385 void Module::setMaterializer(GVMaterializer *GVM) {
386   assert(!Materializer &&
387          "Module already has a GVMaterializer.  Call MaterializeAllPermanently"
388          " to clear it out before setting another one.");
389   Materializer.reset(GVM);
390 }
391
392 bool Module::isDematerializable(const GlobalValue *GV) const {
393   if (Materializer)
394     return Materializer->isDematerializable(GV);
395   return false;
396 }
397
398 std::error_code Module::materialize(GlobalValue *GV) {
399   if (!Materializer)
400     return std::error_code();
401
402   return Materializer->materialize(GV);
403 }
404
405 void Module::Dematerialize(GlobalValue *GV) {
406   if (Materializer)
407     return Materializer->Dematerialize(GV);
408 }
409
410 std::error_code Module::materializeAll() {
411   if (!Materializer)
412     return std::error_code();
413   return Materializer->MaterializeModule(this);
414 }
415
416 std::error_code Module::materializeAllPermanently() {
417   if (std::error_code EC = materializeAll())
418     return EC;
419
420   Materializer.reset();
421   return std::error_code();
422 }
423
424 //===----------------------------------------------------------------------===//
425 // Other module related stuff.
426 //
427
428
429 // dropAllReferences() - This function causes all the subelements to "let go"
430 // of all references that they are maintaining.  This allows one to 'delete' a
431 // whole module at a time, even though there may be circular references... first
432 // all references are dropped, and all use counts go to zero.  Then everything
433 // is deleted for real.  Note that no operations are valid on an object that
434 // has "dropped all references", except operator delete.
435 //
436 void Module::dropAllReferences() {
437   for (Function &F : *this)
438     F.dropAllReferences();
439
440   for (GlobalVariable &GV : globals())
441     GV.dropAllReferences();
442
443   for (GlobalAlias &GA : aliases())
444     GA.dropAllReferences();
445 }
446
447 unsigned Module::getDwarfVersion() const {
448   Value *Val = getModuleFlag("Dwarf Version");
449   if (!Val)
450     return dwarf::DWARF_VERSION;
451   return cast<ConstantInt>(Val)->getZExtValue();
452 }
453
454 Comdat *Module::getOrInsertComdat(StringRef Name) {
455   Comdat C;
456   StringMapEntry<Comdat> &Entry =
457       ComdatSymTab.GetOrCreateValue(Name, std::move(C));
458   Entry.second.Name = &Entry;
459   return &Entry.second;
460 }