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