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