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