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