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