DebugInfo: Move new hierarchy into place
[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 class DIHeaderFieldIterator
62     : public std::iterator<std::input_iterator_tag, StringRef, std::ptrdiff_t,
63                            const StringRef *, StringRef> {
64   StringRef Header;
65   StringRef Current;
66
67 public:
68   DIHeaderFieldIterator() {}
69   explicit DIHeaderFieldIterator(StringRef Header)
70       : Header(Header), Current(Header.slice(0, Header.find('\0'))) {}
71   StringRef operator*() const { return Current; }
72   const StringRef *operator->() const { return &Current; }
73   DIHeaderFieldIterator &operator++() {
74     increment();
75     return *this;
76   }
77   DIHeaderFieldIterator operator++(int) {
78     DIHeaderFieldIterator X(*this);
79     increment();
80     return X;
81   }
82   bool operator==(const DIHeaderFieldIterator &X) const {
83     return Current.data() == X.Current.data();
84   }
85   bool operator!=(const DIHeaderFieldIterator &X) const {
86     return !(*this == X);
87   }
88
89   StringRef getHeader() const { return Header; }
90   StringRef getCurrent() const { return Current; }
91   StringRef getPrefix() const {
92     if (Current.begin() == Header.begin())
93       return StringRef();
94     return Header.slice(0, Current.begin() - Header.begin() - 1);
95   }
96   StringRef getSuffix() const {
97     if (Current.end() == Header.end())
98       return StringRef();
99     return Header.slice(Current.end() - Header.begin() + 1, StringRef::npos);
100   }
101
102   /// \brief Get the current field as a number.
103   ///
104   /// Convert the current field into a number.  Return \c 0 on error.
105   template <class T> T getNumber() const {
106     T Int;
107     if (getCurrent().getAsInteger(0, Int))
108       return 0;
109     return Int;
110   }
111
112 private:
113   void increment() {
114     assert(Current.data() != nullptr && "Cannot increment past the end");
115     StringRef Suffix = getSuffix();
116     Current = Suffix.slice(0, Suffix.find('\0'));
117   }
118 };
119
120 /// \brief A thin wraper around MDNode to access encoded debug info.
121 ///
122 /// This should not be stored in a container, because the underlying MDNode may
123 /// change in certain situations.
124 class DIDescriptor {
125   // Befriends DIRef so DIRef can befriend the protected member
126   // function: getFieldAs<DIRef>.
127   template <typename T> friend class DIRef;
128
129 public:
130   /// \brief Accessibility flags.
131   ///
132   /// The three accessibility flags are mutually exclusive and rolled together
133   /// in the first two bits.
134   enum {
135 #define HANDLE_DI_FLAG(ID, NAME) Flag##NAME = ID,
136 #include "llvm/IR/DebugInfoFlags.def"
137     FlagAccessibility = FlagPrivate | FlagProtected | FlagPublic
138   };
139
140   static unsigned getFlag(StringRef Flag);
141   static const char *getFlagString(unsigned Flag);
142
143   /// \brief Split up a flags bitfield.
144   ///
145   /// Split \c Flags into \c SplitFlags, a vector of its components.  Returns
146   /// any remaining (unrecognized) bits.
147   static unsigned splitFlags(unsigned Flags,
148                              SmallVectorImpl<unsigned> &SplitFlags);
149
150 protected:
151   const MDNode *DbgNode;
152
153   StringRef getStringField(unsigned Elt) const;
154   unsigned getUnsignedField(unsigned Elt) const {
155     return (unsigned)getUInt64Field(Elt);
156   }
157   uint64_t getUInt64Field(unsigned Elt) const;
158   int64_t getInt64Field(unsigned Elt) const;
159   DIDescriptor getDescriptorField(unsigned Elt) const;
160
161   template <typename DescTy> DescTy getFieldAs(unsigned Elt) const {
162     return DescTy(getDescriptorField(Elt));
163   }
164
165   GlobalVariable *getGlobalVariableField(unsigned Elt) const;
166   Constant *getConstantField(unsigned Elt) const;
167   Function *getFunctionField(unsigned Elt) const;
168
169 public:
170   explicit DIDescriptor(const MDNode *N = nullptr) : DbgNode(N) {}
171
172   bool Verify() const;
173
174   MDNode *get() const { return const_cast<MDNode *>(DbgNode); }
175   operator MDNode *() const { return get(); }
176   MDNode *operator->() const { return get(); }
177
178   // An explicit operator bool so that we can do testing of DI values
179   // easily.
180   // FIXME: This operator bool isn't actually protecting anything at the
181   // moment due to the conversion operator above making DIDescriptor nodes
182   // implicitly convertable to bool.
183   explicit operator bool() const { return DbgNode != nullptr; }
184
185   bool operator==(DIDescriptor Other) const { return DbgNode == Other.DbgNode; }
186   bool operator!=(DIDescriptor Other) const { return !operator==(Other); }
187
188   StringRef getHeader() const { return getStringField(0); }
189
190   size_t getNumHeaderFields() const {
191     return std::distance(DIHeaderFieldIterator(getHeader()),
192                          DIHeaderFieldIterator());
193   }
194
195   DIHeaderFieldIterator header_begin() const {
196     return DIHeaderFieldIterator(getHeader());
197   }
198   DIHeaderFieldIterator header_end() const { return DIHeaderFieldIterator(); }
199
200   DIHeaderFieldIterator getHeaderIterator(unsigned Index) const {
201     // Since callers expect an empty string for out-of-range accesses, we can't
202     // use std::advance() here.
203     for (auto I = header_begin(), E = header_end(); I != E; ++I, --Index)
204       if (!Index)
205         return I;
206     return header_end();
207   }
208
209   StringRef getHeaderField(unsigned Index) const {
210     return *getHeaderIterator(Index);
211   }
212
213   template <class T> T getHeaderFieldAs(unsigned Index) const {
214     return getHeaderIterator(Index).getNumber<T>();
215   }
216
217   uint16_t getTag() const {
218     if (auto *N = dyn_cast_or_null<DebugNode>(get()))
219       return N->getTag();
220     return 0;
221   }
222
223   bool isDerivedType() const { return get() && isa<MDDerivedTypeBase>(get()); }
224   bool isCompositeType() const {
225     return get() && isa<MDCompositeTypeBase>(get());
226   }
227   bool isSubroutineType() const {
228     return get() && isa<MDSubroutineType>(get());
229   }
230   bool isBasicType() const { return get() && isa<MDBasicType>(get()); }
231   bool isVariable() const { return get() && isa<MDLocalVariable>(get()); }
232   bool isSubprogram() const { return get() && isa<MDSubprogram>(get()); }
233   bool isGlobalVariable() const {
234     return get() && isa<MDGlobalVariable>(get());
235   }
236   bool isScope() const { return get() && isa<MDScope>(get()); }
237   bool isFile() const { return get() && isa<MDFile>(get()); }
238   bool isCompileUnit() const { return get() && isa<MDCompileUnit>(get()); }
239   bool isNameSpace() const{ return get() && isa<MDNamespace>(get()); }
240   bool isLexicalBlockFile() const {
241     return get() && isa<MDLexicalBlockFile>(get());
242   }
243   bool isLexicalBlock() const {
244     return get() && isa<MDLexicalBlockBase>(get());
245   }
246   bool isSubrange() const { return get() && isa<MDSubrange>(get()); }
247   bool isEnumerator() const { return get() && isa<MDEnumerator>(get()); }
248   bool isType() const { return get() && isa<MDType>(get()); }
249   bool isTemplateTypeParameter() const {
250     return get() && isa<MDTemplateTypeParameter>(get());
251   }
252   bool isTemplateValueParameter() const {
253     return get() && isa<MDTemplateValueParameter>(get());
254   }
255   bool isObjCProperty() const { return get() && isa<MDObjCProperty>(get()); }
256   bool isImportedEntity() const {
257     return get() && isa<MDImportedEntity>(get());
258   }
259   bool isExpression() const { return get() && isa<MDExpression>(get()); }
260
261   void print(raw_ostream &OS) const;
262   void dump() const;
263
264   /// \brief Replace all uses of debug info referenced by this descriptor.
265   void replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D);
266   void replaceAllUsesWith(MDNode *D);
267 };
268
269 #define RETURN_FROM_RAW(VALID, DEFAULT)                                        \
270   do {                                                                         \
271     if (auto *N = getRaw())                                                    \
272       return VALID;                                                            \
273     return DEFAULT;                                                            \
274   } while (false)
275 #define RETURN_DESCRIPTOR_FROM_RAW(DESC, VALID)                                \
276   do {                                                                         \
277     if (auto *N = getRaw())                                                    \
278       return DESC(dyn_cast_or_null<MDNode>(VALID));                            \
279     return DESC(static_cast<const MDNode *>(nullptr));                         \
280   } while (false)
281 #define RETURN_REF_FROM_RAW(REF, VALID)                                        \
282   do {                                                                         \
283     if (auto *N = getRaw())                                                    \
284       return REF::get(VALID);                                                  \
285     return REF::get(nullptr);                                                  \
286   } while (false)
287
288 /// \brief This is used to represent ranges, for array bounds.
289 class DISubrange : public DIDescriptor {
290   MDSubrange *getRaw() const { return dyn_cast_or_null<MDSubrange>(get()); }
291
292 public:
293   explicit DISubrange(const MDNode *N = nullptr) : DIDescriptor(N) {}
294   DISubrange(const MDSubrange *N) : DIDescriptor(N) {}
295
296   int64_t getLo() const { RETURN_FROM_RAW(N->getLo(), 0); }
297   int64_t getCount() const { RETURN_FROM_RAW(N->getCount(), 0); }
298   bool Verify() const;
299 };
300
301 /// \brief This descriptor holds an array of nodes with type T.
302 template <typename T> class DITypedArray : public DIDescriptor {
303 public:
304   explicit DITypedArray(const MDNode *N = nullptr) : DIDescriptor(N) {}
305   unsigned getNumElements() const {
306     return DbgNode ? DbgNode->getNumOperands() : 0;
307   }
308   T getElement(unsigned Idx) const { return getFieldAs<T>(Idx); }
309 };
310
311 typedef DITypedArray<DIDescriptor> DIArray;
312
313 /// \brief A wrapper for an enumerator (e.g. X and Y in 'enum {X,Y}').
314 ///
315 /// FIXME: it seems strange that this doesn't have either a reference to the
316 /// type/precision or a file/line pair for location info.
317 class DIEnumerator : public DIDescriptor {
318   MDEnumerator *getRaw() const { return dyn_cast_or_null<MDEnumerator>(get()); }
319
320 public:
321   explicit DIEnumerator(const MDNode *N = nullptr) : DIDescriptor(N) {}
322   DIEnumerator(const MDEnumerator *N) : DIDescriptor(N) {}
323
324   StringRef getName() const { RETURN_FROM_RAW(N->getName(), ""); }
325   int64_t getEnumValue() const { RETURN_FROM_RAW(N->getValue(), 0); }
326   bool Verify() const;
327 };
328
329 template <typename T> class DIRef;
330 typedef DIRef<DIDescriptor> DIDescriptorRef;
331 typedef DIRef<DIScope> DIScopeRef;
332 typedef DIRef<DIType> DITypeRef;
333 typedef DITypedArray<DITypeRef> DITypeArray;
334
335 /// \brief A base class for various scopes.
336 ///
337 /// Although, implementation-wise, DIScope is the parent class of most
338 /// other DIxxx classes, including DIType and its descendants, most of
339 /// DIScope's descendants are not a substitutable subtype of
340 /// DIScope. The DIDescriptor::isScope() method only is true for
341 /// DIScopes that are scopes in the strict lexical scope sense
342 /// (DICompileUnit, DISubprogram, etc.), but not for, e.g., a DIType.
343 class DIScope : public DIDescriptor {
344 protected:
345   MDScope *getRaw() const { return dyn_cast_or_null<MDScope>(get()); }
346
347 public:
348   explicit DIScope(const MDNode *N = nullptr) : DIDescriptor(N) {}
349   DIScope(const MDScope *N) : DIDescriptor(N) {}
350
351   /// \brief Get the parent scope.
352   ///
353   /// Gets the parent scope for this scope node or returns a default
354   /// constructed scope.
355   DIScopeRef getContext() const;
356   /// \brief Get the scope name.
357   ///
358   /// If the scope node has a name, return that, else return an empty string.
359   StringRef getName() const;
360   StringRef getFilename() const;
361   StringRef getDirectory() const;
362
363   /// \brief Generate a reference to this DIScope.
364   ///
365   /// Uses the type identifier instead of the actual MDNode if possible, to
366   /// help type uniquing.
367   DIScopeRef getRef() const;
368 };
369
370 /// \brief Represents reference to a DIDescriptor.
371 ///
372 /// Abstracts over direct and identifier-based metadata references.
373 template <typename T> class DIRef {
374   template <typename DescTy>
375   friend DescTy DIDescriptor::getFieldAs(unsigned Elt) const;
376   friend DIScopeRef DIScope::getContext() const;
377   friend DIScopeRef DIScope::getRef() const;
378   friend class DIType;
379
380   /// \brief Val can be either a MDNode or a MDString.
381   ///
382   /// In the latter, MDString specifies the type identifier.
383   const Metadata *Val;
384   explicit DIRef(const Metadata *V);
385
386 public:
387   T resolve(const DITypeIdentifierMap &Map) const;
388   StringRef getName() const;
389   operator Metadata *() const { return const_cast<Metadata *>(Val); }
390
391   static DIRef get(const Metadata *MD) { return DIRef(MD); }
392 };
393
394 template <typename T>
395 T DIRef<T>::resolve(const DITypeIdentifierMap &Map) const {
396   if (!Val)
397     return T();
398
399   if (const MDNode *MD = dyn_cast<MDNode>(Val))
400     return T(MD);
401
402   const MDString *MS = cast<MDString>(Val);
403   // Find the corresponding MDNode.
404   DITypeIdentifierMap::const_iterator Iter = Map.find(MS);
405   assert(Iter != Map.end() && "Identifier not in the type map?");
406   assert(DIDescriptor(Iter->second).isType() &&
407          "MDNode in DITypeIdentifierMap should be a DIType.");
408   return T(Iter->second);
409 }
410
411 template <typename T> StringRef DIRef<T>::getName() const {
412   if (!Val)
413     return StringRef();
414
415   if (const MDNode *MD = dyn_cast<MDNode>(Val))
416     return T(MD).getName();
417
418   const MDString *MS = cast<MDString>(Val);
419   return MS->getString();
420 }
421
422 /// \brief Handle fields that are references to DIDescriptors.
423 template <>
424 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const;
425 /// \brief Specialize DIRef constructor for DIDescriptorRef.
426 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V);
427
428 /// \brief Handle fields that are references to DIScopes.
429 template <> DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const;
430 /// \brief Specialize DIRef constructor for DIScopeRef.
431 template <> DIRef<DIScope>::DIRef(const Metadata *V);
432
433 /// \brief Handle fields that are references to DITypes.
434 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const;
435 /// \brief Specialize DIRef constructor for DITypeRef.
436 template <> DIRef<DIType>::DIRef(const Metadata *V);
437
438 /// \brief This is a wrapper for a type.
439 ///
440 /// FIXME: Types should be factored much better so that CV qualifiers and
441 /// others do not require a huge and empty descriptor full of zeros.
442 class DIType : public DIScope {
443   MDType *getRaw() const { return dyn_cast_or_null<MDType>(get()); }
444
445 public:
446   explicit DIType(const MDNode *N = nullptr) : DIScope(N) {}
447   DIType(const MDType *N) : DIScope(N) {}
448
449   operator DITypeRef() const {
450     assert(isType() &&
451            "constructing DITypeRef from an MDNode that is not a type");
452     return DITypeRef(&*getRef());
453   }
454
455   bool Verify() const;
456
457   DIScopeRef getContext() const {
458     RETURN_REF_FROM_RAW(DIScopeRef, N->getScope());
459   }
460   StringRef getName() const { RETURN_FROM_RAW(N->getName(), ""); }
461   unsigned getLineNumber() const { RETURN_FROM_RAW(N->getLine(), 0); }
462   uint64_t getSizeInBits() const { RETURN_FROM_RAW(N->getSizeInBits(), 0); }
463   uint64_t getAlignInBits() const { RETURN_FROM_RAW(N->getAlignInBits(), 0); }
464   // FIXME: Offset is only used for DW_TAG_member nodes.  Making every type
465   // carry this is just plain insane.
466   uint64_t getOffsetInBits() const { RETURN_FROM_RAW(N->getOffsetInBits(), 0); }
467   unsigned getFlags() const { RETURN_FROM_RAW(N->getFlags(), 0); }
468   bool isPrivate() const {
469     return (getFlags() & FlagAccessibility) == FlagPrivate;
470   }
471   bool isProtected() const {
472     return (getFlags() & FlagAccessibility) == FlagProtected;
473   }
474   bool isPublic() const {
475     return (getFlags() & FlagAccessibility) == FlagPublic;
476   }
477   bool isForwardDecl() const { return (getFlags() & FlagFwdDecl) != 0; }
478   bool isAppleBlockExtension() const {
479     return (getFlags() & FlagAppleBlock) != 0;
480   }
481   bool isBlockByrefStruct() const {
482     return (getFlags() & FlagBlockByrefStruct) != 0;
483   }
484   bool isVirtual() const { return (getFlags() & FlagVirtual) != 0; }
485   bool isArtificial() const { return (getFlags() & FlagArtificial) != 0; }
486   bool isObjectPointer() const { return (getFlags() & FlagObjectPointer) != 0; }
487   bool isObjcClassComplete() const {
488     return (getFlags() & FlagObjcClassComplete) != 0;
489   }
490   bool isVector() const { return (getFlags() & FlagVector) != 0; }
491   bool isStaticMember() const { return (getFlags() & FlagStaticMember) != 0; }
492   bool isLValueReference() const {
493     return (getFlags() & FlagLValueReference) != 0;
494   }
495   bool isRValueReference() const {
496     return (getFlags() & FlagRValueReference) != 0;
497   }
498   bool isValid() const { return DbgNode && isType(); }
499 };
500
501 /// \brief A basic type, like 'int' or 'float'.
502 class DIBasicType : public DIType {
503   MDBasicType *getRaw() const { return dyn_cast_or_null<MDBasicType>(get()); }
504
505 public:
506   explicit DIBasicType(const MDNode *N = nullptr) : DIType(N) {}
507   DIBasicType(const MDBasicType *N) : DIType(N) {}
508
509   unsigned getEncoding() const { RETURN_FROM_RAW(N->getEncoding(), 0); }
510
511   bool Verify() const;
512 };
513
514 /// \brief A simple derived type
515 ///
516 /// Like a const qualified type, a typedef, a pointer or reference, et cetera.
517 /// Or, a data member of a class/struct/union.
518 class DIDerivedType : public DIType {
519   MDDerivedTypeBase *getRaw() const {
520     return dyn_cast_or_null<MDDerivedTypeBase>(get());
521   }
522
523 public:
524   explicit DIDerivedType(const MDNode *N = nullptr) : DIType(N) {}
525   DIDerivedType(const MDDerivedTypeBase *N) : DIType(N) {}
526
527   DITypeRef getTypeDerivedFrom() const {
528     RETURN_REF_FROM_RAW(DITypeRef, N->getBaseType());
529   }
530
531   /// \brief Return property node, if this ivar is associated with one.
532   MDNode *getObjCProperty() const {
533     if (auto *N = dyn_cast_or_null<MDDerivedType>(get()))
534       return dyn_cast_or_null<MDNode>(N->getExtraData());
535     return nullptr;
536   }
537
538   DITypeRef getClassType() const {
539     assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
540     if (auto *N = dyn_cast_or_null<MDDerivedType>(get()))
541       return DITypeRef::get(N->getExtraData());
542     return DITypeRef::get(nullptr);
543   }
544
545   Constant *getConstant() const {
546     assert((getTag() == dwarf::DW_TAG_member) && isStaticMember());
547     if (auto *N = dyn_cast_or_null<MDDerivedType>(get()))
548       if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getExtraData()))
549         return C->getValue();
550
551     return nullptr;
552   }
553
554   bool Verify() const;
555 };
556
557 /// \brief Types that refer to multiple other types.
558 ///
559 /// This descriptor holds a type that can refer to multiple other types, like a
560 /// function or struct.
561 ///
562 /// DICompositeType is derived from DIDerivedType because some
563 /// composite types (such as enums) can be derived from basic types
564 // FIXME: Make this derive from DIType directly & just store the
565 // base type in a single DIType field.
566 class DICompositeType : public DIDerivedType {
567   friend class DIBuilder;
568
569   /// \brief Set the array of member DITypes.
570   void setArraysHelper(MDNode *Elements, MDNode *TParams);
571
572   MDCompositeTypeBase *getRaw() const {
573     return dyn_cast_or_null<MDCompositeTypeBase>(get());
574   }
575
576 public:
577   explicit DICompositeType(const MDNode *N = nullptr) : DIDerivedType(N) {}
578   DICompositeType(const MDCompositeTypeBase *N) : DIDerivedType(N) {}
579
580   DIArray getElements() const {
581     assert(!isSubroutineType() && "no elements for DISubroutineType");
582     RETURN_DESCRIPTOR_FROM_RAW(DIArray, N->getElements());
583   }
584
585 private:
586   template <typename T>
587   void setArrays(DITypedArray<T> Elements, DIArray TParams = DIArray()) {
588     assert(
589         (!TParams || DbgNode->getNumOperands() == 8) &&
590         "If you're setting the template parameters this should include a slot "
591         "for that!");
592     setArraysHelper(Elements, TParams);
593   }
594
595 public:
596   unsigned getRunTimeLang() const { RETURN_FROM_RAW(N->getRuntimeLang(), 0); }
597   DITypeRef getContainingType() const {
598     RETURN_REF_FROM_RAW(DITypeRef, N->getVTableHolder());
599   }
600
601 private:
602   /// \brief Set the containing type.
603   void setContainingType(DICompositeType ContainingType);
604
605 public:
606   DIArray getTemplateParams() const {
607     RETURN_DESCRIPTOR_FROM_RAW(DIArray, N->getTemplateParams());
608   }
609   MDString *getIdentifier() const {
610     RETURN_FROM_RAW(N->getRawIdentifier(), nullptr);
611   }
612
613   bool Verify() const;
614 };
615
616 class DISubroutineType : public DICompositeType {
617   MDSubroutineType *getRaw() const {
618     return dyn_cast_or_null<MDSubroutineType>(get());
619   }
620
621 public:
622   explicit DISubroutineType(const MDNode *N = nullptr) : DICompositeType(N) {}
623   DISubroutineType(const MDSubroutineType *N) : DICompositeType(N) {}
624
625   DITypedArray<DITypeRef> getTypeArray() const {
626     RETURN_DESCRIPTOR_FROM_RAW(DITypedArray<DITypeRef>, N->getTypeArray());
627   }
628 };
629
630 /// \brief This is a wrapper for a file.
631 class DIFile : public DIScope {
632   MDFile *getRaw() const { return dyn_cast_or_null<MDFile>(get()); }
633
634 public:
635   explicit DIFile(const MDNode *N = nullptr) : DIScope(N) {}
636   DIFile(const MDFile *N) : DIScope(N) {}
637
638   /// \brief Retrieve the MDNode for the directory/file pair.
639   MDNode *getFileNode() const { return get(); }
640   bool Verify() const;
641 };
642
643 /// \brief A wrapper for a compile unit.
644 class DICompileUnit : public DIScope {
645   MDCompileUnit *getRaw() const {
646     return dyn_cast_or_null<MDCompileUnit>(get());
647   }
648
649 public:
650   explicit DICompileUnit(const MDNode *N = nullptr) : DIScope(N) {}
651   DICompileUnit(const MDCompileUnit *N) : DIScope(N) {}
652
653   dwarf::SourceLanguage getLanguage() const {
654     RETURN_FROM_RAW(static_cast<dwarf::SourceLanguage>(N->getSourceLanguage()),
655                     static_cast<dwarf::SourceLanguage>(0));
656   }
657   StringRef getProducer() const { RETURN_FROM_RAW(N->getProducer(), ""); }
658   bool isOptimized() const { RETURN_FROM_RAW(N->isOptimized(), false); }
659   StringRef getFlags() const { RETURN_FROM_RAW(N->getFlags(), ""); }
660   unsigned getRunTimeVersion() const {
661     RETURN_FROM_RAW(N->getRuntimeVersion(), 0);
662   }
663
664   DIArray getEnumTypes() const {
665     RETURN_DESCRIPTOR_FROM_RAW(DIArray, N->getEnumTypes());
666   }
667   DIArray getRetainedTypes() const {
668     RETURN_DESCRIPTOR_FROM_RAW(DIArray, N->getRetainedTypes());
669   }
670   DIArray getSubprograms() const {
671     RETURN_DESCRIPTOR_FROM_RAW(DIArray, N->getSubprograms());
672   }
673   DIArray getGlobalVariables() const {
674     RETURN_DESCRIPTOR_FROM_RAW(DIArray, N->getGlobalVariables());
675   }
676   DIArray getImportedEntities() const {
677     RETURN_DESCRIPTOR_FROM_RAW(DIArray, N->getImportedEntities());
678   }
679
680   void replaceSubprograms(DIArray Subprograms);
681   void replaceGlobalVariables(DIArray GlobalVariables);
682
683   StringRef getSplitDebugFilename() const {
684     RETURN_FROM_RAW(N->getSplitDebugFilename(), "");
685   }
686   unsigned getEmissionKind() const { RETURN_FROM_RAW(N->getEmissionKind(), 0); }
687
688   bool Verify() const;
689 };
690
691 /// \brief This is a wrapper for a subprogram (e.g. a function).
692 class DISubprogram : public DIScope {
693   MDSubprogram *getRaw() const { return dyn_cast_or_null<MDSubprogram>(get()); }
694
695 public:
696   explicit DISubprogram(const MDNode *N = nullptr) : DIScope(N) {}
697   DISubprogram(const MDSubprogram *N) : DIScope(N) {}
698
699   StringRef getName() const { RETURN_FROM_RAW(N->getName(), ""); }
700   StringRef getDisplayName() const { RETURN_FROM_RAW(N->getDisplayName(), ""); }
701   StringRef getLinkageName() const { RETURN_FROM_RAW(N->getLinkageName(), ""); }
702   unsigned getLineNumber() const { RETURN_FROM_RAW(N->getLine(), 0); }
703
704   /// \brief Check if this is local (like 'static' in C).
705   unsigned isLocalToUnit() const { RETURN_FROM_RAW(N->isLocalToUnit(), 0); }
706   unsigned isDefinition() const { RETURN_FROM_RAW(N->isDefinition(), 0); }
707
708   unsigned getVirtuality() const { RETURN_FROM_RAW(N->getVirtuality(), 0); }
709   unsigned getVirtualIndex() const { RETURN_FROM_RAW(N->getVirtualIndex(), 0); }
710
711   unsigned getFlags() const { RETURN_FROM_RAW(N->getFlags(), 0); }
712
713   unsigned isOptimized() const { RETURN_FROM_RAW(N->isOptimized(), 0); }
714
715   /// \brief Get the beginning of the scope of the function (not the name).
716   unsigned getScopeLineNumber() const { RETURN_FROM_RAW(N->getScopeLine(), 0); }
717
718   DIScopeRef getContext() const {
719     RETURN_REF_FROM_RAW(DIScopeRef, N->getScope());
720   }
721   DISubroutineType getType() const {
722     RETURN_DESCRIPTOR_FROM_RAW(DISubroutineType, N->getType());
723   }
724
725   DITypeRef getContainingType() const {
726     RETURN_REF_FROM_RAW(DITypeRef, N->getContainingType());
727   }
728
729   bool Verify() const;
730
731   /// \brief Check if this provides debugging information for the function F.
732   bool describes(const Function *F);
733
734   Function *getFunction() const;
735
736   void replaceFunction(Function *F) {
737     if (auto *N = getRaw())
738       N->replaceFunction(F);
739   }
740   DIArray getTemplateParams() const {
741     RETURN_DESCRIPTOR_FROM_RAW(DIArray, N->getTemplateParams());
742   }
743   DISubprogram getFunctionDeclaration() const {
744     RETURN_DESCRIPTOR_FROM_RAW(DISubprogram, N->getDeclaration());
745   }
746   MDNode *getVariablesNodes() const { return getVariables(); }
747   DIArray getVariables() const {
748     RETURN_DESCRIPTOR_FROM_RAW(DIArray, N->getVariables());
749   }
750
751   unsigned isArtificial() const { return (getFlags() & FlagArtificial) != 0; }
752   /// \brief Check for the "private" access specifier.
753   bool isPrivate() const {
754     return (getFlags() & FlagAccessibility) == FlagPrivate;
755   }
756   /// \brief Check for the "protected" access specifier.
757   bool isProtected() const {
758     return (getFlags() & FlagAccessibility) == FlagProtected;
759   }
760   /// \brief Check for the "public" access specifier.
761   bool isPublic() const {
762     return (getFlags() & FlagAccessibility) == FlagPublic;
763   }
764   /// \brief Check for "explicit".
765   bool isExplicit() const { return (getFlags() & FlagExplicit) != 0; }
766   /// \brief Check if this is prototyped.
767   bool isPrototyped() const { return (getFlags() & FlagPrototyped) != 0; }
768
769   /// \brief Check if this is reference-qualified.
770   ///
771   /// Return true if this subprogram is a C++11 reference-qualified non-static
772   /// member function (void foo() &).
773   unsigned isLValueReference() const {
774     return (getFlags() & FlagLValueReference) != 0;
775   }
776
777   /// \brief Check if this is rvalue-reference-qualified.
778   ///
779   /// Return true if this subprogram is a C++11 rvalue-reference-qualified
780   /// non-static member function (void foo() &&).
781   unsigned isRValueReference() const {
782     return (getFlags() & FlagRValueReference) != 0;
783   }
784 };
785
786 /// \brief This is a wrapper for a lexical block.
787 class DILexicalBlock : public DIScope {
788   MDLexicalBlockBase *getRaw() const {
789     return dyn_cast_or_null<MDLexicalBlockBase>(get());
790   }
791
792 public:
793   explicit DILexicalBlock(const MDNode *N = nullptr) : DIScope(N) {}
794   DILexicalBlock(const MDLexicalBlock *N) : DIScope(N) {}
795
796   DIScope getContext() const {
797     RETURN_DESCRIPTOR_FROM_RAW(DIScope, N->getScope());
798   }
799   unsigned getLineNumber() const {
800     if (auto *N = dyn_cast_or_null<MDLexicalBlock>(get()))
801       return N->getLine();
802     return 0;
803   }
804   unsigned getColumnNumber() const {
805     if (auto *N = dyn_cast_or_null<MDLexicalBlock>(get()))
806       return N->getColumn();
807     return 0;
808   }
809   bool Verify() const;
810 };
811
812 /// \brief This is a wrapper for a lexical block with a filename change.
813 class DILexicalBlockFile : public DIScope {
814   MDLexicalBlockFile *getRaw() const {
815     return dyn_cast_or_null<MDLexicalBlockFile>(get());
816   }
817
818 public:
819   explicit DILexicalBlockFile(const MDNode *N = nullptr) : DIScope(N) {}
820   DILexicalBlockFile(const MDLexicalBlockFile *N) : DIScope(N) {}
821
822   DIScope getContext() const {
823     // FIXME: This logic is horrible.  getScope() returns a DILexicalBlock, but
824     // then we check if it's a subprogram?  WHAT?!?
825     if (getScope().isSubprogram())
826       return getScope();
827     return getScope().getContext();
828   }
829   unsigned getLineNumber() const { return getScope().getLineNumber(); }
830   unsigned getColumnNumber() const { return getScope().getColumnNumber(); }
831   DILexicalBlock getScope() const {
832     RETURN_DESCRIPTOR_FROM_RAW(DILexicalBlock, N->getScope());
833   }
834   unsigned getDiscriminator() const {
835     RETURN_FROM_RAW(N->getDiscriminator(), 0);
836   }
837   bool Verify() const;
838 };
839
840 /// \brief A wrapper for a C++ style name space.
841 class DINameSpace : public DIScope {
842   MDNamespace *getRaw() const { return dyn_cast_or_null<MDNamespace>(get()); }
843
844 public:
845   explicit DINameSpace(const MDNode *N = nullptr) : DIScope(N) {}
846   DINameSpace(const MDNamespace *N) : DIScope(N) {}
847
848   StringRef getName() const { RETURN_FROM_RAW(N->getName(), ""); }
849   unsigned getLineNumber() const { RETURN_FROM_RAW(N->getLine(), 0); }
850   DIScope getContext() const {
851     RETURN_DESCRIPTOR_FROM_RAW(DIScope, N->getScope());
852   }
853   bool Verify() const;
854 };
855
856 /// \brief This is a wrapper for template type parameter.
857 class DITemplateTypeParameter : public DIDescriptor {
858   MDTemplateTypeParameter *getRaw() const {
859     return dyn_cast_or_null<MDTemplateTypeParameter>(get());
860   }
861
862 public:
863   explicit DITemplateTypeParameter(const MDNode *N = nullptr)
864       : DIDescriptor(N) {}
865   DITemplateTypeParameter(const MDTemplateTypeParameter *N) : DIDescriptor(N) {}
866
867   StringRef getName() const { RETURN_FROM_RAW(N->getName(), ""); }
868
869   DITypeRef getType() const { RETURN_REF_FROM_RAW(DITypeRef, N->getType()); }
870   bool Verify() const;
871 };
872
873 /// \brief This is a wrapper for template value parameter.
874 class DITemplateValueParameter : public DIDescriptor {
875   MDTemplateValueParameter *getRaw() const {
876     return dyn_cast_or_null<MDTemplateValueParameter>(get());
877   }
878
879 public:
880   explicit DITemplateValueParameter(const MDNode *N = nullptr)
881       : DIDescriptor(N) {}
882   DITemplateValueParameter(const MDTemplateValueParameter *N)
883       : DIDescriptor(N) {}
884
885   StringRef getName() const { RETURN_FROM_RAW(N->getName(), ""); }
886   DITypeRef getType() const { RETURN_REF_FROM_RAW(DITypeRef, N->getType()); }
887   Metadata *getValue() const { RETURN_FROM_RAW(N->getValue(), nullptr); }
888   bool Verify() const;
889 };
890
891 /// \brief This is a wrapper for a global variable.
892 class DIGlobalVariable : public DIDescriptor {
893   MDGlobalVariable *getRaw() const {
894     return dyn_cast_or_null<MDGlobalVariable>(get());
895   }
896
897   DIFile getFile() const { RETURN_DESCRIPTOR_FROM_RAW(DIFile, N->getFile()); }
898
899 public:
900   explicit DIGlobalVariable(const MDNode *N = nullptr) : DIDescriptor(N) {}
901   DIGlobalVariable(const MDGlobalVariable *N) : DIDescriptor(N) {}
902
903   StringRef getName() const { RETURN_FROM_RAW(N->getName(), ""); }
904   StringRef getDisplayName() const { RETURN_FROM_RAW(N->getDisplayName(), ""); }
905   StringRef getLinkageName() const { RETURN_FROM_RAW(N->getLinkageName(), ""); }
906   unsigned getLineNumber() const { RETURN_FROM_RAW(N->getLine(), 0); }
907   unsigned isLocalToUnit() const { RETURN_FROM_RAW(N->isLocalToUnit(), 0); }
908   unsigned isDefinition() const { RETURN_FROM_RAW(N->isDefinition(), 0); }
909
910   DIScope getContext() const {
911     RETURN_DESCRIPTOR_FROM_RAW(DIScope, N->getScope());
912   }
913   StringRef getFilename() const { return getFile().getFilename(); }
914   StringRef getDirectory() const { return getFile().getDirectory(); }
915   DITypeRef getType() const { RETURN_REF_FROM_RAW(DITypeRef, N->getType()); }
916
917   GlobalVariable *getGlobal() const;
918   Constant *getConstant() const {
919     if (auto *N = getRaw())
920       if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getVariable()))
921         return C->getValue();
922     return nullptr;
923   }
924   DIDerivedType getStaticDataMemberDeclaration() const {
925     RETURN_DESCRIPTOR_FROM_RAW(DIDerivedType,
926                                N->getStaticDataMemberDeclaration());
927   }
928
929   bool Verify() const;
930 };
931
932 /// \brief This is a wrapper for a variable (e.g. parameter, local, global etc).
933 class DIVariable : public DIDescriptor {
934   MDLocalVariable *getRaw() const {
935     return dyn_cast_or_null<MDLocalVariable>(get());
936   }
937
938   unsigned getFlags() const { RETURN_FROM_RAW(N->getFlags(), 0); }
939
940 public:
941   explicit DIVariable(const MDNode *N = nullptr) : DIDescriptor(N) {}
942   DIVariable(const MDLocalVariable *N) : DIDescriptor(N) {}
943
944   StringRef getName() const { RETURN_FROM_RAW(N->getName(), ""); }
945   unsigned getLineNumber() const { RETURN_FROM_RAW(N->getLine(), 0); }
946   unsigned getArgNumber() const { RETURN_FROM_RAW(N->getArg(), 0); }
947
948   DIScope getContext() const {
949     RETURN_DESCRIPTOR_FROM_RAW(DIScope, N->getScope());
950   }
951   DIFile getFile() const { RETURN_DESCRIPTOR_FROM_RAW(DIFile, N->getFile()); }
952   DITypeRef getType() const { RETURN_REF_FROM_RAW(DITypeRef, N->getType()); }
953
954   /// \brief Return true if this variable is marked as "artificial".
955   bool isArtificial() const {
956     return (getFlags() & FlagArtificial) != 0;
957   }
958
959   bool isObjectPointer() const {
960     return (getFlags() & FlagObjectPointer) != 0;
961   }
962
963   /// \brief If this variable is inlined then return inline location.
964   MDNode *getInlinedAt() const {
965     RETURN_DESCRIPTOR_FROM_RAW(DIDescriptor, N->getInlinedAt());
966   }
967
968   bool Verify() const;
969
970   /// \brief Check if this is a "__block" variable (Apple Blocks).
971   bool isBlockByrefVariable(const DITypeIdentifierMap &Map) const {
972     return (getType().resolve(Map)).isBlockByrefStruct();
973   }
974
975   /// \brief Check if this is an inlined function argument.
976   bool isInlinedFnArgument(const Function *CurFn);
977
978   /// \brief Return the size reported by the variable's type.
979   unsigned getSizeInBits(const DITypeIdentifierMap &Map);
980
981   void printExtendedName(raw_ostream &OS) const;
982 };
983
984 /// \brief A complex location expression in postfix notation.
985 ///
986 /// This is (almost) a DWARF expression that modifies the location of a
987 /// variable or (or the location of a single piece of a variable).
988 ///
989 /// FIXME: Instead of DW_OP_plus taking an argument, this should use DW_OP_const
990 /// and have DW_OP_plus consume the topmost elements on the stack.
991 class DIExpression : public DIDescriptor {
992   MDExpression *getRaw() const { return dyn_cast_or_null<MDExpression>(get()); }
993
994 public:
995   explicit DIExpression(const MDNode *N = nullptr) : DIDescriptor(N) {}
996   DIExpression(const MDExpression *N) : DIDescriptor(N) {}
997
998   bool Verify() const;
999
1000   /// \brief Return the number of elements in the complex expression.
1001   unsigned getNumElements() const { RETURN_FROM_RAW(N->getNumElements(), 0); }
1002
1003   /// \brief return the Idx'th complex address element.
1004   uint64_t getElement(unsigned I) const {
1005     return cast<MDExpression>(get())->getElement(I);
1006   }
1007
1008   /// \brief Return whether this is a piece of an aggregate variable.
1009   bool isBitPiece() const;
1010   /// \brief Return the offset of this piece in bits.
1011   uint64_t getBitPieceOffset() const;
1012   /// \brief Return the size of this piece in bits.
1013   uint64_t getBitPieceSize() const;
1014
1015   class iterator;
1016   /// \brief A lightweight wrapper around an element of a DIExpression.
1017   class Operand {
1018     friend class iterator;
1019     MDExpression::element_iterator I;
1020     Operand() {}
1021     Operand(MDExpression::element_iterator I) : I(I) {}
1022   public:
1023     /// \brief Operands such as DW_OP_piece have explicit (non-stack) arguments.
1024     /// Argument 0 is the operand itself.
1025     uint64_t getArg(unsigned N) const {
1026       MDExpression::element_iterator In = I;
1027       std::advance(In, N);
1028       return *In;
1029     }
1030     operator uint64_t () const { return *I; }
1031     /// \brief Returns underlying MDExpression::element_iterator.
1032     const MDExpression::element_iterator &getBase() const { return I; }
1033     /// \brief Returns the next operand.
1034     Operand getNext() const;
1035   };
1036
1037   /// \brief An iterator for DIExpression elements.
1038   class iterator : public std::iterator<std::input_iterator_tag, StringRef,
1039                                         unsigned, const Operand*, Operand> {
1040     friend class Operand;
1041     MDExpression::element_iterator I;
1042     Operand Tmp;
1043
1044   public:
1045     iterator(MDExpression::element_iterator I) : I(I) {}
1046     const Operand &operator*() { return Tmp = Operand(I); }
1047     const Operand *operator->() { return &(Tmp = Operand(I)); }
1048     iterator &operator++() {
1049       increment();
1050       return *this;
1051     }
1052     iterator operator++(int) {
1053       iterator X(*this);
1054       increment();
1055       return X;
1056     }
1057     bool operator==(const iterator &X) const { return I == X.I; }
1058     bool operator!=(const iterator &X) const { return !(*this == X); }
1059
1060   private:
1061     void increment() {
1062       switch (**this) {
1063       case dwarf::DW_OP_bit_piece: std::advance(I, 3); break;
1064       case dwarf::DW_OP_plus:      std::advance(I, 2); break;
1065       case dwarf::DW_OP_deref:     std::advance(I, 1); break;
1066       default:
1067         llvm_unreachable("unsupported operand");
1068       }
1069     }
1070   };
1071
1072   iterator begin() const { return cast<MDExpression>(get())->elements_begin(); }
1073   iterator end() const { return cast<MDExpression>(get())->elements_end(); }
1074 };
1075
1076 /// \brief This object holds location information.
1077 ///
1078 /// This object is not associated with any DWARF tag.
1079 class DILocation : public DIDescriptor {
1080   MDLocation *getRaw() const { return dyn_cast_or_null<MDLocation>(get()); }
1081
1082 public:
1083   explicit DILocation(const MDNode *N) : DIDescriptor(N) {}
1084
1085   unsigned getLineNumber() const { RETURN_FROM_RAW(N->getLine(), 0); }
1086   unsigned getColumnNumber() const { RETURN_FROM_RAW(N->getColumn(), 0); }
1087   DIScope getScope() const {
1088     RETURN_DESCRIPTOR_FROM_RAW(DIScope, N->getScope());
1089   }
1090   DILocation getOrigLocation() const {
1091     RETURN_DESCRIPTOR_FROM_RAW(DILocation, N->getInlinedAt());
1092   }
1093   StringRef getFilename() const { return getScope().getFilename(); }
1094   StringRef getDirectory() const { return getScope().getDirectory(); }
1095   bool Verify() const;
1096   bool atSameLineAs(const DILocation &Other) const {
1097     return (getLineNumber() == Other.getLineNumber() &&
1098             getFilename() == Other.getFilename());
1099   }
1100   /// \brief Get the DWAF discriminator.
1101   ///
1102   /// DWARF discriminators are used to distinguish identical file locations for
1103   /// instructions that are on different basic blocks. If two instructions are
1104   /// inside the same lexical block and are in different basic blocks, we
1105   /// create a new lexical block with identical location as the original but
1106   /// with a different discriminator value
1107   /// (lib/Transforms/Util/AddDiscriminators.cpp for details).
1108   unsigned getDiscriminator() const {
1109     // Since discriminators are associated with lexical blocks, make
1110     // sure this location is a lexical block before retrieving its
1111     // value.
1112     return getScope().isLexicalBlockFile()
1113                ? DILexicalBlockFile(
1114                      cast<MDNode>(cast<MDLocation>(DbgNode)->getScope()))
1115                      .getDiscriminator()
1116                : 0;
1117   }
1118
1119   /// \brief Generate a new discriminator value for this location.
1120   unsigned computeNewDiscriminator(LLVMContext &Ctx);
1121
1122   /// \brief Return a copy of this location with a different scope.
1123   DILocation copyWithNewScope(LLVMContext &Ctx, DILexicalBlockFile NewScope);
1124 };
1125
1126 class DIObjCProperty : public DIDescriptor {
1127   MDObjCProperty *getRaw() const {
1128     return dyn_cast_or_null<MDObjCProperty>(get());
1129   }
1130
1131 public:
1132   explicit DIObjCProperty(const MDNode *N) : DIDescriptor(N) {}
1133   DIObjCProperty(const MDObjCProperty *N) : DIDescriptor(N) {}
1134
1135   StringRef getObjCPropertyName() const { RETURN_FROM_RAW(N->getName(), ""); }
1136   DIFile getFile() const { RETURN_DESCRIPTOR_FROM_RAW(DIFile, N->getFile()); }
1137   unsigned getLineNumber() const { RETURN_FROM_RAW(N->getLine(), 0); }
1138
1139   StringRef getObjCPropertyGetterName() const {
1140     RETURN_FROM_RAW(N->getGetterName(), "");
1141   }
1142   StringRef getObjCPropertySetterName() const {
1143     RETURN_FROM_RAW(N->getSetterName(), "");
1144   }
1145   unsigned getAttributes() const { RETURN_FROM_RAW(N->getAttributes(), 0); }
1146   bool isReadOnlyObjCProperty() const {
1147     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readonly) != 0;
1148   }
1149   bool isReadWriteObjCProperty() const {
1150     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readwrite) != 0;
1151   }
1152   bool isAssignObjCProperty() const {
1153     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_assign) != 0;
1154   }
1155   bool isRetainObjCProperty() const {
1156     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_retain) != 0;
1157   }
1158   bool isCopyObjCProperty() const {
1159     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_copy) != 0;
1160   }
1161   bool isNonAtomicObjCProperty() const {
1162     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_nonatomic) != 0;
1163   }
1164
1165   /// \brief Get the type.
1166   ///
1167   /// \note Objective-C doesn't have an ODR, so there is no benefit in storing
1168   /// the type as a DITypeRef here.
1169   DIType getType() const { RETURN_DESCRIPTOR_FROM_RAW(DIType, N->getType()); }
1170
1171   bool Verify() const;
1172 };
1173
1174 /// \brief An imported module (C++ using directive or similar).
1175 class DIImportedEntity : public DIDescriptor {
1176   MDImportedEntity *getRaw() const {
1177     return dyn_cast_or_null<MDImportedEntity>(get());
1178   }
1179
1180 public:
1181   DIImportedEntity() = default;
1182   explicit DIImportedEntity(const MDNode *N) : DIDescriptor(N) {}
1183   DIImportedEntity(const MDImportedEntity *N) : DIDescriptor(N) {}
1184
1185   DIScope getContext() const {
1186     RETURN_DESCRIPTOR_FROM_RAW(DIScope, N->getScope());
1187   }
1188   DIDescriptorRef getEntity() const {
1189     RETURN_REF_FROM_RAW(DIDescriptorRef, N->getEntity());
1190   }
1191   unsigned getLineNumber() const { RETURN_FROM_RAW(N->getLine(), 0); }
1192   StringRef getName() const { RETURN_FROM_RAW(N->getName(), ""); }
1193   bool Verify() const;
1194 };
1195
1196 #undef RETURN_FROM_RAW
1197 #undef RETURN_DESCRIPTOR_FROM_RAW
1198 #undef RETURN_REF_FROM_RAW
1199
1200 /// \brief Find subprogram that is enclosing this scope.
1201 DISubprogram getDISubprogram(const MDNode *Scope);
1202
1203 /// \brief Find debug info for a given function.
1204 /// \returns a valid DISubprogram, if found. Otherwise, it returns an empty
1205 /// DISubprogram.
1206 DISubprogram getDISubprogram(const Function *F);
1207
1208 /// \brief Find underlying composite type.
1209 DICompositeType getDICompositeType(DIType T);
1210
1211 /// \brief Create a new inlined variable based on current variable.
1212 ///
1213 /// @param DV            Current Variable.
1214 /// @param InlinedScope  Location at current variable is inlined.
1215 DIVariable createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
1216                                  LLVMContext &VMContext);
1217
1218 /// \brief Remove inlined scope from the variable.
1219 DIVariable cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext);
1220
1221 /// \brief Generate map by visiting all retained types.
1222 DITypeIdentifierMap generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes);
1223
1224 /// \brief Strip debug info in the module if it exists.
1225 ///
1226 /// To do this, we remove all calls to the debugger intrinsics and any named
1227 /// metadata for debugging. We also remove debug locations for instructions.
1228 /// Return true if module is modified.
1229 bool StripDebugInfo(Module &M);
1230
1231 /// \brief Return Debug Info Metadata Version by checking module flags.
1232 unsigned getDebugMetadataVersionFromModule(const Module &M);
1233
1234 /// \brief Utility to find all debug info in a module.
1235 ///
1236 /// DebugInfoFinder tries to list all debug info MDNodes used in a module. To
1237 /// list debug info MDNodes used by an instruction, DebugInfoFinder uses
1238 /// processDeclare, processValue and processLocation to handle DbgDeclareInst,
1239 /// DbgValueInst and DbgLoc attached to instructions. processModule will go
1240 /// through all DICompileUnits in llvm.dbg.cu and list debug info MDNodes
1241 /// used by the CUs.
1242 class DebugInfoFinder {
1243 public:
1244   DebugInfoFinder() : TypeMapInitialized(false) {}
1245
1246   /// \brief Process entire module and collect debug info anchors.
1247   void processModule(const Module &M);
1248
1249   /// \brief Process DbgDeclareInst.
1250   void processDeclare(const Module &M, const DbgDeclareInst *DDI);
1251   /// \brief Process DbgValueInst.
1252   void processValue(const Module &M, const DbgValueInst *DVI);
1253   /// \brief Process DILocation.
1254   void processLocation(const Module &M, DILocation Loc);
1255
1256   /// \brief Process DIExpression.
1257   void processExpression(DIExpression Expr);
1258
1259   /// \brief Clear all lists.
1260   void reset();
1261
1262 private:
1263   void InitializeTypeMap(const Module &M);
1264
1265   void processType(DIType DT);
1266   void processSubprogram(DISubprogram SP);
1267   void processScope(DIScope Scope);
1268   bool addCompileUnit(DICompileUnit CU);
1269   bool addGlobalVariable(DIGlobalVariable DIG);
1270   bool addSubprogram(DISubprogram SP);
1271   bool addType(DIType DT);
1272   bool addScope(DIScope Scope);
1273
1274 public:
1275   typedef SmallVectorImpl<DICompileUnit>::const_iterator compile_unit_iterator;
1276   typedef SmallVectorImpl<DISubprogram>::const_iterator subprogram_iterator;
1277   typedef SmallVectorImpl<DIGlobalVariable>::const_iterator
1278       global_variable_iterator;
1279   typedef SmallVectorImpl<DIType>::const_iterator type_iterator;
1280   typedef SmallVectorImpl<DIScope>::const_iterator scope_iterator;
1281
1282   iterator_range<compile_unit_iterator> compile_units() const {
1283     return iterator_range<compile_unit_iterator>(CUs.begin(), CUs.end());
1284   }
1285
1286   iterator_range<subprogram_iterator> subprograms() const {
1287     return iterator_range<subprogram_iterator>(SPs.begin(), SPs.end());
1288   }
1289
1290   iterator_range<global_variable_iterator> global_variables() const {
1291     return iterator_range<global_variable_iterator>(GVs.begin(), GVs.end());
1292   }
1293
1294   iterator_range<type_iterator> types() const {
1295     return iterator_range<type_iterator>(TYs.begin(), TYs.end());
1296   }
1297
1298   iterator_range<scope_iterator> scopes() const {
1299     return iterator_range<scope_iterator>(Scopes.begin(), Scopes.end());
1300   }
1301
1302   unsigned compile_unit_count() const { return CUs.size(); }
1303   unsigned global_variable_count() const { return GVs.size(); }
1304   unsigned subprogram_count() const { return SPs.size(); }
1305   unsigned type_count() const { return TYs.size(); }
1306   unsigned scope_count() const { return Scopes.size(); }
1307
1308 private:
1309   SmallVector<DICompileUnit, 8> CUs;
1310   SmallVector<DISubprogram, 8> SPs;
1311   SmallVector<DIGlobalVariable, 8> GVs;
1312   SmallVector<DIType, 8> TYs;
1313   SmallVector<DIScope, 8> Scopes;
1314   SmallPtrSet<MDNode *, 64> NodesSeen;
1315   DITypeIdentifierMap TypeIdentifierMap;
1316
1317   /// \brief Specify if TypeIdentifierMap is initialized.
1318   bool TypeMapInitialized;
1319 };
1320
1321 DenseMap<const Function *, DISubprogram> makeSubprogramMap(const Module &M);
1322
1323 } // end namespace llvm
1324
1325 #endif