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