IR: Add debug info flag string conversions
[oota-llvm.git] / lib / IR / DebugInfo.cpp
1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
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 implements the helper classes used to build and interpret debug
11 // information in LLVM IR form.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/IR/DebugInfo.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DIBuilder.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/ValueHandle.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Dwarf.h"
32 #include "llvm/Support/raw_ostream.h"
33 using namespace llvm;
34 using namespace llvm::dwarf;
35
36 //===----------------------------------------------------------------------===//
37 // DIDescriptor
38 //===----------------------------------------------------------------------===//
39
40 unsigned DIDescriptor::getFlag(StringRef Flag) {
41   return StringSwitch<unsigned>(Flag)
42 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
43 #include "llvm/IR/DebugInfoFlags.def"
44       .Default(0);
45 }
46
47 const char *DIDescriptor::getFlagString(unsigned Flag) {
48   switch (Flag) {
49   default:
50     return "";
51 #define HANDLE_DI_FLAG(ID, NAME)                                               \
52   case Flag##NAME:                                                             \
53     return "DIFlag" #NAME;
54 #include "llvm/IR/DebugInfoFlags.def"
55   }
56 }
57
58 bool DIDescriptor::Verify() const {
59   return DbgNode &&
60          (DIDerivedType(DbgNode).Verify() ||
61           DICompositeType(DbgNode).Verify() || DIBasicType(DbgNode).Verify() ||
62           DIVariable(DbgNode).Verify() || DISubprogram(DbgNode).Verify() ||
63           DIGlobalVariable(DbgNode).Verify() || DIFile(DbgNode).Verify() ||
64           DICompileUnit(DbgNode).Verify() || DINameSpace(DbgNode).Verify() ||
65           DILexicalBlock(DbgNode).Verify() ||
66           DILexicalBlockFile(DbgNode).Verify() ||
67           DISubrange(DbgNode).Verify() || DIEnumerator(DbgNode).Verify() ||
68           DIObjCProperty(DbgNode).Verify() ||
69           DITemplateTypeParameter(DbgNode).Verify() ||
70           DITemplateValueParameter(DbgNode).Verify() ||
71           DIImportedEntity(DbgNode).Verify() || DIExpression(DbgNode).Verify());
72 }
73
74 static Metadata *getField(const MDNode *DbgNode, unsigned Elt) {
75   if (!DbgNode || Elt >= DbgNode->getNumOperands())
76     return nullptr;
77   return DbgNode->getOperand(Elt);
78 }
79
80 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
81   return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
82 }
83
84 static StringRef getStringField(const MDNode *DbgNode, unsigned Elt) {
85   if (MDString *MDS = dyn_cast_or_null<MDString>(getField(DbgNode, Elt)))
86     return MDS->getString();
87   return StringRef();
88 }
89
90 StringRef DIDescriptor::getStringField(unsigned Elt) const {
91   return ::getStringField(DbgNode, Elt);
92 }
93
94 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
95   if (auto *C = getConstantField(Elt))
96     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
97       return CI->getZExtValue();
98
99   return 0;
100 }
101
102 int64_t DIDescriptor::getInt64Field(unsigned Elt) const {
103   if (auto *C = getConstantField(Elt))
104     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
105       return CI->getZExtValue();
106
107   return 0;
108 }
109
110 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
111   MDNode *Field = getNodeField(DbgNode, Elt);
112   return DIDescriptor(Field);
113 }
114
115 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
116   return dyn_cast_or_null<GlobalVariable>(getConstantField(Elt));
117 }
118
119 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
120   if (!DbgNode)
121     return nullptr;
122
123   if (Elt < DbgNode->getNumOperands())
124     if (auto *C =
125             dyn_cast_or_null<ConstantAsMetadata>(DbgNode->getOperand(Elt)))
126       return C->getValue();
127   return nullptr;
128 }
129
130 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
131   return dyn_cast_or_null<Function>(getConstantField(Elt));
132 }
133
134 void DIDescriptor::replaceFunctionField(unsigned Elt, Function *F) {
135   if (!DbgNode)
136     return;
137
138   if (Elt < DbgNode->getNumOperands()) {
139     MDNode *Node = const_cast<MDNode *>(DbgNode);
140     Node->replaceOperandWith(Elt, F ? ConstantAsMetadata::get(F) : nullptr);
141   }
142 }
143
144 static unsigned DIVariableInlinedAtIndex = 4;
145 MDNode *DIVariable::getInlinedAt() const {
146   return getNodeField(DbgNode, DIVariableInlinedAtIndex);
147 }
148
149 /// \brief Return the size reported by the variable's type.
150 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
151   DIType Ty = getType().resolve(Map);
152   // Follow derived types until we reach a type that
153   // reports back a size.
154   while (Ty.isDerivedType() && !Ty.getSizeInBits()) {
155     DIDerivedType DT(&*Ty);
156     Ty = DT.getTypeDerivedFrom().resolve(Map);
157   }
158   assert(Ty.getSizeInBits() && "type with size 0");
159   return Ty.getSizeInBits();
160 }
161
162 uint64_t DIExpression::getElement(unsigned Idx) const {
163   unsigned I = Idx + 1;
164   assert(I < getNumHeaderFields() &&
165          "non-existing complex address element requested");
166   return getHeaderFieldAs<int64_t>(I);
167 }
168
169 bool DIExpression::isBitPiece() const {
170   unsigned N = getNumElements();
171   return N >=3 && getElement(N-3) == dwarf::DW_OP_bit_piece;
172 }
173
174 uint64_t DIExpression::getBitPieceOffset() const {
175   assert(isBitPiece() && "not a piece");
176   return getElement(getNumElements()-2);
177 }
178
179 uint64_t DIExpression::getBitPieceSize() const {
180   assert(isBitPiece() && "not a piece");
181   return getElement(getNumElements()-1);
182 }
183
184 DIExpression::iterator DIExpression::begin() const {
185  return DIExpression::iterator(*this);
186 }
187
188 DIExpression::iterator DIExpression::end() const {
189  return DIExpression::iterator();
190 }
191
192 DIExpression::Operand DIExpression::Operand::getNext() const {
193   iterator it(I);
194   return *(++it);
195 }
196
197 //===----------------------------------------------------------------------===//
198 // Predicates
199 //===----------------------------------------------------------------------===//
200
201 bool DIDescriptor::isSubroutineType() const {
202   return DbgNode && getTag() == dwarf::DW_TAG_subroutine_type;
203 }
204
205 bool DIDescriptor::isBasicType() const {
206   if (!DbgNode)
207     return false;
208   switch (getTag()) {
209   case dwarf::DW_TAG_base_type:
210   case dwarf::DW_TAG_unspecified_type:
211     return true;
212   default:
213     return false;
214   }
215 }
216
217 bool DIDescriptor::isDerivedType() const {
218   if (!DbgNode)
219     return false;
220   switch (getTag()) {
221   case dwarf::DW_TAG_typedef:
222   case dwarf::DW_TAG_pointer_type:
223   case dwarf::DW_TAG_ptr_to_member_type:
224   case dwarf::DW_TAG_reference_type:
225   case dwarf::DW_TAG_rvalue_reference_type:
226   case dwarf::DW_TAG_const_type:
227   case dwarf::DW_TAG_volatile_type:
228   case dwarf::DW_TAG_restrict_type:
229   case dwarf::DW_TAG_member:
230   case dwarf::DW_TAG_inheritance:
231   case dwarf::DW_TAG_friend:
232     return true;
233   default:
234     // CompositeTypes are currently modelled as DerivedTypes.
235     return isCompositeType();
236   }
237 }
238
239 bool DIDescriptor::isCompositeType() const {
240   if (!DbgNode)
241     return false;
242   switch (getTag()) {
243   case dwarf::DW_TAG_array_type:
244   case dwarf::DW_TAG_structure_type:
245   case dwarf::DW_TAG_union_type:
246   case dwarf::DW_TAG_enumeration_type:
247   case dwarf::DW_TAG_subroutine_type:
248   case dwarf::DW_TAG_class_type:
249     return true;
250   default:
251     return false;
252   }
253 }
254
255 bool DIDescriptor::isVariable() const {
256   if (!DbgNode)
257     return false;
258   switch (getTag()) {
259   case dwarf::DW_TAG_auto_variable:
260   case dwarf::DW_TAG_arg_variable:
261     return true;
262   default:
263     return false;
264   }
265 }
266
267 bool DIDescriptor::isType() const {
268   return isBasicType() || isCompositeType() || isDerivedType();
269 }
270
271 bool DIDescriptor::isSubprogram() const {
272   return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
273 }
274
275 bool DIDescriptor::isGlobalVariable() const {
276   return DbgNode && getTag() == dwarf::DW_TAG_variable;
277 }
278
279 bool DIDescriptor::isScope() const {
280   if (!DbgNode)
281     return false;
282   switch (getTag()) {
283   case dwarf::DW_TAG_compile_unit:
284   case dwarf::DW_TAG_lexical_block:
285   case dwarf::DW_TAG_subprogram:
286   case dwarf::DW_TAG_namespace:
287   case dwarf::DW_TAG_file_type:
288     return true;
289   default:
290     break;
291   }
292   return isType();
293 }
294
295 bool DIDescriptor::isTemplateTypeParameter() const {
296   return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter;
297 }
298
299 bool DIDescriptor::isTemplateValueParameter() const {
300   return DbgNode && (getTag() == dwarf::DW_TAG_template_value_parameter ||
301                      getTag() == dwarf::DW_TAG_GNU_template_template_param ||
302                      getTag() == dwarf::DW_TAG_GNU_template_parameter_pack);
303 }
304
305 bool DIDescriptor::isCompileUnit() const {
306   return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
307 }
308
309 bool DIDescriptor::isFile() const {
310   return DbgNode && getTag() == dwarf::DW_TAG_file_type;
311 }
312
313 bool DIDescriptor::isNameSpace() const {
314   return DbgNode && getTag() == dwarf::DW_TAG_namespace;
315 }
316
317 bool DIDescriptor::isLexicalBlockFile() const {
318   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
319          DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 2;
320 }
321
322 bool DIDescriptor::isLexicalBlock() const {
323   // FIXME: There are always exactly 4 header fields in DILexicalBlock, but
324   // something relies on this returning true for DILexicalBlockFile.
325   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
326          DbgNode->getNumOperands() == 3 &&
327          (getNumHeaderFields() == 2 || getNumHeaderFields() == 4);
328 }
329
330 bool DIDescriptor::isSubrange() const {
331   return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
332 }
333
334 bool DIDescriptor::isEnumerator() const {
335   return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
336 }
337
338 bool DIDescriptor::isObjCProperty() const {
339   return DbgNode && getTag() == dwarf::DW_TAG_APPLE_property;
340 }
341
342 bool DIDescriptor::isImportedEntity() const {
343   return DbgNode && (getTag() == dwarf::DW_TAG_imported_module ||
344                      getTag() == dwarf::DW_TAG_imported_declaration);
345 }
346
347 bool DIDescriptor::isExpression() const {
348   return DbgNode && (getTag() == dwarf::DW_TAG_expression);
349 }
350
351 //===----------------------------------------------------------------------===//
352 // Simple Descriptor Constructors and other Methods
353 //===----------------------------------------------------------------------===//
354
355 void DIDescriptor::replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D) {
356
357   assert(DbgNode && "Trying to replace an unverified type!");
358
359   // Since we use a TrackingVH for the node, its easy for clients to manufacture
360   // legitimate situations where they want to replaceAllUsesWith() on something
361   // which, due to uniquing, has merged with the source. We shield clients from
362   // this detail by allowing a value to be replaced with replaceAllUsesWith()
363   // itself.
364   const MDNode *DN = D;
365   if (DbgNode == DN) {
366     SmallVector<Metadata *, 10> Ops(DbgNode->op_begin(), DbgNode->op_end());
367     DN = MDNode::get(VMContext, Ops);
368   }
369
370   assert(DbgNode->isTemporary() && "Expected temporary node");
371   auto *Node = const_cast<MDNode *>(DbgNode);
372   Node->replaceAllUsesWith(const_cast<MDNode *>(DN));
373   MDNode::deleteTemporary(Node);
374   DbgNode = DN;
375 }
376
377 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
378   assert(DbgNode && "Trying to replace an unverified type!");
379   assert(DbgNode != D && "This replacement should always happen");
380   assert(DbgNode->isTemporary() && "Expected temporary node");
381   auto *Node = const_cast<MDNode *>(DbgNode);
382   Node->replaceAllUsesWith(D);
383   MDNode::deleteTemporary(Node);
384 }
385
386 bool DICompileUnit::Verify() const {
387   if (!isCompileUnit())
388     return false;
389
390   // Don't bother verifying the compilation directory or producer string
391   // as those could be empty.
392   if (getFilename().empty())
393     return false;
394
395   return DbgNode->getNumOperands() == 7 && getNumHeaderFields() == 8;
396 }
397
398 bool DIObjCProperty::Verify() const {
399   if (!isObjCProperty())
400     return false;
401
402   // Don't worry about the rest of the strings for now.
403   return DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 6;
404 }
405
406 /// \brief Check if a field at position Elt of a MDNode is a MDNode.
407 static bool fieldIsMDNode(const MDNode *DbgNode, unsigned Elt) {
408   Metadata *Fld = getField(DbgNode, Elt);
409   return !Fld || isa<MDNode>(Fld);
410 }
411
412 /// \brief Check if a field at position Elt of a MDNode is a MDString.
413 static bool fieldIsMDString(const MDNode *DbgNode, unsigned Elt) {
414   Metadata *Fld = getField(DbgNode, Elt);
415   return !Fld || isa<MDString>(Fld);
416 }
417
418 /// \brief Check if a value can be a reference to a type.
419 static bool isTypeRef(const Metadata *MD) {
420   if (!MD)
421     return true;
422   if (auto *S = dyn_cast<MDString>(MD))
423     return !S->getString().empty();
424   if (auto *N = dyn_cast<MDNode>(MD))
425     return DIType(N).isType();
426   return false;
427 }
428
429 /// \brief Check if referenced field might be a type.
430 static bool fieldIsTypeRef(const MDNode *DbgNode, unsigned Elt) {
431   return isTypeRef(dyn_cast_or_null<Metadata>(getField(DbgNode, Elt)));
432 }
433
434 /// \brief Check if a value can be a ScopeRef.
435 static bool isScopeRef(const Metadata *MD) {
436   if (!MD)
437     return true;
438   if (auto *S = dyn_cast<MDString>(MD))
439     return !S->getString().empty();
440   if (auto *N = dyn_cast<MDNode>(MD))
441     return DIScope(N).isScope();
442   return false;
443 }
444
445 /// \brief Check if a field at position Elt of a MDNode can be a ScopeRef.
446 static bool fieldIsScopeRef(const MDNode *DbgNode, unsigned Elt) {
447   return isScopeRef(dyn_cast_or_null<Metadata>(getField(DbgNode, Elt)));
448 }
449
450 #ifndef NDEBUG
451 /// \brief Check if a value can be a DescriptorRef.
452 static bool isDescriptorRef(const Metadata *MD) {
453   if (!MD)
454     return true;
455   if (auto *S = dyn_cast<MDString>(MD))
456     return !S->getString().empty();
457   return isa<MDNode>(MD);
458 }
459 #endif
460
461 bool DIType::Verify() const {
462   if (!isType())
463     return false;
464   // Make sure Context @ field 2 is MDNode.
465   if (!fieldIsScopeRef(DbgNode, 2))
466     return false;
467
468   // FIXME: Sink this into the various subclass verifies.
469   uint16_t Tag = getTag();
470   if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
471       Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
472       Tag != dwarf::DW_TAG_ptr_to_member_type &&
473       Tag != dwarf::DW_TAG_reference_type &&
474       Tag != dwarf::DW_TAG_rvalue_reference_type &&
475       Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
476       Tag != dwarf::DW_TAG_enumeration_type &&
477       Tag != dwarf::DW_TAG_subroutine_type &&
478       Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
479       getFilename().empty())
480     return false;
481
482   // DIType is abstract, it should be a BasicType, a DerivedType or
483   // a CompositeType.
484   if (isBasicType())
485     return DIBasicType(DbgNode).Verify();
486   else if (isCompositeType())
487     return DICompositeType(DbgNode).Verify();
488   else if (isDerivedType())
489     return DIDerivedType(DbgNode).Verify();
490   else
491     return false;
492 }
493
494 bool DIBasicType::Verify() const {
495   return isBasicType() && DbgNode->getNumOperands() == 3 &&
496          getNumHeaderFields() == 8;
497 }
498
499 bool DIDerivedType::Verify() const {
500   // Make sure DerivedFrom @ field 3 is TypeRef.
501   if (!fieldIsTypeRef(DbgNode, 3))
502     return false;
503   if (getTag() == dwarf::DW_TAG_ptr_to_member_type)
504     // Make sure ClassType @ field 4 is a TypeRef.
505     if (!fieldIsTypeRef(DbgNode, 4))
506       return false;
507
508   return isDerivedType() && DbgNode->getNumOperands() >= 4 &&
509          DbgNode->getNumOperands() <= 8 && getNumHeaderFields() >= 7 &&
510          getNumHeaderFields() <= 8;
511 }
512
513 bool DICompositeType::Verify() const {
514   if (!isCompositeType())
515     return false;
516
517   // Make sure DerivedFrom @ field 3 and ContainingType @ field 5 are TypeRef.
518   if (!fieldIsTypeRef(DbgNode, 3))
519     return false;
520   if (!fieldIsTypeRef(DbgNode, 5))
521     return false;
522
523   // Make sure the type identifier at field 7 is MDString, it can be null.
524   if (!fieldIsMDString(DbgNode, 7))
525     return false;
526
527   // A subroutine type can't be both & and &&.
528   if (isLValueReference() && isRValueReference())
529     return false;
530
531   return DbgNode->getNumOperands() == 8 && getNumHeaderFields() == 8;
532 }
533
534 bool DISubprogram::Verify() const {
535   if (!isSubprogram())
536     return false;
537
538   // Make sure context @ field 2 is a ScopeRef and type @ field 3 is a MDNode.
539   if (!fieldIsScopeRef(DbgNode, 2))
540     return false;
541   if (!fieldIsMDNode(DbgNode, 3))
542     return false;
543   // Containing type @ field 4.
544   if (!fieldIsTypeRef(DbgNode, 4))
545     return false;
546
547   // A subprogram can't be both & and &&.
548   if (isLValueReference() && isRValueReference())
549     return false;
550
551   // If a DISubprogram has an llvm::Function*, then scope chains from all
552   // instructions within the function should lead to this DISubprogram.
553   if (auto *F = getFunction()) {
554     for (auto &BB : *F) {
555       for (auto &I : BB) {
556         DebugLoc DL = I.getDebugLoc();
557         if (DL.isUnknown())
558           continue;
559
560         MDNode *Scope = nullptr;
561         MDNode *IA = nullptr;
562         // walk the inlined-at scopes
563         while ((IA = DL.getInlinedAt()))
564           DL = DebugLoc::getFromDILocation(IA);
565         DL.getScopeAndInlinedAt(Scope, IA);
566         if (!Scope)
567           return false;
568         assert(!IA);
569         while (!DIDescriptor(Scope).isSubprogram()) {
570           DILexicalBlockFile D(Scope);
571           Scope = D.isLexicalBlockFile()
572                       ? D.getScope()
573                       : DebugLoc::getFromDILexicalBlock(Scope).getScope();
574           if (!Scope)
575             return false;
576         }
577         if (!DISubprogram(Scope).describes(F))
578           return false;
579       }
580     }
581   }
582   return DbgNode->getNumOperands() == 9 && getNumHeaderFields() == 12;
583 }
584
585 bool DIGlobalVariable::Verify() const {
586   if (!isGlobalVariable())
587     return false;
588
589   if (getDisplayName().empty())
590     return false;
591   // Make sure context @ field 1 is an MDNode.
592   if (!fieldIsMDNode(DbgNode, 1))
593     return false;
594   // Make sure that type @ field 3 is a DITypeRef.
595   if (!fieldIsTypeRef(DbgNode, 3))
596     return false;
597   // Make sure StaticDataMemberDeclaration @ field 5 is MDNode.
598   if (!fieldIsMDNode(DbgNode, 5))
599     return false;
600
601   return DbgNode->getNumOperands() == 6 && getNumHeaderFields() == 7;
602 }
603
604 bool DIVariable::Verify() const {
605   if (!isVariable())
606     return false;
607
608   // Make sure context @ field 1 is an MDNode.
609   if (!fieldIsMDNode(DbgNode, 1))
610     return false;
611   // Make sure that type @ field 3 is a DITypeRef.
612   if (!fieldIsTypeRef(DbgNode, 3))
613     return false;
614
615   // Check the number of header fields, which is common between complex and
616   // simple variables.
617   if (getNumHeaderFields() != 4)
618     return false;
619
620   // Variable without an inline location.
621   if (DbgNode->getNumOperands() == 4)
622     return true;
623
624   // Variable with an inline location.
625   return getInlinedAt() != nullptr && DbgNode->getNumOperands() == 5;
626 }
627
628 bool DIExpression::Verify() const {
629   // Empty DIExpressions may be represented as a nullptr.
630   if (!DbgNode)
631     return true;
632
633   if (!(isExpression() && DbgNode->getNumOperands() == 1))
634     return false;
635
636   for (auto Op : *this)
637     switch (Op) {
638     case DW_OP_bit_piece:
639       // Must be the last element of the expression.
640       return std::distance(Op.getBase(), DIHeaderFieldIterator()) == 3;
641     case DW_OP_plus:
642       if (std::distance(Op.getBase(), DIHeaderFieldIterator()) < 2)
643         return false;
644       break;
645     case DW_OP_deref:
646       break;
647     default:
648       // Other operators are not yet supported by the backend.
649       return false;
650     }
651   return true;
652 }
653
654 bool DILocation::Verify() const {
655   return DbgNode && isa<MDLocation>(DbgNode);
656 }
657
658 bool DINameSpace::Verify() const {
659   if (!isNameSpace())
660     return false;
661   return DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 3;
662 }
663
664 MDNode *DIFile::getFileNode() const { return getNodeField(DbgNode, 1); }
665
666 bool DIFile::Verify() const {
667   return isFile() && DbgNode->getNumOperands() == 2;
668 }
669
670 bool DIEnumerator::Verify() const {
671   return isEnumerator() && DbgNode->getNumOperands() == 1 &&
672          getNumHeaderFields() == 3;
673 }
674
675 bool DISubrange::Verify() const {
676   return isSubrange() && DbgNode->getNumOperands() == 1 &&
677          getNumHeaderFields() == 3;
678 }
679
680 bool DILexicalBlock::Verify() const {
681   return isLexicalBlock() && DbgNode->getNumOperands() == 3 &&
682          getNumHeaderFields() == 4;
683 }
684
685 bool DILexicalBlockFile::Verify() const {
686   return isLexicalBlockFile() && DbgNode->getNumOperands() == 3 &&
687          getNumHeaderFields() == 2;
688 }
689
690 bool DITemplateTypeParameter::Verify() const {
691   return isTemplateTypeParameter() && DbgNode->getNumOperands() == 4 &&
692          getNumHeaderFields() == 4;
693 }
694
695 bool DITemplateValueParameter::Verify() const {
696   return isTemplateValueParameter() && DbgNode->getNumOperands() == 5 &&
697          getNumHeaderFields() == 4;
698 }
699
700 bool DIImportedEntity::Verify() const {
701   return isImportedEntity() && DbgNode->getNumOperands() == 3 &&
702          getNumHeaderFields() == 3;
703 }
704
705 MDNode *DIDerivedType::getObjCProperty() const {
706   return getNodeField(DbgNode, 4);
707 }
708
709 MDString *DICompositeType::getIdentifier() const {
710   return cast_or_null<MDString>(getField(DbgNode, 7));
711 }
712
713 #ifndef NDEBUG
714 static void VerifySubsetOf(const MDNode *LHS, const MDNode *RHS) {
715   for (unsigned i = 0; i != LHS->getNumOperands(); ++i) {
716     // Skip the 'empty' list (that's a single i32 0, rather than truly empty).
717     if (i == 0 && mdconst::hasa<ConstantInt>(LHS->getOperand(i)))
718       continue;
719     const MDNode *E = cast<MDNode>(LHS->getOperand(i));
720     bool found = false;
721     for (unsigned j = 0; !found && j != RHS->getNumOperands(); ++j)
722       found = (E == cast<MDNode>(RHS->getOperand(j)));
723     assert(found && "Losing a member during member list replacement");
724   }
725 }
726 #endif
727
728 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
729   TrackingMDNodeRef N(*this);
730   if (Elements) {
731 #ifndef NDEBUG
732     // Check that the new list of members contains all the old members as well.
733     if (const MDNode *El = cast_or_null<MDNode>(N->getOperand(4)))
734       VerifySubsetOf(El, Elements);
735 #endif
736     N->replaceOperandWith(4, Elements);
737   }
738   if (TParams)
739     N->replaceOperandWith(6, TParams);
740   DbgNode = N;
741 }
742
743 DIScopeRef DIScope::getRef() const {
744   if (!isCompositeType())
745     return DIScopeRef(*this);
746   DICompositeType DTy(DbgNode);
747   if (!DTy.getIdentifier())
748     return DIScopeRef(*this);
749   return DIScopeRef(DTy.getIdentifier());
750 }
751
752 void DICompositeType::setContainingType(DICompositeType ContainingType) {
753   TrackingMDNodeRef N(*this);
754   N->replaceOperandWith(5, ContainingType.getRef());
755   DbgNode = N;
756 }
757
758 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
759   assert(CurFn && "Invalid function");
760   if (!getContext().isSubprogram())
761     return false;
762   // This variable is not inlined function argument if its scope
763   // does not describe current function.
764   return !DISubprogram(getContext()).describes(CurFn);
765 }
766
767 bool DISubprogram::describes(const Function *F) {
768   assert(F && "Invalid function");
769   if (F == getFunction())
770     return true;
771   StringRef Name = getLinkageName();
772   if (Name.empty())
773     Name = getName();
774   if (F->getName() == Name)
775     return true;
776   return false;
777 }
778
779 MDNode *DISubprogram::getVariablesNodes() const {
780   return getNodeField(DbgNode, 8);
781 }
782
783 DIArray DISubprogram::getVariables() const {
784   return DIArray(getNodeField(DbgNode, 8));
785 }
786
787 Metadata *DITemplateValueParameter::getValue() const {
788   return DbgNode->getOperand(3);
789 }
790
791 DIScopeRef DIScope::getContext() const {
792
793   if (isType())
794     return DIType(DbgNode).getContext();
795
796   if (isSubprogram())
797     return DIScopeRef(DISubprogram(DbgNode).getContext());
798
799   if (isLexicalBlock())
800     return DIScopeRef(DILexicalBlock(DbgNode).getContext());
801
802   if (isLexicalBlockFile())
803     return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
804
805   if (isNameSpace())
806     return DIScopeRef(DINameSpace(DbgNode).getContext());
807
808   assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
809   return DIScopeRef(nullptr);
810 }
811
812 StringRef DIScope::getName() const {
813   if (isType())
814     return DIType(DbgNode).getName();
815   if (isSubprogram())
816     return DISubprogram(DbgNode).getName();
817   if (isNameSpace())
818     return DINameSpace(DbgNode).getName();
819   assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
820           isCompileUnit()) &&
821          "Unhandled type of scope.");
822   return StringRef();
823 }
824
825 StringRef DIScope::getFilename() const {
826   if (!DbgNode)
827     return StringRef();
828   return ::getStringField(getNodeField(DbgNode, 1), 0);
829 }
830
831 StringRef DIScope::getDirectory() const {
832   if (!DbgNode)
833     return StringRef();
834   return ::getStringField(getNodeField(DbgNode, 1), 1);
835 }
836
837 DIArray DICompileUnit::getEnumTypes() const {
838   if (!DbgNode || DbgNode->getNumOperands() < 7)
839     return DIArray();
840
841   return DIArray(getNodeField(DbgNode, 2));
842 }
843
844 DIArray DICompileUnit::getRetainedTypes() const {
845   if (!DbgNode || DbgNode->getNumOperands() < 7)
846     return DIArray();
847
848   return DIArray(getNodeField(DbgNode, 3));
849 }
850
851 DIArray DICompileUnit::getSubprograms() const {
852   if (!DbgNode || DbgNode->getNumOperands() < 7)
853     return DIArray();
854
855   return DIArray(getNodeField(DbgNode, 4));
856 }
857
858 DIArray DICompileUnit::getGlobalVariables() const {
859   if (!DbgNode || DbgNode->getNumOperands() < 7)
860     return DIArray();
861
862   return DIArray(getNodeField(DbgNode, 5));
863 }
864
865 DIArray DICompileUnit::getImportedEntities() const {
866   if (!DbgNode || DbgNode->getNumOperands() < 7)
867     return DIArray();
868
869   return DIArray(getNodeField(DbgNode, 6));
870 }
871
872 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
873   assert(Verify() && "Expected compile unit");
874   if (Subprograms == getSubprograms())
875     return;
876
877   const_cast<MDNode *>(DbgNode)->replaceOperandWith(4, Subprograms);
878 }
879
880 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
881   assert(Verify() && "Expected compile unit");
882   if (GlobalVariables == getGlobalVariables())
883     return;
884
885   const_cast<MDNode *>(DbgNode)->replaceOperandWith(5, GlobalVariables);
886 }
887
888 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
889                                         DILexicalBlockFile NewScope) {
890   assert(Verify());
891   assert(NewScope && "Expected valid scope");
892
893   const auto *Old = cast<MDLocation>(DbgNode);
894   return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
895                                     NewScope, Old->getInlinedAt()));
896 }
897
898 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
899   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
900   return ++Ctx.pImpl->DiscriminatorTable[Key];
901 }
902
903 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
904                                        LLVMContext &VMContext) {
905   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
906   if (!InlinedScope)
907     return cleanseInlinedVariable(DV, VMContext);
908
909   // Insert inlined scope.
910   SmallVector<Metadata *, 8> Elts(DV->op_begin(),
911                                   DV->op_begin() + DIVariableInlinedAtIndex);
912   Elts.push_back(InlinedScope);
913
914   DIVariable Inlined(MDNode::get(VMContext, Elts));
915   assert(Inlined.Verify() && "Expected to create a DIVariable");
916   return Inlined;
917 }
918
919 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
920   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
921   if (!DIVariable(DV).getInlinedAt())
922     return DIVariable(DV);
923
924   // Remove inlined scope.
925   SmallVector<Metadata *, 8> Elts(DV->op_begin(),
926                                   DV->op_begin() + DIVariableInlinedAtIndex);
927
928   DIVariable Cleansed(MDNode::get(VMContext, Elts));
929   assert(Cleansed.Verify() && "Expected to create a DIVariable");
930   return Cleansed;
931 }
932
933 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
934   DIDescriptor D(Scope);
935   if (D.isSubprogram())
936     return DISubprogram(Scope);
937
938   if (D.isLexicalBlockFile())
939     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
940
941   if (D.isLexicalBlock())
942     return getDISubprogram(DILexicalBlock(Scope).getContext());
943
944   return DISubprogram();
945 }
946
947 DISubprogram llvm::getDISubprogram(const Function *F) {
948   // We look for the first instr that has a debug annotation leading back to F.
949   for (auto &BB : *F) {
950     auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
951       return !Inst.getDebugLoc().isUnknown();
952     });
953     if (Inst == BB.end())
954       continue;
955     DebugLoc DLoc = Inst->getDebugLoc();
956     const MDNode *Scope = DLoc.getScopeNode();
957     DISubprogram Subprogram = getDISubprogram(Scope);
958     return Subprogram.describes(F) ? Subprogram : DISubprogram();
959   }
960
961   return DISubprogram();
962 }
963
964 DICompositeType llvm::getDICompositeType(DIType T) {
965   if (T.isCompositeType())
966     return DICompositeType(T);
967
968   if (T.isDerivedType()) {
969     // This function is currently used by dragonegg and dragonegg does
970     // not generate identifier for types, so using an empty map to resolve
971     // DerivedFrom should be fine.
972     DITypeIdentifierMap EmptyMap;
973     return getDICompositeType(
974         DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
975   }
976
977   return DICompositeType();
978 }
979
980 DITypeIdentifierMap
981 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
982   DITypeIdentifierMap Map;
983   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
984     DICompileUnit CU(CU_Nodes->getOperand(CUi));
985     DIArray Retain = CU.getRetainedTypes();
986     for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
987       if (!Retain.getElement(Ti).isCompositeType())
988         continue;
989       DICompositeType Ty(Retain.getElement(Ti));
990       if (MDString *TypeId = Ty.getIdentifier()) {
991         // Definition has priority over declaration.
992         // Try to insert (TypeId, Ty) to Map.
993         std::pair<DITypeIdentifierMap::iterator, bool> P =
994             Map.insert(std::make_pair(TypeId, Ty));
995         // If TypeId already exists in Map and this is a definition, replace
996         // whatever we had (declaration or definition) with the definition.
997         if (!P.second && !Ty.isForwardDecl())
998           P.first->second = Ty;
999       }
1000     }
1001   }
1002   return Map;
1003 }
1004
1005 //===----------------------------------------------------------------------===//
1006 // DebugInfoFinder implementations.
1007 //===----------------------------------------------------------------------===//
1008
1009 void DebugInfoFinder::reset() {
1010   CUs.clear();
1011   SPs.clear();
1012   GVs.clear();
1013   TYs.clear();
1014   Scopes.clear();
1015   NodesSeen.clear();
1016   TypeIdentifierMap.clear();
1017   TypeMapInitialized = false;
1018 }
1019
1020 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
1021   if (!TypeMapInitialized)
1022     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
1023       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
1024       TypeMapInitialized = true;
1025     }
1026 }
1027
1028 void DebugInfoFinder::processModule(const Module &M) {
1029   InitializeTypeMap(M);
1030   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
1031     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
1032       DICompileUnit CU(CU_Nodes->getOperand(i));
1033       addCompileUnit(CU);
1034       DIArray GVs = CU.getGlobalVariables();
1035       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
1036         DIGlobalVariable DIG(GVs.getElement(i));
1037         if (addGlobalVariable(DIG)) {
1038           processScope(DIG.getContext());
1039           processType(DIG.getType().resolve(TypeIdentifierMap));
1040         }
1041       }
1042       DIArray SPs = CU.getSubprograms();
1043       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
1044         processSubprogram(DISubprogram(SPs.getElement(i)));
1045       DIArray EnumTypes = CU.getEnumTypes();
1046       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
1047         processType(DIType(EnumTypes.getElement(i)));
1048       DIArray RetainedTypes = CU.getRetainedTypes();
1049       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
1050         processType(DIType(RetainedTypes.getElement(i)));
1051       DIArray Imports = CU.getImportedEntities();
1052       for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
1053         DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
1054         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
1055         if (Entity.isType())
1056           processType(DIType(Entity));
1057         else if (Entity.isSubprogram())
1058           processSubprogram(DISubprogram(Entity));
1059         else if (Entity.isNameSpace())
1060           processScope(DINameSpace(Entity).getContext());
1061       }
1062     }
1063   }
1064 }
1065
1066 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
1067   if (!Loc)
1068     return;
1069   InitializeTypeMap(M);
1070   processScope(Loc.getScope());
1071   processLocation(M, Loc.getOrigLocation());
1072 }
1073
1074 void DebugInfoFinder::processType(DIType DT) {
1075   if (!addType(DT))
1076     return;
1077   processScope(DT.getContext().resolve(TypeIdentifierMap));
1078   if (DT.isCompositeType()) {
1079     DICompositeType DCT(DT);
1080     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1081     if (DT.isSubroutineType()) {
1082       DITypeArray DTA = DISubroutineType(DT).getTypeArray();
1083       for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
1084         processType(DTA.getElement(i).resolve(TypeIdentifierMap));
1085       return;
1086     }
1087     DIArray DA = DCT.getElements();
1088     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1089       DIDescriptor D = DA.getElement(i);
1090       if (D.isType())
1091         processType(DIType(D));
1092       else if (D.isSubprogram())
1093         processSubprogram(DISubprogram(D));
1094     }
1095   } else if (DT.isDerivedType()) {
1096     DIDerivedType DDT(DT);
1097     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1098   }
1099 }
1100
1101 void DebugInfoFinder::processScope(DIScope Scope) {
1102   if (Scope.isType()) {
1103     DIType Ty(Scope);
1104     processType(Ty);
1105     return;
1106   }
1107   if (Scope.isCompileUnit()) {
1108     addCompileUnit(DICompileUnit(Scope));
1109     return;
1110   }
1111   if (Scope.isSubprogram()) {
1112     processSubprogram(DISubprogram(Scope));
1113     return;
1114   }
1115   if (!addScope(Scope))
1116     return;
1117   if (Scope.isLexicalBlock()) {
1118     DILexicalBlock LB(Scope);
1119     processScope(LB.getContext());
1120   } else if (Scope.isLexicalBlockFile()) {
1121     DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
1122     processScope(LBF.getScope());
1123   } else if (Scope.isNameSpace()) {
1124     DINameSpace NS(Scope);
1125     processScope(NS.getContext());
1126   }
1127 }
1128
1129 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1130   if (!addSubprogram(SP))
1131     return;
1132   processScope(SP.getContext().resolve(TypeIdentifierMap));
1133   processType(SP.getType());
1134   DIArray TParams = SP.getTemplateParams();
1135   for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
1136     DIDescriptor Element = TParams.getElement(I);
1137     if (Element.isTemplateTypeParameter()) {
1138       DITemplateTypeParameter TType(Element);
1139       processType(TType.getType().resolve(TypeIdentifierMap));
1140     } else if (Element.isTemplateValueParameter()) {
1141       DITemplateValueParameter TVal(Element);
1142       processType(TVal.getType().resolve(TypeIdentifierMap));
1143     }
1144   }
1145 }
1146
1147 void DebugInfoFinder::processDeclare(const Module &M,
1148                                      const DbgDeclareInst *DDI) {
1149   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1150   if (!N)
1151     return;
1152   InitializeTypeMap(M);
1153
1154   DIDescriptor DV(N);
1155   if (!DV.isVariable())
1156     return;
1157
1158   if (!NodesSeen.insert(DV).second)
1159     return;
1160   processScope(DIVariable(N).getContext());
1161   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1162 }
1163
1164 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
1165   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
1166   if (!N)
1167     return;
1168   InitializeTypeMap(M);
1169
1170   DIDescriptor DV(N);
1171   if (!DV.isVariable())
1172     return;
1173
1174   if (!NodesSeen.insert(DV).second)
1175     return;
1176   processScope(DIVariable(N).getContext());
1177   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1178 }
1179
1180 bool DebugInfoFinder::addType(DIType DT) {
1181   if (!DT)
1182     return false;
1183
1184   if (!NodesSeen.insert(DT).second)
1185     return false;
1186
1187   TYs.push_back(DT);
1188   return true;
1189 }
1190
1191 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1192   if (!CU)
1193     return false;
1194   if (!NodesSeen.insert(CU).second)
1195     return false;
1196
1197   CUs.push_back(CU);
1198   return true;
1199 }
1200
1201 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1202   if (!DIG)
1203     return false;
1204
1205   if (!NodesSeen.insert(DIG).second)
1206     return false;
1207
1208   GVs.push_back(DIG);
1209   return true;
1210 }
1211
1212 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1213   if (!SP)
1214     return false;
1215
1216   if (!NodesSeen.insert(SP).second)
1217     return false;
1218
1219   SPs.push_back(SP);
1220   return true;
1221 }
1222
1223 bool DebugInfoFinder::addScope(DIScope Scope) {
1224   if (!Scope)
1225     return false;
1226   // FIXME: Ocaml binding generates a scope with no content, we treat it
1227   // as null for now.
1228   if (Scope->getNumOperands() == 0)
1229     return false;
1230   if (!NodesSeen.insert(Scope).second)
1231     return false;
1232   Scopes.push_back(Scope);
1233   return true;
1234 }
1235
1236 //===----------------------------------------------------------------------===//
1237 // DIDescriptor: dump routines for all descriptors.
1238 //===----------------------------------------------------------------------===//
1239
1240 void DIDescriptor::dump() const {
1241   print(dbgs());
1242   dbgs() << '\n';
1243 }
1244
1245 void DIDescriptor::print(raw_ostream &OS) const {
1246   if (!DbgNode)
1247     return;
1248
1249   if (const char *Tag = dwarf::TagString(getTag()))
1250     OS << "[ " << Tag << " ]";
1251
1252   if (this->isSubrange()) {
1253     DISubrange(DbgNode).printInternal(OS);
1254   } else if (this->isCompileUnit()) {
1255     DICompileUnit(DbgNode).printInternal(OS);
1256   } else if (this->isFile()) {
1257     DIFile(DbgNode).printInternal(OS);
1258   } else if (this->isEnumerator()) {
1259     DIEnumerator(DbgNode).printInternal(OS);
1260   } else if (this->isBasicType()) {
1261     DIType(DbgNode).printInternal(OS);
1262   } else if (this->isDerivedType()) {
1263     DIDerivedType(DbgNode).printInternal(OS);
1264   } else if (this->isCompositeType()) {
1265     DICompositeType(DbgNode).printInternal(OS);
1266   } else if (this->isSubprogram()) {
1267     DISubprogram(DbgNode).printInternal(OS);
1268   } else if (this->isGlobalVariable()) {
1269     DIGlobalVariable(DbgNode).printInternal(OS);
1270   } else if (this->isVariable()) {
1271     DIVariable(DbgNode).printInternal(OS);
1272   } else if (this->isObjCProperty()) {
1273     DIObjCProperty(DbgNode).printInternal(OS);
1274   } else if (this->isNameSpace()) {
1275     DINameSpace(DbgNode).printInternal(OS);
1276   } else if (this->isScope()) {
1277     DIScope(DbgNode).printInternal(OS);
1278   } else if (this->isExpression()) {
1279     DIExpression(DbgNode).printInternal(OS);
1280   }
1281 }
1282
1283 void DISubrange::printInternal(raw_ostream &OS) const {
1284   int64_t Count = getCount();
1285   if (Count != -1)
1286     OS << " [" << getLo() << ", " << Count - 1 << ']';
1287   else
1288     OS << " [unbounded]";
1289 }
1290
1291 void DIScope::printInternal(raw_ostream &OS) const {
1292   OS << " [" << getDirectory() << "/" << getFilename() << ']';
1293 }
1294
1295 void DICompileUnit::printInternal(raw_ostream &OS) const {
1296   DIScope::printInternal(OS);
1297   OS << " [";
1298   unsigned Lang = getLanguage();
1299   if (const char *LangStr = dwarf::LanguageString(Lang))
1300     OS << LangStr;
1301   else
1302     (OS << "lang 0x").write_hex(Lang);
1303   OS << ']';
1304 }
1305
1306 void DIEnumerator::printInternal(raw_ostream &OS) const {
1307   OS << " [" << getName() << " :: " << getEnumValue() << ']';
1308 }
1309
1310 void DIType::printInternal(raw_ostream &OS) const {
1311   if (!DbgNode)
1312     return;
1313
1314   StringRef Res = getName();
1315   if (!Res.empty())
1316     OS << " [" << Res << "]";
1317
1318   // TODO: Print context?
1319
1320   OS << " [line " << getLineNumber() << ", size " << getSizeInBits()
1321      << ", align " << getAlignInBits() << ", offset " << getOffsetInBits();
1322   if (isBasicType())
1323     if (const char *Enc =
1324             dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
1325       OS << ", enc " << Enc;
1326   OS << "]";
1327
1328   if (isPrivate())
1329     OS << " [private]";
1330   else if (isProtected())
1331     OS << " [protected]";
1332   else if (isPublic())
1333     OS << " [public]";
1334
1335   if (isArtificial())
1336     OS << " [artificial]";
1337
1338   if (isForwardDecl())
1339     OS << " [decl]";
1340   else if (getTag() == dwarf::DW_TAG_structure_type ||
1341            getTag() == dwarf::DW_TAG_union_type ||
1342            getTag() == dwarf::DW_TAG_enumeration_type ||
1343            getTag() == dwarf::DW_TAG_class_type)
1344     OS << " [def]";
1345   if (isVector())
1346     OS << " [vector]";
1347   if (isStaticMember())
1348     OS << " [static]";
1349
1350   if (isLValueReference())
1351     OS << " [reference]";
1352
1353   if (isRValueReference())
1354     OS << " [rvalue reference]";
1355 }
1356
1357 void DIDerivedType::printInternal(raw_ostream &OS) const {
1358   DIType::printInternal(OS);
1359   OS << " [from " << getTypeDerivedFrom().getName() << ']';
1360 }
1361
1362 void DICompositeType::printInternal(raw_ostream &OS) const {
1363   DIType::printInternal(OS);
1364   DIArray A = getElements();
1365   OS << " [" << A.getNumElements() << " elements]";
1366 }
1367
1368 void DINameSpace::printInternal(raw_ostream &OS) const {
1369   StringRef Name = getName();
1370   if (!Name.empty())
1371     OS << " [" << Name << ']';
1372
1373   OS << " [line " << getLineNumber() << ']';
1374 }
1375
1376 void DISubprogram::printInternal(raw_ostream &OS) const {
1377   // TODO : Print context
1378   OS << " [line " << getLineNumber() << ']';
1379
1380   if (isLocalToUnit())
1381     OS << " [local]";
1382
1383   if (isDefinition())
1384     OS << " [def]";
1385
1386   if (getScopeLineNumber() != getLineNumber())
1387     OS << " [scope " << getScopeLineNumber() << "]";
1388
1389   if (isPrivate())
1390     OS << " [private]";
1391   else if (isProtected())
1392     OS << " [protected]";
1393   else if (isPublic())
1394     OS << " [public]";
1395
1396   if (isLValueReference())
1397     OS << " [reference]";
1398
1399   if (isRValueReference())
1400     OS << " [rvalue reference]";
1401
1402   StringRef Res = getName();
1403   if (!Res.empty())
1404     OS << " [" << Res << ']';
1405 }
1406
1407 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
1408   StringRef Res = getName();
1409   if (!Res.empty())
1410     OS << " [" << Res << ']';
1411
1412   OS << " [line " << getLineNumber() << ']';
1413
1414   // TODO : Print context
1415
1416   if (isLocalToUnit())
1417     OS << " [local]";
1418
1419   if (isDefinition())
1420     OS << " [def]";
1421 }
1422
1423 void DIVariable::printInternal(raw_ostream &OS) const {
1424   StringRef Res = getName();
1425   if (!Res.empty())
1426     OS << " [" << Res << ']';
1427
1428   OS << " [line " << getLineNumber() << ']';
1429 }
1430
1431 void DIExpression::printInternal(raw_ostream &OS) const {
1432   for (auto Op : *this) {
1433     OS << " [" << OperationEncodingString(Op);
1434     switch (Op) {
1435     case DW_OP_plus: {
1436       OS << " " << Op.getArg(1);
1437       break;
1438     }
1439     case DW_OP_bit_piece: {
1440       OS << " offset=" << Op.getArg(1) << ", size=" << Op.getArg(2);
1441       break;
1442     }
1443     case DW_OP_deref:
1444       // No arguments.
1445       break;
1446     default:
1447       llvm_unreachable("unhandled operation");
1448     }
1449     OS << "]";
1450   }
1451 }
1452
1453 void DIObjCProperty::printInternal(raw_ostream &OS) const {
1454   StringRef Name = getObjCPropertyName();
1455   if (!Name.empty())
1456     OS << " [" << Name << ']';
1457
1458   OS << " [line " << getLineNumber() << ", properties " << getUnsignedField(6)
1459      << ']';
1460 }
1461
1462 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
1463                           const LLVMContext &Ctx) {
1464   if (!DL.isUnknown()) { // Print source line info.
1465     DIScope Scope(DL.getScope(Ctx));
1466     assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
1467     // Omit the directory, because it's likely to be long and uninteresting.
1468     CommentOS << Scope.getFilename();
1469     CommentOS << ':' << DL.getLine();
1470     if (DL.getCol() != 0)
1471       CommentOS << ':' << DL.getCol();
1472     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1473     if (!InlinedAtDL.isUnknown()) {
1474       CommentOS << " @[ ";
1475       printDebugLoc(InlinedAtDL, CommentOS, Ctx);
1476       CommentOS << " ]";
1477     }
1478   }
1479 }
1480
1481 void DIVariable::printExtendedName(raw_ostream &OS) const {
1482   const LLVMContext &Ctx = DbgNode->getContext();
1483   StringRef Res = getName();
1484   if (!Res.empty())
1485     OS << Res << "," << getLineNumber();
1486   if (MDNode *InlinedAt = getInlinedAt()) {
1487     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1488     if (!InlinedAtDL.isUnknown()) {
1489       OS << " @[";
1490       printDebugLoc(InlinedAtDL, OS, Ctx);
1491       OS << "]";
1492     }
1493   }
1494 }
1495
1496 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V) : Val(V) {
1497   assert(isDescriptorRef(V) &&
1498          "DIDescriptorRef should be a MDString or MDNode");
1499 }
1500 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
1501   assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
1502 }
1503 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
1504   assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
1505 }
1506
1507 template <>
1508 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const {
1509   return DIDescriptorRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
1510 }
1511 template <>
1512 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
1513   return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
1514 }
1515 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
1516   return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
1517 }
1518
1519 bool llvm::StripDebugInfo(Module &M) {
1520   bool Changed = false;
1521
1522   // Remove all of the calls to the debugger intrinsics, and remove them from
1523   // the module.
1524   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
1525     while (!Declare->use_empty()) {
1526       CallInst *CI = cast<CallInst>(Declare->user_back());
1527       CI->eraseFromParent();
1528     }
1529     Declare->eraseFromParent();
1530     Changed = true;
1531   }
1532
1533   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
1534     while (!DbgVal->use_empty()) {
1535       CallInst *CI = cast<CallInst>(DbgVal->user_back());
1536       CI->eraseFromParent();
1537     }
1538     DbgVal->eraseFromParent();
1539     Changed = true;
1540   }
1541
1542   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
1543          NME = M.named_metadata_end(); NMI != NME;) {
1544     NamedMDNode *NMD = NMI;
1545     ++NMI;
1546     if (NMD->getName().startswith("llvm.dbg.")) {
1547       NMD->eraseFromParent();
1548       Changed = true;
1549     }
1550   }
1551
1552   for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
1553     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
1554          ++FI)
1555       for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
1556            ++BI) {
1557         if (!BI->getDebugLoc().isUnknown()) {
1558           Changed = true;
1559           BI->setDebugLoc(DebugLoc());
1560         }
1561       }
1562
1563   return Changed;
1564 }
1565
1566 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
1567   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
1568           M.getModuleFlag("Debug Info Version")))
1569     return Val->getZExtValue();
1570   return 0;
1571 }
1572
1573 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
1574 llvm::makeSubprogramMap(const Module &M) {
1575   DenseMap<const Function *, DISubprogram> R;
1576
1577   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
1578   if (!CU_Nodes)
1579     return R;
1580
1581   for (MDNode *N : CU_Nodes->operands()) {
1582     DICompileUnit CUNode(N);
1583     DIArray SPs = CUNode.getSubprograms();
1584     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
1585       DISubprogram SP(SPs.getElement(i));
1586       if (Function *F = SP.getFunction())
1587         R.insert(std::make_pair(F, SP));
1588     }
1589   }
1590   return R;
1591 }