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