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