OSDN Git Service

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