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