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