DebugInfo: Remove DICompositeType mutation API
[oota-llvm.git] / include / llvm / IR / DebugInfo.h
1 //===- DebugInfo.h - Debug Information Helpers ------------------*- C++ -*-===//
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 defines a bunch of datatypes that are useful for creating and
11 // walking debug info in LLVM IR form. They essentially provide wrappers around
12 // the information in the global variables that's needed when constructing the
13 // DWARF information.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #ifndef LLVM_IR_DEBUGINFO_H
18 #define LLVM_IR_DEBUGINFO_H
19
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/iterator_range.h"
25 #include "llvm/IR/DebugInfoMetadata.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include <iterator>
30
31 namespace llvm {
32 class BasicBlock;
33 class Constant;
34 class Function;
35 class GlobalVariable;
36 class Module;
37 class Type;
38 class Value;
39 class DbgDeclareInst;
40 class DbgValueInst;
41 class Instruction;
42 class Metadata;
43 class MDNode;
44 class MDString;
45 class NamedMDNode;
46 class LLVMContext;
47 class raw_ostream;
48
49 class DIFile;
50 class DISubprogram;
51 class DILexicalBlock;
52 class DILexicalBlockFile;
53 class DIVariable;
54 class DIType;
55 class DIScope;
56 class DIObjCProperty;
57
58 /// \brief Maps from type identifier to the actual MDNode.
59 typedef DenseMap<const MDString *, MDNode *> DITypeIdentifierMap;
60
61 /// \brief A thin wraper around MDNode to access encoded debug info.
62 ///
63 /// This should not be stored in a container, because the underlying MDNode may
64 /// change in certain situations.
65 class DIDescriptor {
66   // Befriends DIRef so DIRef can befriend the protected member
67   // function: getFieldAs<DIRef>.
68   template <typename T> friend class DIRef;
69
70 public:
71   /// \brief Duplicated debug info flags.
72   ///
73   /// \see DebugNode::DIFlags.
74   enum {
75 #define HANDLE_DI_FLAG(ID, NAME) Flag##NAME = DebugNode::Flag##NAME,
76 #include "llvm/IR/DebugInfoFlags.def"
77     FlagAccessibility = DebugNode::FlagAccessibility
78   };
79
80 protected:
81   const MDNode *DbgNode;
82
83   DIDescriptor getDescriptorField(unsigned Elt) const;
84   template <typename DescTy> DescTy getFieldAs(unsigned Elt) const {
85     return DescTy(getDescriptorField(Elt));
86   }
87
88 public:
89   explicit DIDescriptor(const MDNode *N = nullptr) : DbgNode(N) {}
90
91   MDNode *get() const { return const_cast<MDNode *>(DbgNode); }
92   operator MDNode *() const { return get(); }
93   MDNode *operator->() const { return get(); }
94   MDNode &operator*() const {
95     assert(get() && "Expected valid pointer");
96     return *get();
97   }
98
99   // An explicit operator bool so that we can do testing of DI values
100   // easily.
101   // FIXME: This operator bool isn't actually protecting anything at the
102   // moment due to the conversion operator above making DIDescriptor nodes
103   // implicitly convertable to bool.
104   explicit operator bool() const { return DbgNode != nullptr; }
105
106   bool operator==(DIDescriptor Other) const { return DbgNode == Other.DbgNode; }
107   bool operator!=(DIDescriptor Other) const { return !operator==(Other); }
108
109   uint16_t getTag() const {
110     if (auto *N = dyn_cast_or_null<DebugNode>(get()))
111       return N->getTag();
112     return 0;
113   }
114
115   void print(raw_ostream &OS) const;
116   void dump() const;
117
118   /// \brief Replace all uses of debug info referenced by this descriptor.
119   void replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D);
120   void replaceAllUsesWith(MDNode *D);
121 };
122
123 #define DECLARE_SIMPLIFY_DESCRIPTOR(DESC)                                      \
124   class DESC;                                                                  \
125   template <> struct simplify_type<const DESC>;                                \
126   template <> struct simplify_type<DESC>;
127 DECLARE_SIMPLIFY_DESCRIPTOR(DIDescriptor)
128 DECLARE_SIMPLIFY_DESCRIPTOR(DISubrange)
129 DECLARE_SIMPLIFY_DESCRIPTOR(DIEnumerator)
130 DECLARE_SIMPLIFY_DESCRIPTOR(DIScope)
131 DECLARE_SIMPLIFY_DESCRIPTOR(DIType)
132 DECLARE_SIMPLIFY_DESCRIPTOR(DIBasicType)
133 DECLARE_SIMPLIFY_DESCRIPTOR(DIDerivedType)
134 DECLARE_SIMPLIFY_DESCRIPTOR(DICompositeType)
135 DECLARE_SIMPLIFY_DESCRIPTOR(DISubroutineType)
136 DECLARE_SIMPLIFY_DESCRIPTOR(DIFile)
137 DECLARE_SIMPLIFY_DESCRIPTOR(DICompileUnit)
138 DECLARE_SIMPLIFY_DESCRIPTOR(DISubprogram)
139 DECLARE_SIMPLIFY_DESCRIPTOR(DILexicalBlock)
140 DECLARE_SIMPLIFY_DESCRIPTOR(DILexicalBlockFile)
141 DECLARE_SIMPLIFY_DESCRIPTOR(DINameSpace)
142 DECLARE_SIMPLIFY_DESCRIPTOR(DITemplateTypeParameter)
143 DECLARE_SIMPLIFY_DESCRIPTOR(DITemplateValueParameter)
144 DECLARE_SIMPLIFY_DESCRIPTOR(DIGlobalVariable)
145 DECLARE_SIMPLIFY_DESCRIPTOR(DIVariable)
146 DECLARE_SIMPLIFY_DESCRIPTOR(DIExpression)
147 DECLARE_SIMPLIFY_DESCRIPTOR(DILocation)
148 DECLARE_SIMPLIFY_DESCRIPTOR(DIObjCProperty)
149 DECLARE_SIMPLIFY_DESCRIPTOR(DIImportedEntity)
150 #undef DECLARE_SIMPLIFY_DESCRIPTOR
151
152 /// \brief This is used to represent ranges, for array bounds.
153 class DISubrange : public DIDescriptor {
154 public:
155   DISubrange() = default;
156   DISubrange(const MDSubrange *N) : DIDescriptor(N) {}
157
158   MDSubrange *get() const {
159     return cast_or_null<MDSubrange>(DIDescriptor::get());
160   }
161   operator MDSubrange *() const { return get(); }
162   MDSubrange *operator->() const { return get(); }
163   MDSubrange &operator*() const {
164     assert(get() && "Expected valid pointer");
165     return *get();
166   }
167
168   int64_t getLo() const { return get()->getLowerBound(); }
169   int64_t getCount() const { return get()->getCount(); }
170 };
171
172 /// \brief This descriptor holds an array of nodes with type T.
173 template <typename T> class DITypedArray : public DIDescriptor {
174 public:
175   explicit DITypedArray(const MDNode *N = nullptr) : DIDescriptor(N) {}
176   operator MDTuple *() const {
177     return const_cast<MDTuple *>(cast_or_null<MDTuple>(DbgNode));
178   }
179   unsigned getNumElements() const {
180     return DbgNode ? DbgNode->getNumOperands() : 0;
181   }
182   T getElement(unsigned Idx) const { return getFieldAs<T>(Idx); }
183 };
184
185 typedef DITypedArray<DIDescriptor> DIArray;
186
187 /// \brief A wrapper for an enumerator (e.g. X and Y in 'enum {X,Y}').
188 ///
189 /// FIXME: it seems strange that this doesn't have either a reference to the
190 /// type/precision or a file/line pair for location info.
191 class DIEnumerator : public DIDescriptor {
192 public:
193   DIEnumerator() = default;
194   DIEnumerator(const MDEnumerator *N) : DIDescriptor(N) {}
195
196   MDEnumerator *get() const {
197     return cast_or_null<MDEnumerator>(DIDescriptor::get());
198   }
199   operator MDEnumerator *() const { return get(); }
200   MDEnumerator *operator->() const { return get(); }
201   MDEnumerator &operator*() const {
202     assert(get() && "Expected valid pointer");
203     return *get();
204   }
205
206   StringRef getName() const { return get()->getName(); }
207   int64_t getEnumValue() const { return get()->getValue(); }
208 };
209
210 template <typename T> class DIRef;
211 typedef DIRef<DIDescriptor> DIDescriptorRef;
212 typedef DIRef<DIScope> DIScopeRef;
213 typedef DIRef<DIType> DITypeRef;
214 typedef DITypedArray<DITypeRef> DITypeArray;
215
216 /// \brief A base class for various scopes.
217 ///
218 /// Although, implementation-wise, DIScope is the parent class of most
219 /// other DIxxx classes, including DIType and its descendants, most of
220 /// DIScope's descendants are not a substitutable subtype of
221 /// DIScope. The DIDescriptor::isScope() method only is true for
222 /// DIScopes that are scopes in the strict lexical scope sense
223 /// (DICompileUnit, DISubprogram, etc.), but not for, e.g., a DIType.
224 class DIScope : public DIDescriptor {
225 public:
226   DIScope() = default;
227   DIScope(const MDScope *N) : DIDescriptor(N) {}
228
229   MDScope *get() const { return cast_or_null<MDScope>(DIDescriptor::get()); }
230   operator MDScope *() const { return get(); }
231   MDScope *operator->() const { return get(); }
232   MDScope &operator*() const {
233     assert(get() && "Expected valid pointer");
234     return *get();
235   }
236
237   /// \brief Get the parent scope.
238   ///
239   /// Gets the parent scope for this scope node or returns a default
240   /// constructed scope.
241   DIScopeRef getContext() const;
242   /// \brief Get the scope name.
243   ///
244   /// If the scope node has a name, return that, else return an empty string.
245   StringRef getName() const;
246   StringRef getFilename() const;
247   StringRef getDirectory() const;
248
249   /// \brief Generate a reference to this DIScope.
250   ///
251   /// Uses the type identifier instead of the actual MDNode if possible, to
252   /// help type uniquing.
253   DIScopeRef getRef() const;
254 };
255
256 /// \brief Represents reference to a DIDescriptor.
257 ///
258 /// Abstracts over direct and identifier-based metadata references.
259 template <typename T> class DIRef {
260   template <typename DescTy>
261   friend DescTy DIDescriptor::getFieldAs(unsigned Elt) const;
262   friend DIScopeRef DIScope::getContext() const;
263   friend DIScopeRef DIScope::getRef() const;
264   friend class DIType;
265
266   /// \brief Val can be either a MDNode or a MDString.
267   ///
268   /// In the latter, MDString specifies the type identifier.
269   const Metadata *Val;
270   explicit DIRef(const Metadata *V);
271
272 public:
273   template <class U>
274   DIRef(const TypedDebugNodeRef<U> &Ref,
275         typename std::enable_if<std::is_convertible<U *, T>::value>::type * =
276             nullptr)
277       : Val(Ref) {}
278
279   T resolve(const DITypeIdentifierMap &Map) const;
280   operator Metadata *() const { return const_cast<Metadata *>(Val); }
281
282   static DIRef get(const Metadata *MD) { return DIRef(MD); }
283 };
284
285 template <>
286 DIDescriptor DIRef<DIDescriptor>::resolve(const DITypeIdentifierMap &Map) const;
287 template <>
288 DIScope DIRef<DIScope>::resolve(const DITypeIdentifierMap &Map) const;
289 template <> DIType DIRef<DIType>::resolve(const DITypeIdentifierMap &Map) const;
290
291 /// \brief Handle fields that are references to DIDescriptors.
292 template <>
293 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const;
294 /// \brief Specialize DIRef constructor for DIDescriptorRef.
295 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V);
296
297 /// \brief Handle fields that are references to DIScopes.
298 template <> DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const;
299 /// \brief Specialize DIRef constructor for DIScopeRef.
300 template <> DIRef<DIScope>::DIRef(const Metadata *V);
301
302 /// \brief Handle fields that are references to DITypes.
303 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const;
304 /// \brief Specialize DIRef constructor for DITypeRef.
305 template <> DIRef<DIType>::DIRef(const Metadata *V);
306
307 /// \brief This is a wrapper for a type.
308 ///
309 /// FIXME: Types should be factored much better so that CV qualifiers and
310 /// others do not require a huge and empty descriptor full of zeros.
311 class DIType : public DIScope {
312 public:
313   DIType() = default;
314   DIType(const MDType *N) : DIScope(N) {}
315
316   MDType *get() const { return cast_or_null<MDType>(DIDescriptor::get()); }
317   operator MDType *() const { return get(); }
318   MDType *operator->() const { return get(); }
319   MDType &operator*() const {
320     assert(get() && "Expected valid pointer");
321     return *get();
322   }
323
324   DIScopeRef getContext() const { return DIScopeRef::get(get()->getScope()); }
325   StringRef getName() const { return get()->getName(); }
326   unsigned getLineNumber() const { return get()->getLine(); }
327   uint64_t getSizeInBits() const { return get()->getSizeInBits(); }
328   uint64_t getAlignInBits() const { return get()->getAlignInBits(); }
329   // FIXME: Offset is only used for DW_TAG_member nodes.  Making every type
330   // carry this is just plain insane.
331   uint64_t getOffsetInBits() const { return get()->getOffsetInBits(); }
332   unsigned getFlags() const { return get()->getFlags(); }
333
334   bool isPrivate() const { return get()->isPrivate(); }
335   bool isProtected() const { return get()->isProtected(); }
336   bool isPublic() const { return get()->isPublic(); }
337   bool isForwardDecl() const { return get()->isForwardDecl(); }
338   bool isAppleBlockExtension() const { return get()->isAppleBlockExtension(); }
339   bool isBlockByrefStruct() const { return get()->isBlockByrefStruct(); }
340   bool isVirtual() const { return get()->isVirtual(); }
341   bool isArtificial() const { return get()->isArtificial(); }
342   bool isObjectPointer() const { return get()->isObjectPointer(); }
343   bool isObjcClassComplete() const { return get()->isObjcClassComplete(); }
344   bool isVector() const { return get()->isVector(); }
345   bool isStaticMember() const { return get()->isStaticMember(); }
346   bool isLValueReference() const { return get()->isLValueReference(); }
347   bool isRValueReference() const { return get()->isRValueReference(); }
348
349   bool isValid() const { return DbgNode && isa<MDType>(*this); }
350 };
351
352 /// \brief A basic type, like 'int' or 'float'.
353 class DIBasicType : public DIType {
354 public:
355   DIBasicType() = default;
356   DIBasicType(const MDBasicType *N) : DIType(N) {}
357
358   MDBasicType *get() const {
359     return cast_or_null<MDBasicType>(DIDescriptor::get());
360   }
361   operator MDBasicType *() const { return get(); }
362   MDBasicType *operator->() const { return get(); }
363   MDBasicType &operator*() const {
364     assert(get() && "Expected valid pointer");
365     return *get();
366   }
367
368   unsigned getEncoding() const { return get()->getEncoding(); }
369 };
370
371 /// \brief A simple derived type
372 ///
373 /// Like a const qualified type, a typedef, a pointer or reference, et cetera.
374 /// Or, a data member of a class/struct/union.
375 class DIDerivedType : public DIType {
376 public:
377   DIDerivedType() = default;
378   DIDerivedType(const MDDerivedTypeBase *N) : DIType(N) {}
379
380   MDDerivedTypeBase *get() const {
381     return cast_or_null<MDDerivedTypeBase>(DIDescriptor::get());
382   }
383   operator MDDerivedTypeBase *() const { return get(); }
384   MDDerivedTypeBase *operator->() const { return get(); }
385   MDDerivedTypeBase &operator*() const {
386     assert(get() && "Expected valid pointer");
387     return *get();
388   }
389
390   DITypeRef getTypeDerivedFrom() const {
391     return DITypeRef::get(get()->getBaseType());
392   }
393
394   /// \brief Return property node, if this ivar is associated with one.
395   MDNode *getObjCProperty() const {
396     if (auto *N = dyn_cast<MDDerivedType>(get()))
397       return dyn_cast_or_null<MDNode>(N->getExtraData());
398     return nullptr;
399   }
400
401   DITypeRef getClassType() const {
402     assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
403     if (auto *N = dyn_cast<MDDerivedType>(get()))
404       return DITypeRef::get(N->getExtraData());
405     return DITypeRef::get(nullptr);
406   }
407
408   Constant *getConstant() const {
409     assert((getTag() == dwarf::DW_TAG_member) && isStaticMember());
410     if (auto *N = dyn_cast<MDDerivedType>(get()))
411       if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getExtraData()))
412         return C->getValue();
413
414     return nullptr;
415   }
416 };
417
418 /// \brief Types that refer to multiple other types.
419 ///
420 /// This descriptor holds a type that can refer to multiple other types, like a
421 /// function or struct.
422 ///
423 /// DICompositeType is derived from DIDerivedType because some
424 /// composite types (such as enums) can be derived from basic types
425 // FIXME: Make this derive from DIType directly & just store the
426 // base type in a single DIType field.
427 class DICompositeType : public DIDerivedType {
428   friend class DIBuilder;
429
430 public:
431   DICompositeType() = default;
432   DICompositeType(const MDCompositeTypeBase *N) : DIDerivedType(N) {}
433
434   MDCompositeTypeBase *get() const {
435     return cast_or_null<MDCompositeTypeBase>(DIDescriptor::get());
436   }
437   operator MDCompositeTypeBase *() const { return get(); }
438   MDCompositeTypeBase *operator->() const { return get(); }
439   MDCompositeTypeBase &operator*() const {
440     assert(get() && "Expected valid pointer");
441     return *get();
442   }
443
444   DIArray getElements() const {
445     assert(!isa<MDSubroutineType>(*this) && "no elements for DISubroutineType");
446     return DIArray(get()->getElements());
447   }
448
449   unsigned getRunTimeLang() const { return get()->getRuntimeLang(); }
450   DITypeRef getContainingType() const {
451     return DITypeRef::get(get()->getVTableHolder());
452   }
453
454   DIArray getTemplateParams() const {
455     return DIArray(get()->getTemplateParams());
456   }
457   MDString *getIdentifier() const { return get()->getRawIdentifier(); }
458 };
459
460 class DISubroutineType : public DICompositeType {
461 public:
462   DISubroutineType() = default;
463   DISubroutineType(const MDSubroutineType *N) : DICompositeType(N) {}
464
465   MDSubroutineType *get() const {
466     return cast_or_null<MDSubroutineType>(DIDescriptor::get());
467   }
468   operator MDSubroutineType *() const { return get(); }
469   MDSubroutineType *operator->() const { return get(); }
470   MDSubroutineType &operator*() const {
471     assert(get() && "Expected valid pointer");
472     return *get();
473   }
474
475   DITypedArray<DITypeRef> getTypeArray() const {
476     return DITypedArray<DITypeRef>(get()->getTypeArray());
477   }
478 };
479
480 /// \brief This is a wrapper for a file.
481 class DIFile : public DIScope {
482 public:
483   DIFile() = default;
484   DIFile(const MDFile *N) : DIScope(N) {}
485
486   MDFile *get() const { return cast_or_null<MDFile>(DIDescriptor::get()); }
487   operator MDFile *() const { return get(); }
488   MDFile *operator->() const { return get(); }
489   MDFile &operator*() const {
490     assert(get() && "Expected valid pointer");
491     return *get();
492   }
493
494   /// \brief Retrieve the MDNode for the directory/file pair.
495   MDNode *getFileNode() const { return get(); }
496 };
497
498 /// \brief A wrapper for a compile unit.
499 class DICompileUnit : public DIScope {
500 public:
501   DICompileUnit() = default;
502   DICompileUnit(const MDCompileUnit *N) : DIScope(N) {}
503
504   MDCompileUnit *get() const {
505     return cast_or_null<MDCompileUnit>(DIDescriptor::get());
506   }
507   operator MDCompileUnit *() const { return get(); }
508   MDCompileUnit *operator->() const { return get(); }
509   MDCompileUnit &operator*() const {
510     assert(get() && "Expected valid pointer");
511     return *get();
512   }
513
514   dwarf::SourceLanguage getLanguage() const {
515     return static_cast<dwarf::SourceLanguage>(get()->getSourceLanguage());
516   }
517   StringRef getProducer() const { return get()->getProducer(); }
518   bool isOptimized() const { return get()->isOptimized(); }
519   StringRef getFlags() const { return get()->getFlags(); }
520   unsigned getRunTimeVersion() const { return get()->getRuntimeVersion(); }
521
522   DIArray getEnumTypes() const { return DIArray(get()->getEnumTypes()); }
523   DIArray getRetainedTypes() const {
524     return DIArray(get()->getRetainedTypes());
525   }
526   DIArray getSubprograms() const { return DIArray(get()->getSubprograms()); }
527   DIArray getGlobalVariables() const {
528     return DIArray(get()->getGlobalVariables());
529   }
530   DIArray getImportedEntities() const {
531     return DIArray(get()->getImportedEntities());
532   }
533
534   void replaceSubprograms(DIArray Subprograms);
535   void replaceGlobalVariables(DIArray GlobalVariables);
536
537   StringRef getSplitDebugFilename() const {
538     return get()->getSplitDebugFilename();
539   }
540   unsigned getEmissionKind() const { return get()->getEmissionKind(); }
541 };
542
543 /// \brief This is a wrapper for a subprogram (e.g. a function).
544 class DISubprogram : public DIScope {
545 public:
546   DISubprogram() = default;
547   DISubprogram(const MDSubprogram *N) : DIScope(N) {}
548
549   MDSubprogram *get() const {
550     return cast_or_null<MDSubprogram>(DIDescriptor::get());
551   }
552   operator MDSubprogram *() const { return get(); }
553   MDSubprogram *operator->() const { return get(); }
554   MDSubprogram &operator*() const {
555     assert(get() && "Expected valid pointer");
556     return *get();
557   }
558
559   StringRef getName() const { return get()->getName(); }
560   StringRef getDisplayName() const { return get()->getDisplayName(); }
561   StringRef getLinkageName() const { return get()->getLinkageName(); }
562   unsigned getLineNumber() const { return get()->getLine(); }
563
564   /// \brief Check if this is local (like 'static' in C).
565   unsigned isLocalToUnit() const { return get()->isLocalToUnit(); }
566   unsigned isDefinition() const { return get()->isDefinition(); }
567
568   unsigned getVirtuality() const { return get()->getVirtuality(); }
569   unsigned getVirtualIndex() const { return get()->getVirtualIndex(); }
570
571   unsigned getFlags() const { return get()->getFlags(); }
572
573   unsigned isOptimized() const { return get()->isOptimized(); }
574
575   /// \brief Get the beginning of the scope of the function (not the name).
576   unsigned getScopeLineNumber() const { return get()->getScopeLine(); }
577
578   DIScopeRef getContext() const { return DIScopeRef::get(get()->getScope()); }
579   DISubroutineType getType() const {
580     return DISubroutineType(get()->getType());
581   }
582
583   DITypeRef getContainingType() const {
584     return DITypeRef::get(get()->getContainingType());
585   }
586
587   /// \brief Check if this provides debugging information for the function F.
588   bool describes(const Function *F);
589
590   Function *getFunction() const;
591
592   void replaceFunction(Function *F) {
593     if (auto *N = get())
594       N->replaceFunction(F);
595   }
596   DIArray getTemplateParams() const {
597     return DIArray(get()->getTemplateParams());
598   }
599   DISubprogram getFunctionDeclaration() const {
600     return DISubprogram(get()->getDeclaration());
601   }
602   MDNode *getVariablesNodes() const { return getVariables(); }
603   DIArray getVariables() const { return DIArray(get()->getVariables()); }
604
605   unsigned isArtificial() const { return get()->isArtificial(); }
606   bool isPrivate() const { return get()->isPrivate(); }
607   bool isProtected() const { return get()->isProtected(); }
608   bool isPublic() const { return get()->isPublic(); }
609   bool isExplicit() const { return get()->isExplicit(); }
610   bool isPrototyped() const { return get()->isPrototyped(); }
611   unsigned isLValueReference() const { return get()->isLValueReference(); }
612   unsigned isRValueReference() const { return get()->isRValueReference(); }
613 };
614
615 /// \brief This is a wrapper for a lexical block.
616 class DILexicalBlock : public DIScope {
617 public:
618   DILexicalBlock() = default;
619   DILexicalBlock(const MDLexicalBlockBase *N) : DIScope(N) {}
620
621   MDLexicalBlockBase *get() const {
622     return cast_or_null<MDLexicalBlockBase>(DIDescriptor::get());
623   }
624   operator MDLexicalBlockBase *() const { return get(); }
625   MDLexicalBlockBase *operator->() const { return get(); }
626   MDLexicalBlockBase &operator*() const {
627     assert(get() && "Expected valid pointer");
628     return *get();
629   }
630
631   DIScope getContext() const { return DIScope(get()->getScope()); }
632   unsigned getLineNumber() const {
633     if (auto *N = dyn_cast<MDLexicalBlock>(get()))
634       return N->getLine();
635     return 0;
636   }
637   unsigned getColumnNumber() const {
638     if (auto *N = dyn_cast<MDLexicalBlock>(get()))
639       return N->getColumn();
640     return 0;
641   }
642 };
643
644 /// \brief This is a wrapper for a lexical block with a filename change.
645 class DILexicalBlockFile : public DIScope {
646 public:
647   DILexicalBlockFile() = default;
648   DILexicalBlockFile(const MDLexicalBlockFile *N) : DIScope(N) {}
649
650   MDLexicalBlockFile *get() const {
651     return cast_or_null<MDLexicalBlockFile>(DIDescriptor::get());
652   }
653   operator MDLexicalBlockFile *() const { return get(); }
654   MDLexicalBlockFile *operator->() const { return get(); }
655   MDLexicalBlockFile &operator*() const {
656     assert(get() && "Expected valid pointer");
657     return *get();
658   }
659
660   DIScope getContext() const { return get()->getScope(); }
661   unsigned getDiscriminator() const { return get()->getDiscriminator(); }
662 };
663
664 /// \brief A wrapper for a C++ style name space.
665 class DINameSpace : public DIScope {
666 public:
667   DINameSpace() = default;
668   DINameSpace(const MDNamespace *N) : DIScope(N) {}
669
670   MDNamespace *get() const {
671     return cast_or_null<MDNamespace>(DIDescriptor::get());
672   }
673   operator MDNamespace *() const { return get(); }
674   MDNamespace *operator->() const { return get(); }
675   MDNamespace &operator*() const {
676     assert(get() && "Expected valid pointer");
677     return *get();
678   }
679
680   StringRef getName() const { return get()->getName(); }
681   unsigned getLineNumber() const { return get()->getLine(); }
682   DIScope getContext() const { return DIScope(get()->getScope()); }
683 };
684
685 /// \brief This is a wrapper for template type parameter.
686 class DITemplateTypeParameter : public DIDescriptor {
687 public:
688   DITemplateTypeParameter() = default;
689   DITemplateTypeParameter(const MDTemplateTypeParameter *N) : DIDescriptor(N) {}
690
691   MDTemplateTypeParameter *get() const {
692     return cast_or_null<MDTemplateTypeParameter>(DIDescriptor::get());
693   }
694   operator MDTemplateTypeParameter *() const { return get(); }
695   MDTemplateTypeParameter *operator->() const { return get(); }
696   MDTemplateTypeParameter &operator*() const {
697     assert(get() && "Expected valid pointer");
698     return *get();
699   }
700
701   StringRef getName() const { return get()->getName(); }
702
703   DITypeRef getType() const { return DITypeRef::get(get()->getType()); }
704 };
705
706 /// \brief This is a wrapper for template value parameter.
707 class DITemplateValueParameter : public DIDescriptor {
708 public:
709   DITemplateValueParameter() = default;
710   DITemplateValueParameter(const MDTemplateValueParameter *N)
711       : DIDescriptor(N) {}
712
713   MDTemplateValueParameter *get() const {
714     return cast_or_null<MDTemplateValueParameter>(DIDescriptor::get());
715   }
716   operator MDTemplateValueParameter *() const { return get(); }
717   MDTemplateValueParameter *operator->() const { return get(); }
718   MDTemplateValueParameter &operator*() const {
719     assert(get() && "Expected valid pointer");
720     return *get();
721   }
722
723   StringRef getName() const { return get()->getName(); }
724   DITypeRef getType() const { return DITypeRef::get(get()->getType()); }
725   Metadata *getValue() const { return get()->getValue(); }
726 };
727
728 /// \brief This is a wrapper for a global variable.
729 class DIGlobalVariable : public DIDescriptor {
730   DIFile getFile() const { return DIFile(get()->getFile()); }
731
732 public:
733   DIGlobalVariable() = default;
734   DIGlobalVariable(const MDGlobalVariable *N) : DIDescriptor(N) {}
735
736   MDGlobalVariable *get() const {
737     return cast_or_null<MDGlobalVariable>(DIDescriptor::get());
738   }
739   operator MDGlobalVariable *() const { return get(); }
740   MDGlobalVariable *operator->() const { return get(); }
741   MDGlobalVariable &operator*() const {
742     assert(get() && "Expected valid pointer");
743     return *get();
744   }
745
746   StringRef getName() const { return get()->getName(); }
747   StringRef getDisplayName() const { return get()->getDisplayName(); }
748   StringRef getLinkageName() const { return get()->getLinkageName(); }
749   unsigned getLineNumber() const { return get()->getLine(); }
750   unsigned isLocalToUnit() const { return get()->isLocalToUnit(); }
751   unsigned isDefinition() const { return get()->isDefinition(); }
752
753   DIScope getContext() const { return DIScope(get()->getScope()); }
754   StringRef getFilename() const { return getFile().getFilename(); }
755   StringRef getDirectory() const { return getFile().getDirectory(); }
756   DITypeRef getType() const { return DITypeRef::get(get()->getType()); }
757
758   GlobalVariable *getGlobal() const;
759   Constant *getConstant() const {
760     if (auto *N = get())
761       if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getVariable()))
762         return C->getValue();
763     return nullptr;
764   }
765   DIDerivedType getStaticDataMemberDeclaration() const {
766     return DIDerivedType(get()->getStaticDataMemberDeclaration());
767   }
768 };
769
770 /// \brief This is a wrapper for a variable (e.g. parameter, local, global etc).
771 class DIVariable : public DIDescriptor {
772   unsigned getFlags() const { return get()->getFlags(); }
773
774 public:
775   DIVariable() = default;
776   DIVariable(const MDLocalVariable *N) : DIDescriptor(N) {}
777
778   MDLocalVariable *get() const {
779     return cast_or_null<MDLocalVariable>(DIDescriptor::get());
780   }
781   operator MDLocalVariable *() const { return get(); }
782   MDLocalVariable *operator->() const { return get(); }
783   MDLocalVariable &operator*() const {
784     assert(get() && "Expected valid pointer");
785     return *get();
786   }
787
788   StringRef getName() const { return get()->getName(); }
789   unsigned getLineNumber() const { return get()->getLine(); }
790   unsigned getArgNumber() const { return get()->getArg(); }
791
792   DIScope getContext() const { return DIScope(get()->getScope()); }
793   DIFile getFile() const { return DIFile(get()->getFile()); }
794   DITypeRef getType() const { return DITypeRef::get(get()->getType()); }
795
796   bool isArtificial() const { return get()->isArtificial(); }
797   bool isObjectPointer() const { return get()->isObjectPointer(); }
798
799   /// \brief If this variable is inlined then return inline location.
800   MDNode *getInlinedAt() const { return DIDescriptor(get()->getInlinedAt()); }
801
802   /// \brief Check if this is a "__block" variable (Apple Blocks).
803   bool isBlockByrefVariable(const DITypeIdentifierMap &Map) const {
804     return (getType().resolve(Map)).isBlockByrefStruct();
805   }
806
807   /// \brief Check if this is an inlined function argument.
808   bool isInlinedFnArgument(const Function *CurFn);
809
810   /// \brief Return the size reported by the variable's type.
811   unsigned getSizeInBits(const DITypeIdentifierMap &Map);
812
813   void printExtendedName(raw_ostream &OS) const;
814 };
815
816 /// \brief A complex location expression in postfix notation.
817 ///
818 /// This is (almost) a DWARF expression that modifies the location of a
819 /// variable or (or the location of a single piece of a variable).
820 ///
821 /// FIXME: Instead of DW_OP_plus taking an argument, this should use DW_OP_const
822 /// and have DW_OP_plus consume the topmost elements on the stack.
823 class DIExpression : public DIDescriptor {
824 public:
825   DIExpression() = default;
826   DIExpression(const MDExpression *N) : DIDescriptor(N) {}
827
828   MDExpression *get() const {
829     return cast_or_null<MDExpression>(DIDescriptor::get());
830   }
831   operator MDExpression *() const { return get(); }
832   MDExpression *operator->() const { return get(); }
833   MDExpression &operator*() const {
834     assert(get() && "Expected valid pointer");
835     return *get();
836   }
837
838   unsigned getNumElements() const { return get()->getNumElements(); }
839   uint64_t getElement(unsigned I) const { return get()->getElement(I); }
840   bool isBitPiece() const { return get()->isBitPiece(); }
841   uint64_t getBitPieceOffset() const { return get()->getBitPieceOffset(); }
842   uint64_t getBitPieceSize() const { return get()->getBitPieceSize(); }
843 };
844
845 /// \brief This object holds location information.
846 ///
847 /// This object is not associated with any DWARF tag.
848 class DILocation : public DIDescriptor {
849 public:
850   DILocation() = default;
851   DILocation(const MDLocation *N) : DIDescriptor(N) {}
852
853   MDLocation *get() const {
854     return cast_or_null<MDLocation>(DIDescriptor::get());
855   }
856   operator MDLocation *() const { return get(); }
857   MDLocation *operator->() const { return get(); }
858   MDLocation &operator*() const {
859     assert(get() && "Expected valid pointer");
860     return *get();
861   }
862
863   unsigned getLineNumber() const { return get()->getLine(); }
864   unsigned getColumnNumber() const { return get()->getColumn(); }
865   DIScope getScope() const { return DIScope(get()->getScope()); }
866   DILocation getOrigLocation() const {
867     return DILocation(get()->getInlinedAt());
868   }
869   StringRef getFilename() const { return getScope().getFilename(); }
870   StringRef getDirectory() const { return getScope().getDirectory(); }
871   bool atSameLineAs(const DILocation &Other) const {
872     return (getLineNumber() == Other.getLineNumber() &&
873             getFilename() == Other.getFilename());
874   }
875   /// \brief Get the DWAF discriminator.
876   ///
877   /// DWARF discriminators are used to distinguish identical file locations for
878   /// instructions that are on different basic blocks. If two instructions are
879   /// inside the same lexical block and are in different basic blocks, we
880   /// create a new lexical block with identical location as the original but
881   /// with a different discriminator value
882   /// (lib/Transforms/Util/AddDiscriminators.cpp for details).
883   unsigned getDiscriminator() const {
884     // Since discriminators are associated with lexical blocks, make
885     // sure this location is a lexical block before retrieving its
886     // value.
887     if (auto *F = dyn_cast<MDLexicalBlockFile>(get()->getScope()))
888       return F->getDiscriminator();
889     return 0;
890   }
891
892   /// \brief Generate a new discriminator value for this location.
893   unsigned computeNewDiscriminator(LLVMContext &Ctx);
894
895   /// \brief Return a copy of this location with a different scope.
896   DILocation copyWithNewScope(LLVMContext &Ctx, DILexicalBlockFile NewScope);
897 };
898
899 class DIObjCProperty : public DIDescriptor {
900 public:
901   DIObjCProperty() = default;
902   DIObjCProperty(const MDObjCProperty *N) : DIDescriptor(N) {}
903
904   MDObjCProperty *get() const {
905     return cast_or_null<MDObjCProperty>(DIDescriptor::get());
906   }
907   operator MDObjCProperty *() const { return get(); }
908   MDObjCProperty *operator->() const { return get(); }
909   MDObjCProperty &operator*() const {
910     assert(get() && "Expected valid pointer");
911     return *get();
912   }
913
914   StringRef getObjCPropertyName() const { return get()->getName(); }
915   DIFile getFile() const { return DIFile(get()->getFile()); }
916   unsigned getLineNumber() const { return get()->getLine(); }
917
918   StringRef getObjCPropertyGetterName() const { return get()->getGetterName(); }
919   StringRef getObjCPropertySetterName() const { return get()->getSetterName(); }
920   unsigned getAttributes() const { return get()->getAttributes(); }
921   bool isReadOnlyObjCProperty() const {
922     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readonly) != 0;
923   }
924   bool isReadWriteObjCProperty() const {
925     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readwrite) != 0;
926   }
927   bool isAssignObjCProperty() const {
928     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_assign) != 0;
929   }
930   bool isRetainObjCProperty() const {
931     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_retain) != 0;
932   }
933   bool isCopyObjCProperty() const {
934     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_copy) != 0;
935   }
936   bool isNonAtomicObjCProperty() const {
937     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_nonatomic) != 0;
938   }
939
940   /// \brief Get the type.
941   ///
942   /// \note Objective-C doesn't have an ODR, so there is no benefit in storing
943   /// the type as a DITypeRef here.
944   DIType getType() const { return DIType(get()->getType()); }
945 };
946
947 /// \brief An imported module (C++ using directive or similar).
948 class DIImportedEntity : public DIDescriptor {
949 public:
950   DIImportedEntity() = default;
951   DIImportedEntity(const MDImportedEntity *N) : DIDescriptor(N) {}
952
953   MDImportedEntity *get() const {
954     return cast_or_null<MDImportedEntity>(DIDescriptor::get());
955   }
956   operator MDImportedEntity *() const { return get(); }
957   MDImportedEntity *operator->() const { return get(); }
958   MDImportedEntity &operator*() const {
959     assert(get() && "Expected valid pointer");
960     return *get();
961   }
962
963   DIScope getContext() const { return DIScope(get()->getScope()); }
964   DIDescriptorRef getEntity() const {
965     return DIDescriptorRef::get(get()->getEntity());
966   }
967   unsigned getLineNumber() const { return get()->getLine(); }
968   StringRef getName() const { return get()->getName(); }
969 };
970
971 #define SIMPLIFY_DESCRIPTOR(DESC)                                              \
972   template <> struct simplify_type<const DESC> {                               \
973     typedef Metadata *SimpleType;                                              \
974     static SimpleType getSimplifiedValue(const DESC &DI) { return DI; }        \
975   };                                                                           \
976   template <> struct simplify_type<DESC> : simplify_type<const DESC> {};
977 SIMPLIFY_DESCRIPTOR(DIDescriptor)
978 SIMPLIFY_DESCRIPTOR(DISubrange)
979 SIMPLIFY_DESCRIPTOR(DIEnumerator)
980 SIMPLIFY_DESCRIPTOR(DIScope)
981 SIMPLIFY_DESCRIPTOR(DIType)
982 SIMPLIFY_DESCRIPTOR(DIBasicType)
983 SIMPLIFY_DESCRIPTOR(DIDerivedType)
984 SIMPLIFY_DESCRIPTOR(DICompositeType)
985 SIMPLIFY_DESCRIPTOR(DISubroutineType)
986 SIMPLIFY_DESCRIPTOR(DIFile)
987 SIMPLIFY_DESCRIPTOR(DICompileUnit)
988 SIMPLIFY_DESCRIPTOR(DISubprogram)
989 SIMPLIFY_DESCRIPTOR(DILexicalBlock)
990 SIMPLIFY_DESCRIPTOR(DILexicalBlockFile)
991 SIMPLIFY_DESCRIPTOR(DINameSpace)
992 SIMPLIFY_DESCRIPTOR(DITemplateTypeParameter)
993 SIMPLIFY_DESCRIPTOR(DITemplateValueParameter)
994 SIMPLIFY_DESCRIPTOR(DIGlobalVariable)
995 SIMPLIFY_DESCRIPTOR(DIVariable)
996 SIMPLIFY_DESCRIPTOR(DIExpression)
997 SIMPLIFY_DESCRIPTOR(DILocation)
998 SIMPLIFY_DESCRIPTOR(DIObjCProperty)
999 SIMPLIFY_DESCRIPTOR(DIImportedEntity)
1000 #undef SIMPLIFY_DESCRIPTOR
1001
1002 /// \brief Find subprogram that is enclosing this scope.
1003 DISubprogram getDISubprogram(const MDNode *Scope);
1004
1005 /// \brief Find debug info for a given function.
1006 /// \returns a valid DISubprogram, if found. Otherwise, it returns an empty
1007 /// DISubprogram.
1008 DISubprogram getDISubprogram(const Function *F);
1009
1010 /// \brief Find underlying composite type.
1011 DICompositeType getDICompositeType(DIType T);
1012
1013 /// \brief Create a new inlined variable based on current variable.
1014 ///
1015 /// @param DV            Current Variable.
1016 /// @param InlinedScope  Location at current variable is inlined.
1017 DIVariable createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
1018                                  LLVMContext &VMContext);
1019
1020 /// \brief Remove inlined scope from the variable.
1021 DIVariable cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext);
1022
1023 /// \brief Generate map by visiting all retained types.
1024 DITypeIdentifierMap generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes);
1025
1026 /// \brief Strip debug info in the module if it exists.
1027 ///
1028 /// To do this, we remove all calls to the debugger intrinsics and any named
1029 /// metadata for debugging. We also remove debug locations for instructions.
1030 /// Return true if module is modified.
1031 bool StripDebugInfo(Module &M);
1032 bool stripDebugInfo(Function &F);
1033
1034 /// \brief Return Debug Info Metadata Version by checking module flags.
1035 unsigned getDebugMetadataVersionFromModule(const Module &M);
1036
1037 /// \brief Utility to find all debug info in a module.
1038 ///
1039 /// DebugInfoFinder tries to list all debug info MDNodes used in a module. To
1040 /// list debug info MDNodes used by an instruction, DebugInfoFinder uses
1041 /// processDeclare, processValue and processLocation to handle DbgDeclareInst,
1042 /// DbgValueInst and DbgLoc attached to instructions. processModule will go
1043 /// through all DICompileUnits in llvm.dbg.cu and list debug info MDNodes
1044 /// used by the CUs.
1045 class DebugInfoFinder {
1046 public:
1047   DebugInfoFinder() : TypeMapInitialized(false) {}
1048
1049   /// \brief Process entire module and collect debug info anchors.
1050   void processModule(const Module &M);
1051
1052   /// \brief Process DbgDeclareInst.
1053   void processDeclare(const Module &M, const DbgDeclareInst *DDI);
1054   /// \brief Process DbgValueInst.
1055   void processValue(const Module &M, const DbgValueInst *DVI);
1056   /// \brief Process DILocation.
1057   void processLocation(const Module &M, DILocation Loc);
1058
1059   /// \brief Clear all lists.
1060   void reset();
1061
1062 private:
1063   void InitializeTypeMap(const Module &M);
1064
1065   void processType(DIType DT);
1066   void processSubprogram(DISubprogram SP);
1067   void processScope(DIScope Scope);
1068   bool addCompileUnit(DICompileUnit CU);
1069   bool addGlobalVariable(DIGlobalVariable DIG);
1070   bool addSubprogram(DISubprogram SP);
1071   bool addType(DIType DT);
1072   bool addScope(DIScope Scope);
1073
1074 public:
1075   typedef SmallVectorImpl<DICompileUnit>::const_iterator compile_unit_iterator;
1076   typedef SmallVectorImpl<DISubprogram>::const_iterator subprogram_iterator;
1077   typedef SmallVectorImpl<DIGlobalVariable>::const_iterator
1078       global_variable_iterator;
1079   typedef SmallVectorImpl<DIType>::const_iterator type_iterator;
1080   typedef SmallVectorImpl<DIScope>::const_iterator scope_iterator;
1081
1082   iterator_range<compile_unit_iterator> compile_units() const {
1083     return iterator_range<compile_unit_iterator>(CUs.begin(), CUs.end());
1084   }
1085
1086   iterator_range<subprogram_iterator> subprograms() const {
1087     return iterator_range<subprogram_iterator>(SPs.begin(), SPs.end());
1088   }
1089
1090   iterator_range<global_variable_iterator> global_variables() const {
1091     return iterator_range<global_variable_iterator>(GVs.begin(), GVs.end());
1092   }
1093
1094   iterator_range<type_iterator> types() const {
1095     return iterator_range<type_iterator>(TYs.begin(), TYs.end());
1096   }
1097
1098   iterator_range<scope_iterator> scopes() const {
1099     return iterator_range<scope_iterator>(Scopes.begin(), Scopes.end());
1100   }
1101
1102   unsigned compile_unit_count() const { return CUs.size(); }
1103   unsigned global_variable_count() const { return GVs.size(); }
1104   unsigned subprogram_count() const { return SPs.size(); }
1105   unsigned type_count() const { return TYs.size(); }
1106   unsigned scope_count() const { return Scopes.size(); }
1107
1108 private:
1109   SmallVector<DICompileUnit, 8> CUs;
1110   SmallVector<DISubprogram, 8> SPs;
1111   SmallVector<DIGlobalVariable, 8> GVs;
1112   SmallVector<DIType, 8> TYs;
1113   SmallVector<DIScope, 8> Scopes;
1114   SmallPtrSet<MDNode *, 64> NodesSeen;
1115   DITypeIdentifierMap TypeIdentifierMap;
1116
1117   /// \brief Specify if TypeIdentifierMap is initialized.
1118   bool TypeMapInitialized;
1119 };
1120
1121 DenseMap<const Function *, DISubprogram> makeSubprogramMap(const Module &M);
1122
1123 } // end namespace llvm
1124
1125 #endif