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