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