bf15d588be5f28a0930313089a31607fe2694ea1
[oota-llvm.git] / include / llvm / IR / DebugInfo.h
1 //===- DebugInfo.h - Debug Information Helpers ------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a bunch of datatypes that are useful for creating and
11 // walking debug info in LLVM IR form. They essentially provide wrappers around
12 // the information in the global variables that's needed when constructing the
13 // DWARF information.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #ifndef LLVM_IR_DEBUGINFO_H
18 #define LLVM_IR_DEBUGINFO_H
19
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/iterator_range.h"
25 #include "llvm/IR/DebugInfoMetadata.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include <iterator>
30
31 namespace llvm {
32 class BasicBlock;
33 class Constant;
34 class Function;
35 class GlobalVariable;
36 class Module;
37 class Type;
38 class Value;
39 class DbgDeclareInst;
40 class DbgValueInst;
41 class Instruction;
42 class Metadata;
43 class MDNode;
44 class MDString;
45 class NamedMDNode;
46 class LLVMContext;
47 class raw_ostream;
48
49 class DIFile;
50 class DISubprogram;
51 class DILexicalBlock;
52 class DILexicalBlockFile;
53 class DIVariable;
54 class DIType;
55 class DIScope;
56 class DIObjCProperty;
57
58 /// \brief Maps from type identifier to the actual MDNode.
59 typedef DenseMap<const MDString *, MDNode *> DITypeIdentifierMap;
60
61 class DIHeaderFieldIterator
62     : public std::iterator<std::input_iterator_tag, StringRef, std::ptrdiff_t,
63                            const StringRef *, StringRef> {
64   StringRef Header;
65   StringRef Current;
66
67 public:
68   DIHeaderFieldIterator() {}
69   explicit DIHeaderFieldIterator(StringRef Header)
70       : Header(Header), Current(Header.slice(0, Header.find('\0'))) {}
71   StringRef operator*() const { return Current; }
72   const StringRef *operator->() const { return &Current; }
73   DIHeaderFieldIterator &operator++() {
74     increment();
75     return *this;
76   }
77   DIHeaderFieldIterator operator++(int) {
78     DIHeaderFieldIterator X(*this);
79     increment();
80     return X;
81   }
82   bool operator==(const DIHeaderFieldIterator &X) const {
83     return Current.data() == X.Current.data();
84   }
85   bool operator!=(const DIHeaderFieldIterator &X) const {
86     return !(*this == X);
87   }
88
89   StringRef getHeader() const { return Header; }
90   StringRef getCurrent() const { return Current; }
91   StringRef getPrefix() const {
92     if (Current.begin() == Header.begin())
93       return StringRef();
94     return Header.slice(0, Current.begin() - Header.begin() - 1);
95   }
96   StringRef getSuffix() const {
97     if (Current.end() == Header.end())
98       return StringRef();
99     return Header.slice(Current.end() - Header.begin() + 1, StringRef::npos);
100   }
101
102   /// \brief Get the current field as a number.
103   ///
104   /// Convert the current field into a number.  Return \c 0 on error.
105   template <class T> T getNumber() const {
106     T Int;
107     if (getCurrent().getAsInteger(0, Int))
108       return 0;
109     return Int;
110   }
111
112 private:
113   void increment() {
114     assert(Current.data() != nullptr && "Cannot increment past the end");
115     StringRef Suffix = getSuffix();
116     Current = Suffix.slice(0, Suffix.find('\0'));
117   }
118 };
119
120 /// \brief A thin wraper around MDNode to access encoded debug info.
121 ///
122 /// This should not be stored in a container, because the underlying MDNode may
123 /// change in certain situations.
124 class DIDescriptor {
125   // Befriends DIRef so DIRef can befriend the protected member
126   // function: getFieldAs<DIRef>.
127   template <typename T> friend class DIRef;
128
129 public:
130   /// \brief Accessibility flags.
131   ///
132   /// The three accessibility flags are mutually exclusive and rolled together
133   /// in the first two bits.
134   enum {
135 #define HANDLE_DI_FLAG(ID, NAME) Flag##NAME = ID,
136 #include "llvm/IR/DebugInfoFlags.def"
137     FlagAccessibility = FlagPrivate | FlagProtected | FlagPublic
138   };
139
140 protected:
141   const MDNode *DbgNode;
142
143   StringRef getStringField(unsigned Elt) const;
144   unsigned getUnsignedField(unsigned Elt) const {
145     return (unsigned)getUInt64Field(Elt);
146   }
147   uint64_t getUInt64Field(unsigned Elt) const;
148   int64_t getInt64Field(unsigned Elt) const;
149   DIDescriptor getDescriptorField(unsigned Elt) const;
150
151   template <typename DescTy> DescTy getFieldAs(unsigned Elt) const {
152     return DescTy(getDescriptorField(Elt));
153   }
154
155   GlobalVariable *getGlobalVariableField(unsigned Elt) const;
156   Constant *getConstantField(unsigned Elt) const;
157   Function *getFunctionField(unsigned Elt) const;
158   void replaceFunctionField(unsigned Elt, Function *F);
159
160 public:
161   explicit DIDescriptor(const MDNode *N = nullptr) : DbgNode(N) {}
162
163   bool Verify() const;
164
165   MDNode *get() const { return const_cast<MDNode *>(DbgNode); }
166   operator MDNode *() const { return get(); }
167   MDNode *operator->() const { return get(); }
168
169   // An explicit operator bool so that we can do testing of DI values
170   // easily.
171   // FIXME: This operator bool isn't actually protecting anything at the
172   // moment due to the conversion operator above making DIDescriptor nodes
173   // implicitly convertable to bool.
174   explicit operator bool() const { return DbgNode != nullptr; }
175
176   bool operator==(DIDescriptor Other) const { return DbgNode == Other.DbgNode; }
177   bool operator!=(DIDescriptor Other) const { return !operator==(Other); }
178
179   StringRef getHeader() const { return getStringField(0); }
180
181   size_t getNumHeaderFields() const {
182     return std::distance(DIHeaderFieldIterator(getHeader()),
183                          DIHeaderFieldIterator());
184   }
185
186   DIHeaderFieldIterator header_begin() const {
187     return DIHeaderFieldIterator(getHeader());
188   }
189   DIHeaderFieldIterator header_end() const { return DIHeaderFieldIterator(); }
190
191   DIHeaderFieldIterator getHeaderIterator(unsigned Index) const {
192     // Since callers expect an empty string for out-of-range accesses, we can't
193     // use std::advance() here.
194     for (auto I = header_begin(), E = header_end(); I != E; ++I, --Index)
195       if (!Index)
196         return I;
197     return header_end();
198   }
199
200   StringRef getHeaderField(unsigned Index) const {
201     return *getHeaderIterator(Index);
202   }
203
204   template <class T> T getHeaderFieldAs(unsigned Index) const {
205     return getHeaderIterator(Index).getNumber<T>();
206   }
207
208   uint16_t getTag() const { return getHeaderFieldAs<uint16_t>(0); }
209
210   bool isDerivedType() const;
211   bool isCompositeType() const;
212   bool isSubroutineType() const;
213   bool isBasicType() const;
214   bool isVariable() const;
215   bool isSubprogram() const;
216   bool isGlobalVariable() const;
217   bool isScope() const;
218   bool isFile() const;
219   bool isCompileUnit() const;
220   bool isNameSpace() const;
221   bool isLexicalBlockFile() const;
222   bool isLexicalBlock() const;
223   bool isSubrange() const;
224   bool isEnumerator() const;
225   bool isType() const;
226   bool isTemplateTypeParameter() const;
227   bool isTemplateValueParameter() const;
228   bool isObjCProperty() const;
229   bool isImportedEntity() const;
230   bool isExpression() const;
231
232   void print(raw_ostream &OS) const;
233   void dump() const;
234
235   /// \brief Replace all uses of debug info referenced by this descriptor.
236   void replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D);
237   void replaceAllUsesWith(MDNode *D);
238 };
239
240 #define RETURN_FROM_RAW(VALID, DEFAULT)                                        \
241   do {                                                                         \
242     if (auto *N = getRaw())                                                    \
243       return VALID;                                                            \
244     return DEFAULT;                                                            \
245   } while (false)
246 #define RETURN_DESCRIPTOR_FROM_RAW(DESC, VALID)                                \
247   do {                                                                         \
248     if (auto *N = getRaw())                                                    \
249       return DESC(dyn_cast_or_null<MDNode>(VALID));                            \
250     return DESC(static_cast<const MDNode *>(nullptr));                         \
251   } while (false)
252
253 /// \brief This is used to represent ranges, for array bounds.
254 class DISubrange : public DIDescriptor {
255   friend class DIDescriptor;
256   void printInternal(raw_ostream &OS) const;
257
258 public:
259   explicit DISubrange(const MDNode *N = nullptr) : DIDescriptor(N) {}
260
261   int64_t getLo() const { return getHeaderFieldAs<int64_t>(1); }
262   int64_t getCount() const { return getHeaderFieldAs<int64_t>(2); }
263   bool Verify() const;
264 };
265
266 /// \brief This descriptor holds an array of nodes with type T.
267 template <typename T> class DITypedArray : public DIDescriptor {
268 public:
269   explicit DITypedArray(const MDNode *N = nullptr) : DIDescriptor(N) {}
270   unsigned getNumElements() const {
271     return DbgNode ? DbgNode->getNumOperands() : 0;
272   }
273   T getElement(unsigned Idx) const { return getFieldAs<T>(Idx); }
274 };
275
276 typedef DITypedArray<DIDescriptor> DIArray;
277
278 /// \brief A wrapper for an enumerator (e.g. X and Y in 'enum {X,Y}').
279 ///
280 /// FIXME: it seems strange that this doesn't have either a reference to the
281 /// type/precision or a file/line pair for location info.
282 class DIEnumerator : public DIDescriptor {
283   friend class DIDescriptor;
284   void printInternal(raw_ostream &OS) const;
285
286 public:
287   explicit DIEnumerator(const MDNode *N = nullptr) : DIDescriptor(N) {}
288
289   StringRef getName() const { return getHeaderField(1); }
290   int64_t getEnumValue() const { return getHeaderFieldAs<int64_t>(2); }
291   bool Verify() const;
292 };
293
294 template <typename T> class DIRef;
295 typedef DIRef<DIDescriptor> DIDescriptorRef;
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 DIDescriptors.
386 template <>
387 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const;
388 /// \brief Specialize DIRef constructor for DIDescriptorRef.
389 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V);
390
391 /// \brief Handle fields that are references to DIScopes.
392 template <> DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const;
393 /// \brief Specialize DIRef constructor for DIScopeRef.
394 template <> DIRef<DIScope>::DIRef(const Metadata *V);
395
396 /// \brief Handle fields that are references to DITypes.
397 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const;
398 /// \brief Specialize DIRef constructor for DITypeRef.
399 template <> DIRef<DIType>::DIRef(const Metadata *V);
400
401 /// \brief This is a wrapper for a type.
402 ///
403 /// FIXME: Types should be factored much better so that CV qualifiers and
404 /// others do not require a huge and empty descriptor full of zeros.
405 class DIType : public DIScope {
406 protected:
407   friend class DIDescriptor;
408   void printInternal(raw_ostream &OS) const;
409
410 public:
411   explicit DIType(const MDNode *N = nullptr) : DIScope(N) {}
412   operator DITypeRef() const {
413     assert(isType() &&
414            "constructing DITypeRef from an MDNode that is not a type");
415     return DITypeRef(&*getRef());
416   }
417
418   bool Verify() const;
419
420   DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(2); }
421   StringRef getName() const { return getHeaderField(1); }
422   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
423   uint64_t getSizeInBits() const { return getHeaderFieldAs<unsigned>(3); }
424   uint64_t getAlignInBits() const { return getHeaderFieldAs<unsigned>(4); }
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 { return getHeaderFieldAs<unsigned>(5); }
428   unsigned getFlags() const { return getHeaderFieldAs<unsigned>(6); }
429   bool isPrivate() const {
430     return (getFlags() & FlagAccessibility) == FlagPrivate;
431   }
432   bool isProtected() const {
433     return (getFlags() & FlagAccessibility) == FlagProtected;
434   }
435   bool isPublic() const {
436     return (getFlags() & FlagAccessibility) == FlagPublic;
437   }
438   bool isForwardDecl() const { return (getFlags() & FlagFwdDecl) != 0; }
439   bool isAppleBlockExtension() const {
440     return (getFlags() & FlagAppleBlock) != 0;
441   }
442   bool isBlockByrefStruct() const {
443     return (getFlags() & FlagBlockByrefStruct) != 0;
444   }
445   bool isVirtual() const { return (getFlags() & FlagVirtual) != 0; }
446   bool isArtificial() const { return (getFlags() & FlagArtificial) != 0; }
447   bool isObjectPointer() const { return (getFlags() & FlagObjectPointer) != 0; }
448   bool isObjcClassComplete() const {
449     return (getFlags() & FlagObjcClassComplete) != 0;
450   }
451   bool isVector() const { return (getFlags() & FlagVector) != 0; }
452   bool isStaticMember() const { return (getFlags() & FlagStaticMember) != 0; }
453   bool isLValueReference() const {
454     return (getFlags() & FlagLValueReference) != 0;
455   }
456   bool isRValueReference() const {
457     return (getFlags() & FlagRValueReference) != 0;
458   }
459   bool isValid() const { return DbgNode && isType(); }
460 };
461
462 /// \brief A basic type, like 'int' or 'float'.
463 class DIBasicType : public DIType {
464 public:
465   explicit DIBasicType(const MDNode *N = nullptr) : DIType(N) {}
466
467   unsigned getEncoding() const { return getHeaderFieldAs<unsigned>(7); }
468
469   bool Verify() const;
470 };
471
472 /// \brief A simple derived type
473 ///
474 /// Like a const qualified type, a typedef, a pointer or reference, et cetera.
475 /// Or, a data member of a class/struct/union.
476 class DIDerivedType : public DIType {
477   friend class DIDescriptor;
478   void printInternal(raw_ostream &OS) const;
479
480 public:
481   explicit DIDerivedType(const MDNode *N = nullptr) : DIType(N) {}
482
483   DITypeRef getTypeDerivedFrom() const { return getFieldAs<DITypeRef>(3); }
484
485   /// \brief Return property node, if this ivar is associated with one.
486   MDNode *getObjCProperty() const;
487
488   DITypeRef getClassType() const {
489     assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
490     return getFieldAs<DITypeRef>(4);
491   }
492
493   Constant *getConstant() const {
494     assert((getTag() == dwarf::DW_TAG_member) && isStaticMember());
495     return getConstantField(4);
496   }
497
498   bool Verify() const;
499 };
500
501 /// \brief Types that refer to multiple other types.
502 ///
503 /// This descriptor holds a type that can refer to multiple other types, like a
504 /// function or struct.
505 ///
506 /// DICompositeType is derived from DIDerivedType because some
507 /// composite types (such as enums) can be derived from basic types
508 // FIXME: Make this derive from DIType directly & just store the
509 // base type in a single DIType field.
510 class DICompositeType : public DIDerivedType {
511   friend class DIBuilder;
512   friend class DIDescriptor;
513   void printInternal(raw_ostream &OS) const;
514
515   /// \brief Set the array of member DITypes.
516   void setArraysHelper(MDNode *Elements, MDNode *TParams);
517
518 public:
519   explicit DICompositeType(const MDNode *N = nullptr) : DIDerivedType(N) {}
520
521   DIArray getElements() const {
522     assert(!isSubroutineType() && "no elements for DISubroutineType");
523     return getFieldAs<DIArray>(4);
524   }
525
526 private:
527   template <typename T>
528   void setArrays(DITypedArray<T> Elements, DIArray TParams = DIArray()) {
529     assert(
530         (!TParams || DbgNode->getNumOperands() == 8) &&
531         "If you're setting the template parameters this should include a slot "
532         "for that!");
533     setArraysHelper(Elements, TParams);
534   }
535
536 public:
537   unsigned getRunTimeLang() const { return getHeaderFieldAs<unsigned>(7); }
538   DITypeRef getContainingType() const { return getFieldAs<DITypeRef>(5); }
539
540 private:
541   /// \brief Set the containing type.
542   void setContainingType(DICompositeType ContainingType);
543
544 public:
545   DIArray getTemplateParams() const { return getFieldAs<DIArray>(6); }
546   MDString *getIdentifier() const;
547
548   bool Verify() const;
549 };
550
551 class DISubroutineType : public DICompositeType {
552 public:
553   explicit DISubroutineType(const MDNode *N = nullptr) : DICompositeType(N) {}
554   DITypedArray<DITypeRef> getTypeArray() const {
555     return getFieldAs<DITypedArray<DITypeRef>>(4);
556   }
557 };
558
559 /// \brief This is a wrapper for a file.
560 class DIFile : public DIScope {
561   friend class DIDescriptor;
562
563 public:
564   explicit DIFile(const MDNode *N = nullptr) : DIScope(N) {}
565
566   /// \brief Retrieve the MDNode for the directory/file pair.
567   MDNode *getFileNode() const;
568   bool Verify() const;
569 };
570
571 /// \brief A wrapper for a compile unit.
572 class DICompileUnit : public DIScope {
573   friend class DIDescriptor;
574   void printInternal(raw_ostream &OS) const;
575
576 public:
577   explicit DICompileUnit(const MDNode *N = nullptr) : DIScope(N) {}
578
579   dwarf::SourceLanguage getLanguage() const {
580     return static_cast<dwarf::SourceLanguage>(getHeaderFieldAs<unsigned>(1));
581   }
582   StringRef getProducer() const { return getHeaderField(2); }
583
584   bool isOptimized() const { return getHeaderFieldAs<bool>(3) != 0; }
585   StringRef getFlags() const { return getHeaderField(4); }
586   unsigned getRunTimeVersion() const { return getHeaderFieldAs<unsigned>(5); }
587
588   DIArray getEnumTypes() const;
589   DIArray getRetainedTypes() const;
590   DIArray getSubprograms() const;
591   DIArray getGlobalVariables() const;
592   DIArray getImportedEntities() const;
593
594   void replaceSubprograms(DIArray Subprograms);
595   void replaceGlobalVariables(DIArray GlobalVariables);
596
597   StringRef getSplitDebugFilename() const { return getHeaderField(6); }
598   unsigned getEmissionKind() const { return getHeaderFieldAs<unsigned>(7); }
599
600   bool Verify() const;
601 };
602
603 /// \brief This is a wrapper for a subprogram (e.g. a function).
604 class DISubprogram : public DIScope {
605   friend class DIDescriptor;
606   void printInternal(raw_ostream &OS) const;
607
608 public:
609   explicit DISubprogram(const MDNode *N = nullptr) : DIScope(N) {}
610
611   StringRef getName() const { return getHeaderField(1); }
612   StringRef getDisplayName() const { return getHeaderField(2); }
613   StringRef getLinkageName() const { return getHeaderField(3); }
614   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(4); }
615
616   /// \brief Check if this is local (like 'static' in C).
617   unsigned isLocalToUnit() const { return getHeaderFieldAs<unsigned>(5); }
618   unsigned isDefinition() const { return getHeaderFieldAs<unsigned>(6); }
619
620   unsigned getVirtuality() const { return getHeaderFieldAs<unsigned>(7); }
621   unsigned getVirtualIndex() const { return getHeaderFieldAs<unsigned>(8); }
622
623   unsigned getFlags() const { return getHeaderFieldAs<unsigned>(9); }
624
625   unsigned isOptimized() const { return getHeaderFieldAs<bool>(10); }
626
627   /// \brief Get the beginning of the scope of the function (not the name).
628   unsigned getScopeLineNumber() const { return getHeaderFieldAs<unsigned>(11); }
629
630   DIScopeRef getContext() const { return getFieldAs<DIScopeRef>(2); }
631   DISubroutineType getType() const { return getFieldAs<DISubroutineType>(3); }
632
633   DITypeRef getContainingType() const { return getFieldAs<DITypeRef>(4); }
634
635   bool Verify() const;
636
637   /// \brief Check if this provides debugging information for the function F.
638   bool describes(const Function *F);
639
640   Function *getFunction() const { return getFunctionField(5); }
641   void replaceFunction(Function *F) { replaceFunctionField(5, F); }
642   DIArray getTemplateParams() const { return getFieldAs<DIArray>(6); }
643   DISubprogram getFunctionDeclaration() const {
644     return getFieldAs<DISubprogram>(7);
645   }
646   MDNode *getVariablesNodes() const;
647   DIArray getVariables() const;
648
649   unsigned isArtificial() const { return (getFlags() & FlagArtificial) != 0; }
650   /// \brief Check for the "private" access specifier.
651   bool isPrivate() const {
652     return (getFlags() & FlagAccessibility) == FlagPrivate;
653   }
654   /// \brief Check for the "protected" access specifier.
655   bool isProtected() const {
656     return (getFlags() & FlagAccessibility) == FlagProtected;
657   }
658   /// \brief Check for the "public" access specifier.
659   bool isPublic() const {
660     return (getFlags() & FlagAccessibility) == FlagPublic;
661   }
662   /// \brief Check for "explicit".
663   bool isExplicit() const { return (getFlags() & FlagExplicit) != 0; }
664   /// \brief Check if this is prototyped.
665   bool isPrototyped() const { return (getFlags() & FlagPrototyped) != 0; }
666
667   /// \brief Check if this is reference-qualified.
668   ///
669   /// Return true if this subprogram is a C++11 reference-qualified non-static
670   /// member function (void foo() &).
671   unsigned isLValueReference() const {
672     return (getFlags() & FlagLValueReference) != 0;
673   }
674
675   /// \brief Check if this is rvalue-reference-qualified.
676   ///
677   /// Return true if this subprogram is a C++11 rvalue-reference-qualified
678   /// non-static member function (void foo() &&).
679   unsigned isRValueReference() const {
680     return (getFlags() & FlagRValueReference) != 0;
681   }
682 };
683
684 /// \brief This is a wrapper for a lexical block.
685 class DILexicalBlock : public DIScope {
686 public:
687   explicit DILexicalBlock(const MDNode *N = nullptr) : DIScope(N) {}
688   DIScope getContext() const { return getFieldAs<DIScope>(2); }
689   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(1); }
690   unsigned getColumnNumber() const { return getHeaderFieldAs<unsigned>(2); }
691   bool Verify() const;
692 };
693
694 /// \brief This is a wrapper for a lexical block with a filename change.
695 class DILexicalBlockFile : public DIScope {
696 public:
697   explicit DILexicalBlockFile(const MDNode *N = nullptr) : DIScope(N) {}
698   DIScope getContext() const {
699     // FIXME: This logic is horrible.  getScope() returns a DILexicalBlock, but
700     // then we check if it's a subprogram?  WHAT?!?
701     if (getScope().isSubprogram())
702       return getScope();
703     return getScope().getContext();
704   }
705   unsigned getLineNumber() const { return getScope().getLineNumber(); }
706   unsigned getColumnNumber() const { return getScope().getColumnNumber(); }
707   DILexicalBlock getScope() const { return getFieldAs<DILexicalBlock>(2); }
708   unsigned getDiscriminator() const { return getHeaderFieldAs<unsigned>(1); }
709   bool Verify() const;
710 };
711
712 /// \brief A wrapper for a C++ style name space.
713 class DINameSpace : public DIScope {
714   friend class DIDescriptor;
715   void printInternal(raw_ostream &OS) const;
716
717 public:
718   explicit DINameSpace(const MDNode *N = nullptr) : DIScope(N) {}
719   StringRef getName() const { return getHeaderField(1); }
720   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
721   DIScope getContext() const { return getFieldAs<DIScope>(2); }
722   bool Verify() const;
723 };
724
725 /// \brief This is a wrapper for template type parameter.
726 class DITemplateTypeParameter : public DIDescriptor {
727 public:
728   explicit DITemplateTypeParameter(const MDNode *N = nullptr)
729       : DIDescriptor(N) {}
730
731   StringRef getName() const { return getHeaderField(1); }
732
733   DITypeRef getType() const { return getFieldAs<DITypeRef>(2); }
734   bool Verify() const;
735 };
736
737 /// \brief This is a wrapper for template value parameter.
738 class DITemplateValueParameter : public DIDescriptor {
739 public:
740   explicit DITemplateValueParameter(const MDNode *N = nullptr)
741       : DIDescriptor(N) {}
742
743   StringRef getName() const { return getHeaderField(1); }
744
745   DITypeRef getType() const { return getFieldAs<DITypeRef>(2); }
746   Metadata *getValue() const;
747   bool Verify() const;
748 };
749
750 /// \brief This is a wrapper for a global variable.
751 class DIGlobalVariable : public DIDescriptor {
752   friend class DIDescriptor;
753   void printInternal(raw_ostream &OS) const;
754
755 public:
756   explicit DIGlobalVariable(const MDNode *N = nullptr) : DIDescriptor(N) {}
757
758   StringRef getName() const { return getHeaderField(1); }
759   StringRef getDisplayName() const { return getHeaderField(2); }
760   StringRef getLinkageName() const { return getHeaderField(3); }
761   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(4); }
762   unsigned isLocalToUnit() const { return getHeaderFieldAs<bool>(5); }
763   unsigned isDefinition() const { return getHeaderFieldAs<bool>(6); }
764
765   DIScope getContext() const { return getFieldAs<DIScope>(1); }
766   StringRef getFilename() const { return getFieldAs<DIFile>(2).getFilename(); }
767   StringRef getDirectory() const {
768     return getFieldAs<DIFile>(2).getDirectory();
769   }
770   DITypeRef getType() const { return getFieldAs<DITypeRef>(3); }
771
772   GlobalVariable *getGlobal() const { return getGlobalVariableField(4); }
773   Constant *getConstant() const { return getConstantField(4); }
774   DIDerivedType getStaticDataMemberDeclaration() const {
775     return getFieldAs<DIDerivedType>(5);
776   }
777
778   bool Verify() const;
779 };
780
781 /// \brief This is a wrapper for a variable (e.g. parameter, local, global etc).
782 class DIVariable : public DIDescriptor {
783   friend class DIDescriptor;
784   void printInternal(raw_ostream &OS) const;
785
786 public:
787   explicit DIVariable(const MDNode *N = nullptr) : DIDescriptor(N) {}
788
789   StringRef getName() const { return getHeaderField(1); }
790   unsigned getLineNumber() const {
791     // FIXME: Line number and arg number shouldn't be merged together like this.
792     return (getHeaderFieldAs<unsigned>(2) << 8) >> 8;
793   }
794   unsigned getArgNumber() const { return getHeaderFieldAs<unsigned>(2) >> 24; }
795
796   DIScope getContext() const { return getFieldAs<DIScope>(1); }
797   DIFile getFile() const { return getFieldAs<DIFile>(2); }
798   DITypeRef getType() const { return getFieldAs<DITypeRef>(3); }
799
800   /// \brief Return true if this variable is marked as "artificial".
801   bool isArtificial() const {
802     return (getHeaderFieldAs<unsigned>(3) & FlagArtificial) != 0;
803   }
804
805   bool isObjectPointer() const {
806     return (getHeaderFieldAs<unsigned>(3) & FlagObjectPointer) != 0;
807   }
808
809   /// \brief If this variable is inlined then return inline location.
810   MDNode *getInlinedAt() const;
811
812   bool Verify() const;
813
814   /// \brief Check if this is a "__block" variable (Apple Blocks).
815   bool isBlockByrefVariable(const DITypeIdentifierMap &Map) const {
816     return (getType().resolve(Map)).isBlockByrefStruct();
817   }
818
819   /// \brief Check if this is an inlined function argument.
820   bool isInlinedFnArgument(const Function *CurFn);
821
822   /// \brief Return the size reported by the variable's type.
823   unsigned getSizeInBits(const DITypeIdentifierMap &Map);
824
825   void printExtendedName(raw_ostream &OS) const;
826 };
827
828 /// \brief A complex location expression in postfix notation.
829 ///
830 /// This is (almost) a DWARF expression that modifies the location of a
831 /// variable or (or the location of a single piece of a variable).
832 ///
833 /// FIXME: Instead of DW_OP_plus taking an argument, this should use DW_OP_const
834 /// and have DW_OP_plus consume the topmost elements on the stack.
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 isBitPiece() const;
858   /// \brief Return the offset of this piece in bits.
859   uint64_t getBitPieceOffset() const;
860   /// \brief Return the size of this piece in bits.
861   uint64_t getBitPieceSize() const;
862
863   class iterator;
864   /// \brief A lightweight wrapper around an element of a DIExpression.
865   class Operand {
866     friend class iterator;
867     DIHeaderFieldIterator I;
868     Operand() {}
869     Operand(DIHeaderFieldIterator I) : I(I) {}
870   public:
871     /// \brief Operands such as DW_OP_piece have explicit (non-stack) arguments.
872     /// Argument 0 is the operand itself.
873     uint64_t getArg(unsigned N) const {
874       DIHeaderFieldIterator In = I;
875       std::advance(In, N);
876       return In.getNumber<uint64_t>();
877     }
878     operator uint64_t () const { return I.getNumber<uint64_t>(); }
879     /// \brief Returns underlying DIHeaderFieldIterator.
880     const DIHeaderFieldIterator &getBase() const { return I; }
881     /// \brief Returns the next operand.
882     Operand getNext() const;
883   };
884
885   /// \brief An iterator for DIExpression elements.
886   class iterator : public std::iterator<std::input_iterator_tag, StringRef,
887                                         unsigned, const Operand*, Operand> {
888     friend class Operand;
889     DIHeaderFieldIterator I;
890     Operand Tmp;
891     iterator(DIHeaderFieldIterator I) : I(I) {}
892   public:
893     iterator() {}
894     iterator(const DIExpression &Expr) : I(++Expr.header_begin()) {}
895     const Operand &operator*() { return Tmp = Operand(I); }
896     const Operand *operator->() { return &(Tmp = Operand(I)); }
897     iterator &operator++() {
898       increment();
899       return *this;
900     }
901     iterator operator++(int) {
902       iterator X(*this);
903       increment();
904       return X;
905     }
906     bool operator==(const iterator &X) const { return I == X.I; }
907     bool operator!=(const iterator &X) const { return !(*this == X); }
908
909   private:
910     void increment() {
911       switch (**this) {
912       case dwarf::DW_OP_bit_piece: std::advance(I, 3); break;
913       case dwarf::DW_OP_plus:      std::advance(I, 2); break;
914       case dwarf::DW_OP_deref:     std::advance(I, 1); break;
915       default:
916         llvm_unreachable("unsupported operand");
917       }
918     }
919   };
920
921   iterator begin() const;
922   iterator end() const;
923 };
924
925 /// \brief This object holds location information.
926 ///
927 /// This object is not associated with any DWARF tag.
928 class DILocation : public DIDescriptor {
929   MDLocation *getRaw() const { return dyn_cast_or_null<MDLocation>(get()); }
930
931 public:
932   explicit DILocation(const MDNode *N) : DIDescriptor(N) {}
933
934   unsigned getLineNumber() const { RETURN_FROM_RAW(N->getLine(), 0); }
935   unsigned getColumnNumber() const { RETURN_FROM_RAW(N->getColumn(), 0); }
936   DIScope getScope() const {
937     RETURN_DESCRIPTOR_FROM_RAW(DIScope, N->getScope());
938   }
939   DILocation getOrigLocation() const {
940     RETURN_DESCRIPTOR_FROM_RAW(DILocation, N->getInlinedAt());
941   }
942   StringRef getFilename() const { return getScope().getFilename(); }
943   StringRef getDirectory() const { return getScope().getDirectory(); }
944   bool Verify() const;
945   bool atSameLineAs(const DILocation &Other) const {
946     return (getLineNumber() == Other.getLineNumber() &&
947             getFilename() == Other.getFilename());
948   }
949   /// \brief Get the DWAF discriminator.
950   ///
951   /// DWARF discriminators are used to distinguish identical file locations for
952   /// instructions that are on different basic blocks. If two instructions are
953   /// inside the same lexical block and are in different basic blocks, we
954   /// create a new lexical block with identical location as the original but
955   /// with a different discriminator value
956   /// (lib/Transforms/Util/AddDiscriminators.cpp for details).
957   unsigned getDiscriminator() const {
958     // Since discriminators are associated with lexical blocks, make
959     // sure this location is a lexical block before retrieving its
960     // value.
961     return getScope().isLexicalBlockFile()
962                ? DILexicalBlockFile(
963                      cast<MDNode>(cast<MDLocation>(DbgNode)->getScope()))
964                      .getDiscriminator()
965                : 0;
966   }
967
968   /// \brief Generate a new discriminator value for this location.
969   unsigned computeNewDiscriminator(LLVMContext &Ctx);
970
971   /// \brief Return a copy of this location with a different scope.
972   DILocation copyWithNewScope(LLVMContext &Ctx, DILexicalBlockFile NewScope);
973 };
974
975 class DIObjCProperty : public DIDescriptor {
976   friend class DIDescriptor;
977   void printInternal(raw_ostream &OS) const;
978
979 public:
980   explicit DIObjCProperty(const MDNode *N) : DIDescriptor(N) {}
981
982   StringRef getObjCPropertyName() const { return getHeaderField(1); }
983   DIFile getFile() const { return getFieldAs<DIFile>(1); }
984   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(2); }
985
986   StringRef getObjCPropertyGetterName() const { return getHeaderField(3); }
987   StringRef getObjCPropertySetterName() const { return getHeaderField(4); }
988   unsigned getAttributes() const { return getHeaderFieldAs<unsigned>(5); }
989   bool isReadOnlyObjCProperty() const {
990     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readonly) != 0;
991   }
992   bool isReadWriteObjCProperty() const {
993     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_readwrite) != 0;
994   }
995   bool isAssignObjCProperty() const {
996     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_assign) != 0;
997   }
998   bool isRetainObjCProperty() const {
999     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_retain) != 0;
1000   }
1001   bool isCopyObjCProperty() const {
1002     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_copy) != 0;
1003   }
1004   bool isNonAtomicObjCProperty() const {
1005     return (getAttributes() & dwarf::DW_APPLE_PROPERTY_nonatomic) != 0;
1006   }
1007
1008   /// \brief Get the type.
1009   ///
1010   /// \note Objective-C doesn't have an ODR, so there is no benefit in storing
1011   /// the type as a DITypeRef here.
1012   DIType getType() const { return getFieldAs<DIType>(2); }
1013
1014   bool Verify() const;
1015 };
1016
1017 /// \brief An imported module (C++ using directive or similar).
1018 class DIImportedEntity : public DIDescriptor {
1019   friend class DIDescriptor;
1020   void printInternal(raw_ostream &OS) const;
1021
1022 public:
1023   explicit DIImportedEntity(const MDNode *N) : DIDescriptor(N) {}
1024   DIScope getContext() const { return getFieldAs<DIScope>(1); }
1025   DIDescriptorRef getEntity() const { return getFieldAs<DIDescriptorRef>(2); }
1026   unsigned getLineNumber() const { return getHeaderFieldAs<unsigned>(1); }
1027   StringRef getName() const { return getHeaderField(2); }
1028   bool Verify() const;
1029 };
1030
1031 #undef RETURN_FROM_RAW
1032 #undef RETURN_DESCRIPTOR_FROM_RAW
1033
1034 /// \brief Find subprogram that is enclosing this scope.
1035 DISubprogram getDISubprogram(const MDNode *Scope);
1036
1037 /// \brief Find debug info for a given function.
1038 /// \returns a valid DISubprogram, if found. Otherwise, it returns an empty
1039 /// DISubprogram.
1040 DISubprogram getDISubprogram(const Function *F);
1041
1042 /// \brief Find underlying composite type.
1043 DICompositeType getDICompositeType(DIType T);
1044
1045 /// \brief Create a new inlined variable based on current variable.
1046 ///
1047 /// @param DV            Current Variable.
1048 /// @param InlinedScope  Location at current variable is inlined.
1049 DIVariable createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
1050                                  LLVMContext &VMContext);
1051
1052 /// \brief Remove inlined scope from the variable.
1053 DIVariable cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext);
1054
1055 /// \brief Generate map by visiting all retained types.
1056 DITypeIdentifierMap generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes);
1057
1058 /// \brief Strip debug info in the module if it exists.
1059 ///
1060 /// To do this, we remove all calls to the debugger intrinsics and any named
1061 /// metadata for debugging. We also remove debug locations for instructions.
1062 /// Return true if module is modified.
1063 bool StripDebugInfo(Module &M);
1064
1065 /// \brief Return Debug Info Metadata Version by checking module flags.
1066 unsigned getDebugMetadataVersionFromModule(const Module &M);
1067
1068 /// \brief Utility to find all debug info in a module.
1069 ///
1070 /// DebugInfoFinder tries to list all debug info MDNodes used in a module. To
1071 /// list debug info MDNodes used by an instruction, DebugInfoFinder uses
1072 /// processDeclare, processValue and processLocation to handle DbgDeclareInst,
1073 /// DbgValueInst and DbgLoc attached to instructions. processModule will go
1074 /// through all DICompileUnits in llvm.dbg.cu and list debug info MDNodes
1075 /// used by the CUs.
1076 class DebugInfoFinder {
1077 public:
1078   DebugInfoFinder() : TypeMapInitialized(false) {}
1079
1080   /// \brief Process entire module and collect debug info anchors.
1081   void processModule(const Module &M);
1082
1083   /// \brief Process DbgDeclareInst.
1084   void processDeclare(const Module &M, const DbgDeclareInst *DDI);
1085   /// \brief Process DbgValueInst.
1086   void processValue(const Module &M, const DbgValueInst *DVI);
1087   /// \brief Process DILocation.
1088   void processLocation(const Module &M, DILocation Loc);
1089
1090   /// \brief Process DIExpression.
1091   void processExpression(DIExpression Expr);
1092
1093   /// \brief Clear all lists.
1094   void reset();
1095
1096 private:
1097   void InitializeTypeMap(const Module &M);
1098
1099   void processType(DIType DT);
1100   void processSubprogram(DISubprogram SP);
1101   void processScope(DIScope Scope);
1102   bool addCompileUnit(DICompileUnit CU);
1103   bool addGlobalVariable(DIGlobalVariable DIG);
1104   bool addSubprogram(DISubprogram SP);
1105   bool addType(DIType DT);
1106   bool addScope(DIScope Scope);
1107
1108 public:
1109   typedef SmallVectorImpl<DICompileUnit>::const_iterator compile_unit_iterator;
1110   typedef SmallVectorImpl<DISubprogram>::const_iterator subprogram_iterator;
1111   typedef SmallVectorImpl<DIGlobalVariable>::const_iterator
1112       global_variable_iterator;
1113   typedef SmallVectorImpl<DIType>::const_iterator type_iterator;
1114   typedef SmallVectorImpl<DIScope>::const_iterator scope_iterator;
1115
1116   iterator_range<compile_unit_iterator> compile_units() const {
1117     return iterator_range<compile_unit_iterator>(CUs.begin(), CUs.end());
1118   }
1119
1120   iterator_range<subprogram_iterator> subprograms() const {
1121     return iterator_range<subprogram_iterator>(SPs.begin(), SPs.end());
1122   }
1123
1124   iterator_range<global_variable_iterator> global_variables() const {
1125     return iterator_range<global_variable_iterator>(GVs.begin(), GVs.end());
1126   }
1127
1128   iterator_range<type_iterator> types() const {
1129     return iterator_range<type_iterator>(TYs.begin(), TYs.end());
1130   }
1131
1132   iterator_range<scope_iterator> scopes() const {
1133     return iterator_range<scope_iterator>(Scopes.begin(), Scopes.end());
1134   }
1135
1136   unsigned compile_unit_count() const { return CUs.size(); }
1137   unsigned global_variable_count() const { return GVs.size(); }
1138   unsigned subprogram_count() const { return SPs.size(); }
1139   unsigned type_count() const { return TYs.size(); }
1140   unsigned scope_count() const { return Scopes.size(); }
1141
1142 private:
1143   SmallVector<DICompileUnit, 8> CUs;
1144   SmallVector<DISubprogram, 8> SPs;
1145   SmallVector<DIGlobalVariable, 8> GVs;
1146   SmallVector<DIType, 8> TYs;
1147   SmallVector<DIScope, 8> Scopes;
1148   SmallPtrSet<MDNode *, 64> NodesSeen;
1149   DITypeIdentifierMap TypeIdentifierMap;
1150
1151   /// \brief Specify if TypeIdentifierMap is initialized.
1152   bool TypeMapInitialized;
1153 };
1154
1155 DenseMap<const Function *, DISubprogram> makeSubprogramMap(const Module &M);
1156
1157 } // end namespace llvm
1158
1159 #endif