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