Remove unnecessary constructors as the default conversions will handle
[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           DITemplateTypeParameter(DbgNode).Verify() ||
49           DITemplateValueParameter(DbgNode).Verify() ||
50           DIImportedEntity(DbgNode).Verify());
51 }
52
53 static Value *getField(const MDNode *DbgNode, unsigned Elt) {
54   if (DbgNode == 0 || Elt >= DbgNode->getNumOperands())
55     return 0;
56   return DbgNode->getOperand(Elt);
57 }
58
59 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
60   return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
61 }
62
63 static StringRef getStringField(const MDNode *DbgNode, unsigned Elt) {
64   if (MDString *MDS = dyn_cast_or_null<MDString>(getField(DbgNode, Elt)))
65     return MDS->getString();
66   return StringRef();
67 }
68
69 StringRef DIDescriptor::getStringField(unsigned Elt) const {
70   return ::getStringField(DbgNode, Elt);
71 }
72
73 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
74   if (DbgNode == 0)
75     return 0;
76
77   if (Elt < DbgNode->getNumOperands())
78     if (ConstantInt *CI
79         = dyn_cast_or_null<ConstantInt>(DbgNode->getOperand(Elt)))
80       return CI->getZExtValue();
81
82   return 0;
83 }
84
85 int64_t DIDescriptor::getInt64Field(unsigned Elt) const {
86   if (DbgNode == 0)
87     return 0;
88
89   if (Elt < DbgNode->getNumOperands())
90     if (ConstantInt *CI
91         = dyn_cast_or_null<ConstantInt>(DbgNode->getOperand(Elt)))
92       return CI->getSExtValue();
93
94   return 0;
95 }
96
97 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
98   MDNode *Field = getNodeField(DbgNode, Elt);
99   return DIDescriptor(Field);
100 }
101
102 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
103   if (DbgNode == 0)
104     return 0;
105
106   if (Elt < DbgNode->getNumOperands())
107       return dyn_cast_or_null<GlobalVariable>(DbgNode->getOperand(Elt));
108   return 0;
109 }
110
111 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
112   if (DbgNode == 0)
113     return 0;
114
115   if (Elt < DbgNode->getNumOperands())
116       return dyn_cast_or_null<Constant>(DbgNode->getOperand(Elt));
117   return 0;
118 }
119
120 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
121   if (DbgNode == 0)
122     return 0;
123
124   if (Elt < DbgNode->getNumOperands())
125       return dyn_cast_or_null<Function>(DbgNode->getOperand(Elt));
126   return 0;
127 }
128
129 void DIDescriptor::replaceFunctionField(unsigned Elt, Function *F) {
130   if (DbgNode == 0)
131     return;
132
133   if (Elt < DbgNode->getNumOperands()) {
134     MDNode *Node = const_cast<MDNode*>(DbgNode);
135     Node->replaceOperandWith(Elt, F);
136   }
137 }
138
139 unsigned DIVariable::getNumAddrElements() const {
140   return DbgNode->getNumOperands()-8;
141 }
142
143 /// getInlinedAt - If this variable is inlined then return inline location.
144 MDNode *DIVariable::getInlinedAt() const {
145   return getNodeField(DbgNode, 7);
146 }
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) 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) return false;
168   switch (getTag()) {
169   case dwarf::DW_TAG_typedef:
170   case dwarf::DW_TAG_pointer_type:
171   case dwarf::DW_TAG_ptr_to_member_type:
172   case dwarf::DW_TAG_reference_type:
173   case dwarf::DW_TAG_rvalue_reference_type:
174   case dwarf::DW_TAG_const_type:
175   case dwarf::DW_TAG_volatile_type:
176   case dwarf::DW_TAG_restrict_type:
177   case dwarf::DW_TAG_member:
178   case dwarf::DW_TAG_inheritance:
179   case dwarf::DW_TAG_friend:
180     return true;
181   default:
182     // CompositeTypes are currently modelled as DerivedTypes.
183     return isCompositeType();
184   }
185 }
186
187 /// isCompositeType - Return true if the specified tag is legal for
188 /// DICompositeType.
189 bool DIDescriptor::isCompositeType() const {
190   if (!DbgNode) return false;
191   switch (getTag()) {
192   case dwarf::DW_TAG_array_type:
193   case dwarf::DW_TAG_structure_type:
194   case dwarf::DW_TAG_union_type:
195   case dwarf::DW_TAG_enumeration_type:
196   case dwarf::DW_TAG_subroutine_type:
197   case dwarf::DW_TAG_class_type:
198     return true;
199   default:
200     return false;
201   }
202 }
203
204 /// isVariable - Return true if the specified tag is legal for DIVariable.
205 bool DIDescriptor::isVariable() const {
206   if (!DbgNode) return false;
207   switch (getTag()) {
208   case dwarf::DW_TAG_auto_variable:
209   case dwarf::DW_TAG_arg_variable:
210     return true;
211   default:
212     return false;
213   }
214 }
215
216 /// isType - Return true if the specified tag is legal for DIType.
217 bool DIDescriptor::isType() const {
218   return isBasicType() || isCompositeType() || isDerivedType();
219 }
220
221 /// isSubprogram - Return true if the specified tag is legal for
222 /// DISubprogram.
223 bool DIDescriptor::isSubprogram() const {
224   return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
225 }
226
227 /// isGlobalVariable - Return true if the specified tag is legal for
228 /// DIGlobalVariable.
229 bool DIDescriptor::isGlobalVariable() const {
230   return DbgNode && (getTag() == dwarf::DW_TAG_variable ||
231                      getTag() == dwarf::DW_TAG_constant);
232 }
233
234 /// isGlobal - Return true if the specified tag is legal for DIGlobal.
235 bool DIDescriptor::isGlobal() const {
236   return isGlobalVariable();
237 }
238
239 /// isUnspecifiedParmeter - Return true if the specified tag is
240 /// DW_TAG_unspecified_parameters.
241 bool DIDescriptor::isUnspecifiedParameter() const {
242   return DbgNode && getTag() == dwarf::DW_TAG_unspecified_parameters;
243 }
244
245 /// isScope - Return true if the specified tag is one of the scope
246 /// related tag.
247 bool DIDescriptor::isScope() const {
248   if (!DbgNode) 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     return true;
255   default:
256     break;
257   }
258   return false;
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 debug info referenced by
336 /// this descriptor.
337 void DIType::replaceAllUsesWith(DIDescriptor &D) {
338   if (!DbgNode)
339     return;
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 debug info referenced by
356 /// this descriptor.
357 void DIType::replaceAllUsesWith(MDNode *D) {
358   if (!DbgNode)
359     return;
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 /// isUnsignedDIType - Return true if type encoding is unsigned.
376 bool DIType::isUnsignedDIType() {
377   DIDerivedType DTy(DbgNode);
378   if (DTy.Verify())
379     return DTy.getTypeDerivedFrom().isUnsignedDIType();
380
381   DIBasicType BTy(DbgNode);
382   if (BTy.Verify()) {
383     unsigned Encoding = BTy.getEncoding();
384     if (Encoding == dwarf::DW_ATE_unsigned ||
385         Encoding == dwarf::DW_ATE_unsigned_char ||
386         Encoding == dwarf::DW_ATE_boolean)
387       return true;
388   }
389   return false;
390 }
391
392 /// Verify - Verify that a compile unit is well formed.
393 bool DICompileUnit::Verify() const {
394   if (!isCompileUnit())
395     return false;
396
397   // Don't bother verifying the compilation directory or producer string
398   // as those could be empty.
399   if (getFilename().empty())
400     return false;
401
402   return DbgNode->getNumOperands() == 13;
403 }
404
405 /// Verify - Verify that an ObjC property is well formed.
406 bool DIObjCProperty::Verify() const {
407   if (!isObjCProperty())
408     return false;
409
410   // Don't worry about the rest of the strings for now.
411   return DbgNode->getNumOperands() == 8;
412 }
413
414 /// Verify - Verify that a type descriptor is well formed.
415 bool DIType::Verify() const {
416   if (!isType())
417     return false;
418   // FIXME: Sink this into the various subclass verifies.
419   unsigned Tag = getTag();
420   if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
421       Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
422       Tag != dwarf::DW_TAG_ptr_to_member_type &&
423       Tag != dwarf::DW_TAG_reference_type &&
424       Tag != dwarf::DW_TAG_rvalue_reference_type &&
425       Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
426       Tag != dwarf::DW_TAG_enumeration_type &&
427       Tag != dwarf::DW_TAG_subroutine_type &&
428       Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
429       getFilename().empty())
430     return false;
431   // DIType is abstract, it should be a BasicType, a DerivedType or
432   // a CompositeType.
433   if (isBasicType())
434     DIBasicType(DbgNode).Verify();
435   else if (isCompositeType())
436     DICompositeType(DbgNode).Verify();
437   else if (isDerivedType())
438     DIDerivedType(DbgNode).Verify();
439   else
440     return false;
441   return true;
442 }
443
444 /// Verify - Verify that a basic type descriptor is well formed.
445 bool DIBasicType::Verify() const {
446   return isBasicType() && DbgNode->getNumOperands() == 10;
447 }
448
449 /// Verify - Verify that a derived type descriptor is well formed.
450 bool DIDerivedType::Verify() const {
451   return isDerivedType() && DbgNode->getNumOperands() >= 10 &&
452          DbgNode->getNumOperands() <= 14;
453 }
454
455 /// Verify - Verify that a composite type descriptor is well formed.
456 bool DICompositeType::Verify() const {
457   if (!isCompositeType())
458     return false;
459
460   return DbgNode->getNumOperands() >= 10 && DbgNode->getNumOperands() <= 14;
461 }
462
463 /// Verify - Verify that a subprogram descriptor is well formed.
464 bool DISubprogram::Verify() const {
465   if (!isSubprogram())
466     return false;
467
468   return DbgNode->getNumOperands() == 20;
469 }
470
471 /// Verify - Verify that a global variable descriptor is well formed.
472 bool DIGlobalVariable::Verify() const {
473   if (!isGlobalVariable())
474     return false;
475
476   if (getDisplayName().empty())
477     return false;
478
479   return DbgNode->getNumOperands() == 13;
480 }
481
482 /// Verify - Verify that a variable descriptor is well formed.
483 bool DIVariable::Verify() const {
484   if (!isVariable())
485     return false;
486
487   return DbgNode->getNumOperands() >= 8;
488 }
489
490 /// Verify - Verify that a location descriptor is well formed.
491 bool DILocation::Verify() const {
492   if (!DbgNode)
493     return false;
494
495   return DbgNode->getNumOperands() == 4;
496 }
497
498 /// Verify - Verify that a namespace descriptor is well formed.
499 bool DINameSpace::Verify() const {
500   if (!isNameSpace())
501     return false;
502   return DbgNode->getNumOperands() == 5;
503 }
504
505 /// \brief Retrieve the MDNode for the directory/file pair.
506 MDNode *DIFile::getFileNode() const {
507   return getNodeField(DbgNode, 1);
508 }
509
510 /// \brief Verify that the file descriptor is well formed.
511 bool DIFile::Verify() const {
512   return isFile() && DbgNode->getNumOperands() == 2;
513 }
514
515 /// \brief Verify that the enumerator descriptor is well formed.
516 bool DIEnumerator::Verify() const {
517   return isEnumerator() && DbgNode->getNumOperands() == 3;
518 }
519
520 /// \brief Verify that the subrange descriptor is well formed.
521 bool DISubrange::Verify() const {
522   return isSubrange() && DbgNode->getNumOperands() == 3;
523 }
524
525 /// \brief Verify that the lexical block descriptor is well formed.
526 bool DILexicalBlock::Verify() const {
527   return isLexicalBlock() && DbgNode->getNumOperands() == 6;
528 }
529
530 /// \brief Verify that the file-scoped lexical block descriptor is well formed.
531 bool DILexicalBlockFile::Verify() const {
532   return isLexicalBlockFile() && DbgNode->getNumOperands() == 3;
533 }
534
535 /// \brief Verify that the template type parameter descriptor is well formed.
536 bool DITemplateTypeParameter::Verify() const {
537   return isTemplateTypeParameter() && DbgNode->getNumOperands() == 7;
538 }
539
540 /// \brief Verify that the template value parameter descriptor is well formed.
541 bool DITemplateValueParameter::Verify() const {
542   return isTemplateValueParameter() && DbgNode->getNumOperands() == 8;
543 }
544
545 /// \brief Verify that the imported module descriptor is well formed.
546 bool DIImportedEntity::Verify() const {
547   return isImportedEntity() &&
548          (DbgNode->getNumOperands() == 4 || DbgNode->getNumOperands() == 5);
549 }
550
551 /// getOriginalTypeSize - If this type is derived from a base type then
552 /// return base type size.
553 uint64_t DIDerivedType::getOriginalTypeSize() const {
554   unsigned Tag = getTag();
555
556   if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
557       Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
558       Tag != dwarf::DW_TAG_restrict_type)
559     return getSizeInBits();
560
561   DIType BaseType = getTypeDerivedFrom();
562
563   // If this type is not derived from any type then take conservative approach.
564   if (!BaseType.isValid())
565     return getSizeInBits();
566
567   // If this is a derived type, go ahead and get the base type, unless it's a
568   // reference then it's just the size of the field. Pointer types have no need
569   // of this since they're a different type of qualification on the type.
570   if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
571       BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
572     return getSizeInBits();
573
574   if (BaseType.isDerivedType())
575     return DIDerivedType(BaseType).getOriginalTypeSize();
576
577   return BaseType.getSizeInBits();
578 }
579
580 /// getObjCProperty - Return property node, if this ivar is associated with one.
581 MDNode *DIDerivedType::getObjCProperty() const {
582   return getNodeField(DbgNode, 10);
583 }
584
585 /// \brief Set the array of member DITypes.
586 void DICompositeType::setTypeArray(DIArray Elements, DIArray TParams) {
587   assert((!TParams || DbgNode->getNumOperands() == 14) &&
588          "If you're setting the template parameters this should include a slot "
589          "for that!");
590   TrackingVH<MDNode> N(*this);
591   N->replaceOperandWith(10, Elements);
592   if (TParams)
593     N->replaceOperandWith(13, TParams);
594   DbgNode = N;
595 }
596
597 /// \brief Set the containing type.
598 void DICompositeType::setContainingType(DICompositeType ContainingType) {
599   TrackingVH<MDNode> N(*this);
600   N->replaceOperandWith(12, ContainingType);
601   DbgNode = N;
602 }
603
604 /// isInlinedFnArgument - Return true if this variable provides debugging
605 /// information for an inlined function arguments.
606 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
607   assert(CurFn && "Invalid function");
608   if (!getContext().isSubprogram())
609     return false;
610   // This variable is not inlined function argument if its scope
611   // does not describe current function.
612   return !DISubprogram(getContext()).describes(CurFn);
613 }
614
615 /// describes - Return true if this subprogram provides debugging
616 /// information for the function F.
617 bool DISubprogram::describes(const Function *F) {
618   assert(F && "Invalid function");
619   if (F == getFunction())
620     return true;
621   StringRef Name = getLinkageName();
622   if (Name.empty())
623     Name = getName();
624   if (F->getName() == Name)
625     return true;
626   return false;
627 }
628
629 unsigned DISubprogram::isOptimized() const {
630   assert (DbgNode && "Invalid subprogram descriptor!");
631   if (DbgNode->getNumOperands() == 15)
632     return getUnsignedField(14);
633   return 0;
634 }
635
636 MDNode *DISubprogram::getVariablesNodes() const {
637   return getNodeField(DbgNode, 18);
638 }
639
640 DIArray DISubprogram::getVariables() const {
641   return DIArray(getNodeField(DbgNode, 18));
642 }
643
644 Value *DITemplateValueParameter::getValue() const {
645   return getField(DbgNode, 4);
646 }
647
648 StringRef DIScope::getFilename() const {
649   if (!DbgNode)
650     return StringRef();
651   return ::getStringField(getNodeField(DbgNode, 1), 0);
652 }
653
654 StringRef DIScope::getDirectory() const {
655   if (!DbgNode)
656     return StringRef();
657   return ::getStringField(getNodeField(DbgNode, 1), 1);
658 }
659
660 DIArray DICompileUnit::getEnumTypes() const {
661   if (!DbgNode || DbgNode->getNumOperands() < 13)
662     return DIArray();
663
664   return DIArray(getNodeField(DbgNode, 7));
665 }
666
667 DIArray DICompileUnit::getRetainedTypes() const {
668   if (!DbgNode || DbgNode->getNumOperands() < 13)
669     return DIArray();
670
671   return DIArray(getNodeField(DbgNode, 8));
672 }
673
674 DIArray DICompileUnit::getSubprograms() const {
675   if (!DbgNode || DbgNode->getNumOperands() < 13)
676     return DIArray();
677
678   return DIArray(getNodeField(DbgNode, 9));
679 }
680
681
682 DIArray DICompileUnit::getGlobalVariables() const {
683   if (!DbgNode || DbgNode->getNumOperands() < 13)
684     return DIArray();
685
686   return DIArray(getNodeField(DbgNode, 10));
687 }
688
689 DIArray DICompileUnit::getImportedEntities() const {
690   if (!DbgNode || DbgNode->getNumOperands() < 13)
691     return DIArray();
692
693   return DIArray(getNodeField(DbgNode, 11));
694 }
695
696 /// fixupSubprogramName - Replace contains special characters used
697 /// in a typical Objective-C names with '.' in a given string.
698 static void fixupSubprogramName(DISubprogram Fn, SmallVectorImpl<char> &Out) {
699   StringRef FName =
700       Fn.getFunction() ? Fn.getFunction()->getName() : Fn.getName();
701   FName = Function::getRealLinkageName(FName);
702
703   StringRef Prefix("llvm.dbg.lv.");
704   Out.reserve(FName.size() + Prefix.size());
705   Out.append(Prefix.begin(), Prefix.end());
706
707   bool isObjCLike = false;
708   for (size_t i = 0, e = FName.size(); i < e; ++i) {
709     char C = FName[i];
710     if (C == '[')
711       isObjCLike = true;
712
713     if (isObjCLike && (C == '[' || C == ']' || C == ' ' || C == ':' ||
714                        C == '+' || C == '(' || C == ')'))
715       Out.push_back('.');
716     else
717       Out.push_back(C);
718   }
719 }
720
721 /// getFnSpecificMDNode - Return a NameMDNode, if available, that is
722 /// suitable to hold function specific information.
723 NamedMDNode *llvm::getFnSpecificMDNode(const Module &M, DISubprogram Fn) {
724   SmallString<32> Name;
725   fixupSubprogramName(Fn, Name);
726   return M.getNamedMetadata(Name.str());
727 }
728
729 /// getOrInsertFnSpecificMDNode - Return a NameMDNode that is suitable
730 /// to hold function specific information.
731 NamedMDNode *llvm::getOrInsertFnSpecificMDNode(Module &M, DISubprogram Fn) {
732   SmallString<32> Name;
733   fixupSubprogramName(Fn, Name);
734   return M.getOrInsertNamedMetadata(Name.str());
735 }
736
737 /// createInlinedVariable - Create a new inlined variable based on current
738 /// variable.
739 /// @param DV            Current Variable.
740 /// @param InlinedScope  Location at current variable is inlined.
741 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
742                                        LLVMContext &VMContext) {
743   SmallVector<Value *, 16> Elts;
744   // Insert inlined scope as 7th element.
745   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
746     i == 7 ? Elts.push_back(InlinedScope) :
747              Elts.push_back(DV->getOperand(i));
748   return DIVariable(MDNode::get(VMContext, Elts));
749 }
750
751 /// cleanseInlinedVariable - Remove inlined scope from the variable.
752 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
753   SmallVector<Value *, 16> Elts;
754   // Insert inlined scope as 7th element.
755   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
756     i == 7 ?
757       Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext))):
758       Elts.push_back(DV->getOperand(i));
759   return DIVariable(MDNode::get(VMContext, Elts));
760 }
761
762 /// getDISubprogram - Find subprogram that is enclosing this scope.
763 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
764   DIDescriptor D(Scope);
765   if (D.isSubprogram())
766     return DISubprogram(Scope);
767
768   if (D.isLexicalBlockFile())
769     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
770
771   if (D.isLexicalBlock())
772     return getDISubprogram(DILexicalBlock(Scope).getContext());
773
774   return DISubprogram();
775 }
776
777 /// getDICompositeType - Find underlying composite type.
778 DICompositeType llvm::getDICompositeType(DIType T) {
779   if (T.isCompositeType())
780     return DICompositeType(T);
781
782   if (T.isDerivedType())
783     return getDICompositeType(DIDerivedType(T).getTypeDerivedFrom());
784
785   return DICompositeType();
786 }
787
788 /// isSubprogramContext - Return true if Context is either a subprogram
789 /// or another context nested inside a subprogram.
790 bool llvm::isSubprogramContext(const MDNode *Context) {
791   if (!Context)
792     return false;
793   DIDescriptor D(Context);
794   if (D.isSubprogram())
795     return true;
796   if (D.isType())
797     return isSubprogramContext(DIType(Context).getContext());
798   return false;
799 }
800
801 //===----------------------------------------------------------------------===//
802 // DebugInfoFinder implementations.
803 //===----------------------------------------------------------------------===//
804
805 void DebugInfoFinder::reset() {
806   CUs.clear();
807   SPs.clear();
808   GVs.clear();
809   TYs.clear();
810   Scopes.clear();
811   NodesSeen.clear();
812 }
813
814 /// processModule - Process entire module and collect debug info.
815 void DebugInfoFinder::processModule(const Module &M) {
816   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
817     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
818       DICompileUnit CU(CU_Nodes->getOperand(i));
819       addCompileUnit(CU);
820       DIArray GVs = CU.getGlobalVariables();
821       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
822         DIGlobalVariable DIG(GVs.getElement(i));
823         if (addGlobalVariable(DIG)) {
824           processScope(DIG.getContext());
825           processType(DIG.getType());
826         }
827       }
828       DIArray SPs = CU.getSubprograms();
829       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
830         processSubprogram(DISubprogram(SPs.getElement(i)));
831       DIArray EnumTypes = CU.getEnumTypes();
832       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
833         processType(DIType(EnumTypes.getElement(i)));
834       DIArray RetainedTypes = CU.getRetainedTypes();
835       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
836         processType(DIType(RetainedTypes.getElement(i)));
837       // FIXME: We really shouldn't be bailing out after visiting just one CU
838       return;
839     }
840   }
841 }
842
843 /// processLocation - Process DILocation.
844 void DebugInfoFinder::processLocation(DILocation Loc) {
845   if (!Loc.Verify()) return;
846   DIDescriptor S(Loc.getScope());
847   if (S.isCompileUnit())
848     addCompileUnit(DICompileUnit(S));
849   else if (S.isSubprogram())
850     processSubprogram(DISubprogram(S));
851   else if (S.isLexicalBlock())
852     processLexicalBlock(DILexicalBlock(S));
853   else if (S.isLexicalBlockFile()) {
854     DILexicalBlockFile DBF = DILexicalBlockFile(S);
855     processLexicalBlock(DILexicalBlock(DBF.getScope()));
856   }
857   processLocation(Loc.getOrigLocation());
858 }
859
860 /// processType - Process DIType.
861 void DebugInfoFinder::processType(DIType DT) {
862   if (!addType(DT))
863     return;
864   processScope(DT.getContext());
865   if (DT.isCompositeType()) {
866     DICompositeType DCT(DT);
867     processType(DCT.getTypeDerivedFrom());
868     DIArray DA = DCT.getTypeArray();
869     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
870       DIDescriptor D = DA.getElement(i);
871       if (D.isType())
872         processType(DIType(D));
873       else if (D.isSubprogram())
874         processSubprogram(DISubprogram(D));
875     }
876   } else if (DT.isDerivedType()) {
877     DIDerivedType DDT(DT);
878     processType(DDT.getTypeDerivedFrom());
879   }
880 }
881
882 void DebugInfoFinder::processScope(DIScope Scope) {
883   if (Scope.isType()) {
884     DIType Ty(Scope);
885     processType(Ty);
886     return;
887   }
888   if (Scope.isCompileUnit()) {
889     addCompileUnit(DICompileUnit(Scope));
890     return;
891   }
892   if (Scope.isSubprogram()) {
893     processSubprogram(DISubprogram(Scope));
894     return;
895   }
896   if (!addScope(Scope))
897     return;
898   if (Scope.isLexicalBlock()) {
899     DILexicalBlock LB(Scope);
900     processScope(LB.getContext());
901   } else if (Scope.isLexicalBlockFile()) {
902     DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
903     processScope(LBF.getScope());
904   } else if (Scope.isNameSpace()) {
905     DINameSpace NS(Scope);
906     processScope(NS.getContext());
907   }
908 }
909
910 /// processLexicalBlock
911 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
912   DIScope Context = LB.getContext();
913   if (Context.isLexicalBlock())
914     return processLexicalBlock(DILexicalBlock(Context));
915   else if (Context.isLexicalBlockFile()) {
916     DILexicalBlockFile DBF = DILexicalBlockFile(Context);
917     return processLexicalBlock(DILexicalBlock(DBF.getScope()));
918   }
919   else
920     return processSubprogram(DISubprogram(Context));
921 }
922
923 /// processSubprogram - Process DISubprogram.
924 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
925   if (!addSubprogram(SP))
926     return;
927   processScope(SP.getContext());
928   processType(SP.getType());
929 }
930
931 /// processDeclare - Process DbgDeclareInst.
932 void DebugInfoFinder::processDeclare(const DbgDeclareInst *DDI) {
933   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
934   if (!N) return;
935
936   DIDescriptor DV(N);
937   if (!DV.isVariable())
938     return;
939
940   if (!NodesSeen.insert(DV))
941     return;
942   processScope(DIVariable(N).getContext());
943   processType(DIVariable(N).getType());
944 }
945
946 void DebugInfoFinder::processValue(const DbgValueInst *DVI) {
947   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
948   if (!N) return;
949
950   DIDescriptor DV(N);
951   if (!DV.isVariable())
952     return;
953
954   if (!NodesSeen.insert(DV))
955     return;
956   processType(DIVariable(N).getType());
957 }
958
959 /// addType - Add type into Tys.
960 bool DebugInfoFinder::addType(DIType DT) {
961   if (!DT.isValid())
962     return false;
963
964   if (!NodesSeen.insert(DT))
965     return false;
966
967   TYs.push_back(DT);
968   return true;
969 }
970
971 /// addCompileUnit - Add compile unit into CUs.
972 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
973   if (!CU.Verify())
974     return false;
975
976   if (!NodesSeen.insert(CU))
977     return false;
978
979   CUs.push_back(CU);
980   return true;
981 }
982
983 /// addGlobalVariable - Add global variable into GVs.
984 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
985   if (!DIDescriptor(DIG).isGlobalVariable())
986     return false;
987
988   if (!NodesSeen.insert(DIG))
989     return false;
990
991   GVs.push_back(DIG);
992   return true;
993 }
994
995 // addSubprogram - Add subprgoram into SPs.
996 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
997   if (!DIDescriptor(SP).isSubprogram())
998     return false;
999
1000   if (!NodesSeen.insert(SP))
1001     return false;
1002
1003   SPs.push_back(SP);
1004   return true;
1005 }
1006
1007 bool DebugInfoFinder::addScope(DIScope Scope) {
1008   if (!Scope)
1009     return false;
1010   if (!NodesSeen.insert(Scope))
1011     return false;
1012   Scopes.push_back(Scope);
1013   return true;
1014 }
1015
1016 //===----------------------------------------------------------------------===//
1017 // DIDescriptor: dump routines for all descriptors.
1018 //===----------------------------------------------------------------------===//
1019
1020 /// dump - Print descriptor to dbgs() with a newline.
1021 void DIDescriptor::dump() const {
1022   print(dbgs()); dbgs() << '\n';
1023 }
1024
1025 /// print - Print descriptor.
1026 void DIDescriptor::print(raw_ostream &OS) const {
1027   if (!DbgNode) return;
1028
1029   if (const char *Tag = dwarf::TagString(getTag()))
1030     OS << "[ " << Tag << " ]";
1031
1032   if (this->isSubrange()) {
1033     DISubrange(DbgNode).printInternal(OS);
1034   } else if (this->isCompileUnit()) {
1035     DICompileUnit(DbgNode).printInternal(OS);
1036   } else if (this->isFile()) {
1037     DIFile(DbgNode).printInternal(OS);
1038   } else if (this->isEnumerator()) {
1039     DIEnumerator(DbgNode).printInternal(OS);
1040   } else if (this->isBasicType()) {
1041     DIType(DbgNode).printInternal(OS);
1042   } else if (this->isDerivedType()) {
1043     DIDerivedType(DbgNode).printInternal(OS);
1044   } else if (this->isCompositeType()) {
1045     DICompositeType(DbgNode).printInternal(OS);
1046   } else if (this->isSubprogram()) {
1047     DISubprogram(DbgNode).printInternal(OS);
1048   } else if (this->isGlobalVariable()) {
1049     DIGlobalVariable(DbgNode).printInternal(OS);
1050   } else if (this->isVariable()) {
1051     DIVariable(DbgNode).printInternal(OS);
1052   } else if (this->isObjCProperty()) {
1053     DIObjCProperty(DbgNode).printInternal(OS);
1054   } else if (this->isNameSpace()) {
1055     DINameSpace(DbgNode).printInternal(OS);
1056   } else if (this->isScope()) {
1057     DIScope(DbgNode).printInternal(OS);
1058   }
1059 }
1060
1061 void DISubrange::printInternal(raw_ostream &OS) const {
1062   int64_t Count = getCount();
1063   if (Count != -1)
1064     OS << " [" << getLo() << ", " << Count - 1 << ']';
1065   else
1066     OS << " [unbounded]";
1067 }
1068
1069 void DIScope::printInternal(raw_ostream &OS) const {
1070   OS << " [" << getDirectory() << "/" << getFilename() << ']';
1071 }
1072
1073 void DICompileUnit::printInternal(raw_ostream &OS) const {
1074   DIScope::printInternal(OS);
1075   OS << " [";
1076   unsigned Lang = getLanguage();
1077   if (const char *LangStr = dwarf::LanguageString(Lang))
1078     OS << LangStr;
1079   else
1080     (OS << "lang 0x").write_hex(Lang);
1081   OS << ']';
1082 }
1083
1084 void DIEnumerator::printInternal(raw_ostream &OS) const {
1085   OS << " [" << getName() << " :: " << getEnumValue() << ']';
1086 }
1087
1088 void DIType::printInternal(raw_ostream &OS) const {
1089   if (!DbgNode) return;
1090
1091   StringRef Res = getName();
1092   if (!Res.empty())
1093     OS << " [" << Res << "]";
1094
1095   // TODO: Print context?
1096
1097   OS << " [line " << getLineNumber()
1098      << ", size " << getSizeInBits()
1099      << ", align " << getAlignInBits()
1100      << ", offset " << getOffsetInBits();
1101   if (isBasicType())
1102     if (const char *Enc =
1103         dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
1104       OS << ", enc " << Enc;
1105   OS << "]";
1106
1107   if (isPrivate())
1108     OS << " [private]";
1109   else if (isProtected())
1110     OS << " [protected]";
1111
1112   if (isArtificial())
1113     OS << " [artificial]";
1114
1115   if (isForwardDecl())
1116     OS << " [decl]";
1117   else if (getTag() == dwarf::DW_TAG_structure_type ||
1118            getTag() == dwarf::DW_TAG_union_type ||
1119            getTag() == dwarf::DW_TAG_enumeration_type ||
1120            getTag() == dwarf::DW_TAG_class_type)
1121     OS << " [def]";
1122   if (isVector())
1123     OS << " [vector]";
1124   if (isStaticMember())
1125     OS << " [static]";
1126 }
1127
1128 void DIDerivedType::printInternal(raw_ostream &OS) const {
1129   DIType::printInternal(OS);
1130   OS << " [from " << getTypeDerivedFrom().getName() << ']';
1131 }
1132
1133 void DICompositeType::printInternal(raw_ostream &OS) const {
1134   DIType::printInternal(OS);
1135   DIArray A = getTypeArray();
1136   OS << " [" << A.getNumElements() << " elements]";
1137 }
1138
1139 void DINameSpace::printInternal(raw_ostream &OS) const {
1140   StringRef Name = getName();
1141   if (!Name.empty())
1142     OS << " [" << Name << ']';
1143
1144   OS << " [line " << getLineNumber() << ']';
1145 }
1146
1147 void DISubprogram::printInternal(raw_ostream &OS) const {
1148   // TODO : Print context
1149   OS << " [line " << getLineNumber() << ']';
1150
1151   if (isLocalToUnit())
1152     OS << " [local]";
1153
1154   if (isDefinition())
1155     OS << " [def]";
1156
1157   if (getScopeLineNumber() != getLineNumber())
1158     OS << " [scope " << getScopeLineNumber() << "]";
1159
1160   if (isPrivate())
1161     OS << " [private]";
1162   else if (isProtected())
1163     OS << " [protected]";
1164
1165   StringRef Res = getName();
1166   if (!Res.empty())
1167     OS << " [" << Res << ']';
1168 }
1169
1170 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
1171   StringRef Res = getName();
1172   if (!Res.empty())
1173     OS << " [" << Res << ']';
1174
1175   OS << " [line " << getLineNumber() << ']';
1176
1177   // TODO : Print context
1178
1179   if (isLocalToUnit())
1180     OS << " [local]";
1181
1182   if (isDefinition())
1183     OS << " [def]";
1184 }
1185
1186 void DIVariable::printInternal(raw_ostream &OS) const {
1187   StringRef Res = getName();
1188   if (!Res.empty())
1189     OS << " [" << Res << ']';
1190
1191   OS << " [line " << getLineNumber() << ']';
1192 }
1193
1194 void DIObjCProperty::printInternal(raw_ostream &OS) const {
1195   StringRef Name = getObjCPropertyName();
1196   if (!Name.empty())
1197     OS << " [" << Name << ']';
1198
1199   OS << " [line " << getLineNumber()
1200      << ", properties " << getUnsignedField(6) << ']';
1201 }
1202
1203 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
1204                           const LLVMContext &Ctx) {
1205   if (!DL.isUnknown()) {          // Print source line info.
1206     DIScope Scope(DL.getScope(Ctx));
1207     assert(Scope.isScope() &&
1208       "Scope of a DebugLoc should be a DIScope.");
1209     // Omit the directory, because it's likely to be long and uninteresting.
1210     CommentOS << Scope.getFilename();
1211     CommentOS << ':' << DL.getLine();
1212     if (DL.getCol() != 0)
1213       CommentOS << ':' << DL.getCol();
1214     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1215     if (!InlinedAtDL.isUnknown()) {
1216       CommentOS << " @[ ";
1217       printDebugLoc(InlinedAtDL, CommentOS, Ctx);
1218       CommentOS << " ]";
1219     }
1220   }
1221 }
1222
1223 void DIVariable::printExtendedName(raw_ostream &OS) const {
1224   const LLVMContext &Ctx = DbgNode->getContext();
1225   StringRef Res = getName();
1226   if (!Res.empty())
1227     OS << Res << "," << getLineNumber();
1228   if (MDNode *InlinedAt = getInlinedAt()) {
1229     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1230     if (!InlinedAtDL.isUnknown()) {
1231       OS << " @[";
1232       printDebugLoc(InlinedAtDL, OS, Ctx);
1233       OS << "]";
1234     }
1235   }
1236 }