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