Debug Info: improve the verifier to check field types.
[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 /// isUnspecifiedParmeter - Return true if the specified tag is
235 /// DW_TAG_unspecified_parameters.
236 bool DIDescriptor::isUnspecifiedParameter() const {
237   return DbgNode && getTag() == dwarf::DW_TAG_unspecified_parameters;
238 }
239
240 /// isScope - Return true if the specified tag is one of the scope
241 /// related tag.
242 bool DIDescriptor::isScope() const {
243   if (!DbgNode) return false;
244   switch (getTag()) {
245   case dwarf::DW_TAG_compile_unit:
246   case dwarf::DW_TAG_lexical_block:
247   case dwarf::DW_TAG_subprogram:
248   case dwarf::DW_TAG_namespace:
249     return true;
250   default:
251     break;
252   }
253   return false;
254 }
255
256 /// isTemplateTypeParameter - Return true if the specified tag is
257 /// DW_TAG_template_type_parameter.
258 bool DIDescriptor::isTemplateTypeParameter() const {
259   return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter;
260 }
261
262 /// isTemplateValueParameter - Return true if the specified tag is
263 /// DW_TAG_template_value_parameter.
264 bool DIDescriptor::isTemplateValueParameter() const {
265   return DbgNode && (getTag() == dwarf::DW_TAG_template_value_parameter ||
266                      getTag() == dwarf::DW_TAG_GNU_template_template_param ||
267                      getTag() == dwarf::DW_TAG_GNU_template_parameter_pack);
268 }
269
270 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
271 bool DIDescriptor::isCompileUnit() const {
272   return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
273 }
274
275 /// isFile - Return true if the specified tag is DW_TAG_file_type.
276 bool DIDescriptor::isFile() const {
277   return DbgNode && getTag() == dwarf::DW_TAG_file_type;
278 }
279
280 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
281 bool DIDescriptor::isNameSpace() const {
282   return DbgNode && getTag() == dwarf::DW_TAG_namespace;
283 }
284
285 /// isLexicalBlockFile - Return true if the specified descriptor is a
286 /// lexical block with an extra file.
287 bool DIDescriptor::isLexicalBlockFile() const {
288   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
289     (DbgNode->getNumOperands() == 3);
290 }
291
292 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
293 bool DIDescriptor::isLexicalBlock() const {
294   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
295     (DbgNode->getNumOperands() > 3);
296 }
297
298 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
299 bool DIDescriptor::isSubrange() const {
300   return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
301 }
302
303 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
304 bool DIDescriptor::isEnumerator() const {
305   return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
306 }
307
308 /// isObjCProperty - Return true if the specified tag is DW_TAG_APPLE_property.
309 bool DIDescriptor::isObjCProperty() const {
310   return DbgNode && getTag() == dwarf::DW_TAG_APPLE_property;
311 }
312
313 /// \brief Return true if the specified tag is DW_TAG_imported_module or
314 /// DW_TAG_imported_declaration.
315 bool DIDescriptor::isImportedEntity() const {
316   return DbgNode && (getTag() == dwarf::DW_TAG_imported_module ||
317                      getTag() == dwarf::DW_TAG_imported_declaration);
318 }
319
320 //===----------------------------------------------------------------------===//
321 // Simple Descriptor Constructors and other Methods
322 //===----------------------------------------------------------------------===//
323
324 unsigned DIArray::getNumElements() const {
325   if (!DbgNode)
326     return 0;
327   return DbgNode->getNumOperands();
328 }
329
330 /// replaceAllUsesWith - Replace all uses of the MDNode used by this
331 /// type with the one in the passed descriptor.
332 void DIType::replaceAllUsesWith(DIDescriptor &D) {
333
334   assert(DbgNode && "Trying to replace an unverified type!");
335
336   // Since we use a TrackingVH for the node, its easy for clients to manufacture
337   // legitimate situations where they want to replaceAllUsesWith() on something
338   // which, due to uniquing, has merged with the source. We shield clients from
339   // this detail by allowing a value to be replaced with replaceAllUsesWith()
340   // itself.
341   if (DbgNode != D) {
342     MDNode *Node = const_cast<MDNode*>(DbgNode);
343     const MDNode *DN = D;
344     const Value *V = cast_or_null<Value>(DN);
345     Node->replaceAllUsesWith(const_cast<Value*>(V));
346     MDNode::deleteTemporary(Node);
347   }
348 }
349
350 /// replaceAllUsesWith - Replace all uses of the MDNode used by this
351 /// type with the one in D.
352 void DIType::replaceAllUsesWith(MDNode *D) {
353
354   assert(DbgNode && "Trying to replace an unverified type!");
355
356   // Since we use a TrackingVH for the node, its easy for clients to manufacture
357   // legitimate situations where they want to replaceAllUsesWith() on something
358   // which, due to uniquing, has merged with the source. We shield clients from
359   // this detail by allowing a value to be replaced with replaceAllUsesWith()
360   // itself.
361   if (DbgNode != D) {
362     MDNode *Node = const_cast<MDNode*>(DbgNode);
363     const MDNode *DN = D;
364     const Value *V = cast_or_null<Value>(DN);
365     Node->replaceAllUsesWith(const_cast<Value*>(V));
366     MDNode::deleteTemporary(Node);
367   }
368 }
369
370 /// isUnsignedDIType - Return true if type encoding is unsigned.
371 bool DIType::isUnsignedDIType() {
372   DIDerivedType DTy(DbgNode);
373   if (DTy.Verify())
374     return DTy.getTypeDerivedFrom().isUnsignedDIType();
375
376   DIBasicType BTy(DbgNode);
377   if (BTy.Verify()) {
378     unsigned Encoding = BTy.getEncoding();
379     if (Encoding == dwarf::DW_ATE_unsigned ||
380         Encoding == dwarf::DW_ATE_unsigned_char ||
381         Encoding == dwarf::DW_ATE_boolean)
382       return true;
383   }
384   return false;
385 }
386
387 /// Verify - Verify that a compile unit is well formed.
388 bool DICompileUnit::Verify() const {
389   if (!isCompileUnit())
390     return false;
391
392   // Don't bother verifying the compilation directory or producer string
393   // as those could be empty.
394   if (getFilename().empty())
395     return false;
396
397   return DbgNode->getNumOperands() == 13;
398 }
399
400 /// Verify - Verify that an ObjC property is well formed.
401 bool DIObjCProperty::Verify() const {
402   if (!isObjCProperty())
403     return false;
404
405   // Don't worry about the rest of the strings for now.
406   return DbgNode->getNumOperands() == 8;
407 }
408
409 /// We allow an empty string to represent null. But we don't allow
410 /// a non-empty string in a MDNode field.
411 static bool fieldIsMDNode(const MDNode *DbgNode, unsigned Elt) {
412   Value *Fld = getField(DbgNode, Elt);
413   if (Fld && isa<MDString>(Fld) &&
414       !cast<MDString>(Fld)->getString().empty())
415     return false;
416   return true;
417 }
418
419 /// Verify - Verify that a type descriptor is well formed.
420 bool DIType::Verify() const {
421   if (!isType())
422     return false;
423   // Make sure Context @ field 2 is MDNode.
424   if (!fieldIsMDNode(DbgNode, 2))
425     return false;
426
427   // FIXME: Sink this into the various subclass verifies.
428   unsigned Tag = getTag();
429   if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
430       Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
431       Tag != dwarf::DW_TAG_ptr_to_member_type &&
432       Tag != dwarf::DW_TAG_reference_type &&
433       Tag != dwarf::DW_TAG_rvalue_reference_type &&
434       Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
435       Tag != dwarf::DW_TAG_enumeration_type &&
436       Tag != dwarf::DW_TAG_subroutine_type &&
437       Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
438       getFilename().empty())
439     return false;
440   // DIType is abstract, it should be a BasicType, a DerivedType or
441   // a CompositeType.
442   if (isBasicType())
443     DIBasicType(DbgNode).Verify();
444   else if (isCompositeType())
445     DICompositeType(DbgNode).Verify();
446   else if (isDerivedType())
447     DIDerivedType(DbgNode).Verify();
448   else
449     return false;
450   return true;
451 }
452
453 /// Verify - Verify that a basic type descriptor is well formed.
454 bool DIBasicType::Verify() const {
455   return isBasicType() && DbgNode->getNumOperands() == 10;
456 }
457
458 /// Verify - Verify that a derived type descriptor is well formed.
459 bool DIDerivedType::Verify() const {
460   // Make sure DerivedFrom @ field 9 is MDNode.
461   if (!fieldIsMDNode(DbgNode, 9))
462     return false;
463   if (getTag() == dwarf::DW_TAG_ptr_to_member_type)
464     // Make sure ClassType @ field 10 is MDNode.
465     if (!fieldIsMDNode(DbgNode, 10))
466       return false;
467
468   return isDerivedType() && DbgNode->getNumOperands() >= 10 &&
469          DbgNode->getNumOperands() <= 14;
470 }
471
472 /// Verify - Verify that a composite type descriptor is well formed.
473 bool DICompositeType::Verify() const {
474   if (!isCompositeType())
475     return false;
476
477   // Make sure DerivedFrom @ field 9 and ContainingType @ field 12 are MDNodes.
478   if (!fieldIsMDNode(DbgNode, 9))
479     return false;
480   if (!fieldIsMDNode(DbgNode, 12))
481     return false;
482
483   return DbgNode->getNumOperands() >= 10 && DbgNode->getNumOperands() <= 14;
484 }
485
486 /// Verify - Verify that a subprogram descriptor is well formed.
487 bool DISubprogram::Verify() const {
488   if (!isSubprogram())
489     return false;
490
491   // Make sure context @ field 2 and type @ field 7 are MDNodes.
492   if (!fieldIsMDNode(DbgNode, 2))
493     return false;
494   if (!fieldIsMDNode(DbgNode, 7))
495     return false;
496   // Containing type @ field 12.
497   if (!fieldIsMDNode(DbgNode, 12))
498     return false;
499   return DbgNode->getNumOperands() == 20;
500 }
501
502 /// Verify - Verify that a global variable descriptor is well formed.
503 bool DIGlobalVariable::Verify() const {
504   if (!isGlobalVariable())
505     return false;
506
507   if (getDisplayName().empty())
508     return false;
509   // Make sure context @ field 2 and type @ field 8 are MDNodes.
510   if (!fieldIsMDNode(DbgNode, 2))
511     return false;
512   if (!fieldIsMDNode(DbgNode, 8))
513     return false;
514   // Make sure StaticDataMemberDeclaration @ field 12 is MDNode.
515   if (!fieldIsMDNode(DbgNode, 12))
516     return false;
517
518   return DbgNode->getNumOperands() == 13;
519 }
520
521 /// Verify - Verify that a variable descriptor is well formed.
522 bool DIVariable::Verify() const {
523   if (!isVariable())
524     return false;
525
526   // Make sure context @ field 1 and type @ field 5 are MDNodes.
527   if (!fieldIsMDNode(DbgNode, 1))
528     return false;
529   if (!fieldIsMDNode(DbgNode, 5))
530     return false;
531   return DbgNode->getNumOperands() >= 8;
532 }
533
534 /// Verify - Verify that a location descriptor is well formed.
535 bool DILocation::Verify() const {
536   if (!DbgNode)
537     return false;
538
539   return DbgNode->getNumOperands() == 4;
540 }
541
542 /// Verify - Verify that a namespace descriptor is well formed.
543 bool DINameSpace::Verify() const {
544   if (!isNameSpace())
545     return false;
546   return DbgNode->getNumOperands() == 5;
547 }
548
549 /// \brief Retrieve the MDNode for the directory/file pair.
550 MDNode *DIFile::getFileNode() const {
551   return getNodeField(DbgNode, 1);
552 }
553
554 /// \brief Verify that the file descriptor is well formed.
555 bool DIFile::Verify() const {
556   return isFile() && DbgNode->getNumOperands() == 2;
557 }
558
559 /// \brief Verify that the enumerator descriptor is well formed.
560 bool DIEnumerator::Verify() const {
561   return isEnumerator() && DbgNode->getNumOperands() == 3;
562 }
563
564 /// \brief Verify that the subrange descriptor is well formed.
565 bool DISubrange::Verify() const {
566   return isSubrange() && DbgNode->getNumOperands() == 3;
567 }
568
569 /// \brief Verify that the lexical block descriptor is well formed.
570 bool DILexicalBlock::Verify() const {
571   return isLexicalBlock() && DbgNode->getNumOperands() == 6;
572 }
573
574 /// \brief Verify that the file-scoped lexical block descriptor is well formed.
575 bool DILexicalBlockFile::Verify() const {
576   return isLexicalBlockFile() && DbgNode->getNumOperands() == 3;
577 }
578
579 /// \brief Verify that the template type parameter descriptor is well formed.
580 bool DITemplateTypeParameter::Verify() const {
581   return isTemplateTypeParameter() && DbgNode->getNumOperands() == 7;
582 }
583
584 /// \brief Verify that the template value parameter descriptor is well formed.
585 bool DITemplateValueParameter::Verify() const {
586   return isTemplateValueParameter() && DbgNode->getNumOperands() == 8;
587 }
588
589 /// \brief Verify that the imported module descriptor is well formed.
590 bool DIImportedEntity::Verify() const {
591   return isImportedEntity() &&
592          (DbgNode->getNumOperands() == 4 || DbgNode->getNumOperands() == 5);
593 }
594
595 /// getOriginalTypeSize - If this type is derived from a base type then
596 /// return base type size.
597 uint64_t DIDerivedType::getOriginalTypeSize() const {
598   unsigned Tag = getTag();
599
600   if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
601       Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
602       Tag != dwarf::DW_TAG_restrict_type)
603     return getSizeInBits();
604
605   DIType BaseType = getTypeDerivedFrom();
606
607   // If this type is not derived from any type then take conservative approach.
608   if (!BaseType.isValid())
609     return getSizeInBits();
610
611   // If this is a derived type, go ahead and get the base type, unless it's a
612   // reference then it's just the size of the field. Pointer types have no need
613   // of this since they're a different type of qualification on the type.
614   if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
615       BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
616     return getSizeInBits();
617
618   if (BaseType.isDerivedType())
619     return DIDerivedType(BaseType).getOriginalTypeSize();
620
621   return BaseType.getSizeInBits();
622 }
623
624 /// getObjCProperty - Return property node, if this ivar is associated with one.
625 MDNode *DIDerivedType::getObjCProperty() const {
626   return getNodeField(DbgNode, 10);
627 }
628
629 /// \brief Set the array of member DITypes.
630 void DICompositeType::setTypeArray(DIArray Elements, DIArray TParams) {
631   assert((!TParams || DbgNode->getNumOperands() == 14) &&
632          "If you're setting the template parameters this should include a slot "
633          "for that!");
634   TrackingVH<MDNode> N(*this);
635   N->replaceOperandWith(10, Elements);
636   if (TParams)
637     N->replaceOperandWith(13, TParams);
638   DbgNode = N;
639 }
640
641 /// \brief Set the containing type.
642 void DICompositeType::setContainingType(DICompositeType ContainingType) {
643   TrackingVH<MDNode> N(*this);
644   N->replaceOperandWith(12, ContainingType);
645   DbgNode = N;
646 }
647
648 /// isInlinedFnArgument - Return true if this variable provides debugging
649 /// information for an inlined function arguments.
650 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
651   assert(CurFn && "Invalid function");
652   if (!getContext().isSubprogram())
653     return false;
654   // This variable is not inlined function argument if its scope
655   // does not describe current function.
656   return !DISubprogram(getContext()).describes(CurFn);
657 }
658
659 /// describes - Return true if this subprogram provides debugging
660 /// information for the function F.
661 bool DISubprogram::describes(const Function *F) {
662   assert(F && "Invalid function");
663   if (F == getFunction())
664     return true;
665   StringRef Name = getLinkageName();
666   if (Name.empty())
667     Name = getName();
668   if (F->getName() == Name)
669     return true;
670   return false;
671 }
672
673 unsigned DISubprogram::isOptimized() const {
674   assert (DbgNode && "Invalid subprogram descriptor!");
675   if (DbgNode->getNumOperands() == 15)
676     return getUnsignedField(14);
677   return 0;
678 }
679
680 MDNode *DISubprogram::getVariablesNodes() const {
681   return getNodeField(DbgNode, 18);
682 }
683
684 DIArray DISubprogram::getVariables() const {
685   return DIArray(getNodeField(DbgNode, 18));
686 }
687
688 Value *DITemplateValueParameter::getValue() const {
689   return getField(DbgNode, 4);
690 }
691
692 StringRef DIScope::getFilename() const {
693   if (!DbgNode)
694     return StringRef();
695   return ::getStringField(getNodeField(DbgNode, 1), 0);
696 }
697
698 StringRef DIScope::getDirectory() const {
699   if (!DbgNode)
700     return StringRef();
701   return ::getStringField(getNodeField(DbgNode, 1), 1);
702 }
703
704 DIArray DICompileUnit::getEnumTypes() const {
705   if (!DbgNode || DbgNode->getNumOperands() < 13)
706     return DIArray();
707
708   return DIArray(getNodeField(DbgNode, 7));
709 }
710
711 DIArray DICompileUnit::getRetainedTypes() const {
712   if (!DbgNode || DbgNode->getNumOperands() < 13)
713     return DIArray();
714
715   return DIArray(getNodeField(DbgNode, 8));
716 }
717
718 DIArray DICompileUnit::getSubprograms() const {
719   if (!DbgNode || DbgNode->getNumOperands() < 13)
720     return DIArray();
721
722   return DIArray(getNodeField(DbgNode, 9));
723 }
724
725
726 DIArray DICompileUnit::getGlobalVariables() const {
727   if (!DbgNode || DbgNode->getNumOperands() < 13)
728     return DIArray();
729
730   return DIArray(getNodeField(DbgNode, 10));
731 }
732
733 DIArray DICompileUnit::getImportedEntities() const {
734   if (!DbgNode || DbgNode->getNumOperands() < 13)
735     return DIArray();
736
737   return DIArray(getNodeField(DbgNode, 11));
738 }
739
740 /// fixupSubprogramName - Replace contains special characters used
741 /// in a typical Objective-C names with '.' in a given string.
742 static void fixupSubprogramName(DISubprogram Fn, SmallVectorImpl<char> &Out) {
743   StringRef FName =
744       Fn.getFunction() ? Fn.getFunction()->getName() : Fn.getName();
745   FName = Function::getRealLinkageName(FName);
746
747   StringRef Prefix("llvm.dbg.lv.");
748   Out.reserve(FName.size() + Prefix.size());
749   Out.append(Prefix.begin(), Prefix.end());
750
751   bool isObjCLike = false;
752   for (size_t i = 0, e = FName.size(); i < e; ++i) {
753     char C = FName[i];
754     if (C == '[')
755       isObjCLike = true;
756
757     if (isObjCLike && (C == '[' || C == ']' || C == ' ' || C == ':' ||
758                        C == '+' || C == '(' || C == ')'))
759       Out.push_back('.');
760     else
761       Out.push_back(C);
762   }
763 }
764
765 /// getFnSpecificMDNode - Return a NameMDNode, if available, that is
766 /// suitable to hold function specific information.
767 NamedMDNode *llvm::getFnSpecificMDNode(const Module &M, DISubprogram Fn) {
768   SmallString<32> Name;
769   fixupSubprogramName(Fn, Name);
770   return M.getNamedMetadata(Name.str());
771 }
772
773 /// getOrInsertFnSpecificMDNode - Return a NameMDNode that is suitable
774 /// to hold function specific information.
775 NamedMDNode *llvm::getOrInsertFnSpecificMDNode(Module &M, DISubprogram Fn) {
776   SmallString<32> Name;
777   fixupSubprogramName(Fn, Name);
778   return M.getOrInsertNamedMetadata(Name.str());
779 }
780
781 /// createInlinedVariable - Create a new inlined variable based on current
782 /// variable.
783 /// @param DV            Current Variable.
784 /// @param InlinedScope  Location at current variable is inlined.
785 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
786                                        LLVMContext &VMContext) {
787   SmallVector<Value *, 16> Elts;
788   // Insert inlined scope as 7th element.
789   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
790     i == 7 ? Elts.push_back(InlinedScope) :
791              Elts.push_back(DV->getOperand(i));
792   return DIVariable(MDNode::get(VMContext, Elts));
793 }
794
795 /// cleanseInlinedVariable - Remove inlined scope from the variable.
796 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
797   SmallVector<Value *, 16> Elts;
798   // Insert inlined scope as 7th element.
799   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
800     i == 7 ?
801       Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext))):
802       Elts.push_back(DV->getOperand(i));
803   return DIVariable(MDNode::get(VMContext, Elts));
804 }
805
806 /// getDISubprogram - Find subprogram that is enclosing this scope.
807 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
808   DIDescriptor D(Scope);
809   if (D.isSubprogram())
810     return DISubprogram(Scope);
811
812   if (D.isLexicalBlockFile())
813     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
814
815   if (D.isLexicalBlock())
816     return getDISubprogram(DILexicalBlock(Scope).getContext());
817
818   return DISubprogram();
819 }
820
821 /// getDICompositeType - Find underlying composite type.
822 DICompositeType llvm::getDICompositeType(DIType T) {
823   if (T.isCompositeType())
824     return DICompositeType(T);
825
826   if (T.isDerivedType())
827     return getDICompositeType(DIDerivedType(T).getTypeDerivedFrom());
828
829   return DICompositeType();
830 }
831
832 /// isSubprogramContext - Return true if Context is either a subprogram
833 /// or another context nested inside a subprogram.
834 bool llvm::isSubprogramContext(const MDNode *Context) {
835   if (!Context)
836     return false;
837   DIDescriptor D(Context);
838   if (D.isSubprogram())
839     return true;
840   if (D.isType())
841     return isSubprogramContext(DIType(Context).getContext());
842   return false;
843 }
844
845 //===----------------------------------------------------------------------===//
846 // DebugInfoFinder implementations.
847 //===----------------------------------------------------------------------===//
848
849 void DebugInfoFinder::reset() {
850   CUs.clear();
851   SPs.clear();
852   GVs.clear();
853   TYs.clear();
854   Scopes.clear();
855   NodesSeen.clear();
856 }
857
858 /// processModule - Process entire module and collect debug info.
859 void DebugInfoFinder::processModule(const Module &M) {
860   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
861     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
862       DICompileUnit CU(CU_Nodes->getOperand(i));
863       addCompileUnit(CU);
864       DIArray GVs = CU.getGlobalVariables();
865       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
866         DIGlobalVariable DIG(GVs.getElement(i));
867         if (addGlobalVariable(DIG)) {
868           processScope(DIG.getContext());
869           processType(DIG.getType());
870         }
871       }
872       DIArray SPs = CU.getSubprograms();
873       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
874         processSubprogram(DISubprogram(SPs.getElement(i)));
875       DIArray EnumTypes = CU.getEnumTypes();
876       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
877         processType(DIType(EnumTypes.getElement(i)));
878       DIArray RetainedTypes = CU.getRetainedTypes();
879       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
880         processType(DIType(RetainedTypes.getElement(i)));
881       // FIXME: We really shouldn't be bailing out after visiting just one CU
882       return;
883     }
884   }
885 }
886
887 /// processLocation - Process DILocation.
888 void DebugInfoFinder::processLocation(DILocation Loc) {
889   if (!Loc.Verify()) return;
890   DIDescriptor S(Loc.getScope());
891   if (S.isCompileUnit())
892     addCompileUnit(DICompileUnit(S));
893   else if (S.isSubprogram())
894     processSubprogram(DISubprogram(S));
895   else if (S.isLexicalBlock())
896     processLexicalBlock(DILexicalBlock(S));
897   else if (S.isLexicalBlockFile()) {
898     DILexicalBlockFile DBF = DILexicalBlockFile(S);
899     processLexicalBlock(DILexicalBlock(DBF.getScope()));
900   }
901   processLocation(Loc.getOrigLocation());
902 }
903
904 /// processType - Process DIType.
905 void DebugInfoFinder::processType(DIType DT) {
906   if (!addType(DT))
907     return;
908   processScope(DT.getContext());
909   if (DT.isCompositeType()) {
910     DICompositeType DCT(DT);
911     processType(DCT.getTypeDerivedFrom());
912     DIArray DA = DCT.getTypeArray();
913     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
914       DIDescriptor D = DA.getElement(i);
915       if (D.isType())
916         processType(DIType(D));
917       else if (D.isSubprogram())
918         processSubprogram(DISubprogram(D));
919     }
920   } else if (DT.isDerivedType()) {
921     DIDerivedType DDT(DT);
922     processType(DDT.getTypeDerivedFrom());
923   }
924 }
925
926 void DebugInfoFinder::processScope(DIScope Scope) {
927   if (Scope.isType()) {
928     DIType Ty(Scope);
929     processType(Ty);
930     return;
931   }
932   if (Scope.isCompileUnit()) {
933     addCompileUnit(DICompileUnit(Scope));
934     return;
935   }
936   if (Scope.isSubprogram()) {
937     processSubprogram(DISubprogram(Scope));
938     return;
939   }
940   if (!addScope(Scope))
941     return;
942   if (Scope.isLexicalBlock()) {
943     DILexicalBlock LB(Scope);
944     processScope(LB.getContext());
945   } else if (Scope.isLexicalBlockFile()) {
946     DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
947     processScope(LBF.getScope());
948   } else if (Scope.isNameSpace()) {
949     DINameSpace NS(Scope);
950     processScope(NS.getContext());
951   }
952 }
953
954 /// processLexicalBlock
955 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
956   DIScope Context = LB.getContext();
957   if (Context.isLexicalBlock())
958     return processLexicalBlock(DILexicalBlock(Context));
959   else if (Context.isLexicalBlockFile()) {
960     DILexicalBlockFile DBF = DILexicalBlockFile(Context);
961     return processLexicalBlock(DILexicalBlock(DBF.getScope()));
962   }
963   else
964     return processSubprogram(DISubprogram(Context));
965 }
966
967 /// processSubprogram - Process DISubprogram.
968 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
969   if (!addSubprogram(SP))
970     return;
971   processScope(SP.getContext());
972   processType(SP.getType());
973 }
974
975 /// processDeclare - Process DbgDeclareInst.
976 void DebugInfoFinder::processDeclare(const DbgDeclareInst *DDI) {
977   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
978   if (!N) return;
979
980   DIDescriptor DV(N);
981   if (!DV.isVariable())
982     return;
983
984   if (!NodesSeen.insert(DV))
985     return;
986   processScope(DIVariable(N).getContext());
987   processType(DIVariable(N).getType());
988 }
989
990 void DebugInfoFinder::processValue(const DbgValueInst *DVI) {
991   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
992   if (!N) return;
993
994   DIDescriptor DV(N);
995   if (!DV.isVariable())
996     return;
997
998   if (!NodesSeen.insert(DV))
999     return;
1000   processScope(DIVariable(N).getContext());
1001   processType(DIVariable(N).getType());
1002 }
1003
1004 /// addType - Add type into Tys.
1005 bool DebugInfoFinder::addType(DIType DT) {
1006   if (!DT.isValid())
1007     return false;
1008
1009   if (!NodesSeen.insert(DT))
1010     return false;
1011
1012   TYs.push_back(DT);
1013   return true;
1014 }
1015
1016 /// addCompileUnit - Add compile unit into CUs.
1017 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1018   if (!CU.Verify())
1019     return false;
1020
1021   if (!NodesSeen.insert(CU))
1022     return false;
1023
1024   CUs.push_back(CU);
1025   return true;
1026 }
1027
1028 /// addGlobalVariable - Add global variable into GVs.
1029 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1030   if (!DIDescriptor(DIG).isGlobalVariable())
1031     return false;
1032
1033   if (!NodesSeen.insert(DIG))
1034     return false;
1035
1036   GVs.push_back(DIG);
1037   return true;
1038 }
1039
1040 // addSubprogram - Add subprgoram into SPs.
1041 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1042   if (!DIDescriptor(SP).isSubprogram())
1043     return false;
1044
1045   if (!NodesSeen.insert(SP))
1046     return false;
1047
1048   SPs.push_back(SP);
1049   return true;
1050 }
1051
1052 bool DebugInfoFinder::addScope(DIScope Scope) {
1053   if (!Scope)
1054     return false;
1055   if (!NodesSeen.insert(Scope))
1056     return false;
1057   Scopes.push_back(Scope);
1058   return true;
1059 }
1060
1061 //===----------------------------------------------------------------------===//
1062 // DIDescriptor: dump routines for all descriptors.
1063 //===----------------------------------------------------------------------===//
1064
1065 /// dump - Print descriptor to dbgs() with a newline.
1066 void DIDescriptor::dump() const {
1067   print(dbgs()); dbgs() << '\n';
1068 }
1069
1070 /// print - Print descriptor.
1071 void DIDescriptor::print(raw_ostream &OS) const {
1072   if (!DbgNode) return;
1073
1074   if (const char *Tag = dwarf::TagString(getTag()))
1075     OS << "[ " << Tag << " ]";
1076
1077   if (this->isSubrange()) {
1078     DISubrange(DbgNode).printInternal(OS);
1079   } else if (this->isCompileUnit()) {
1080     DICompileUnit(DbgNode).printInternal(OS);
1081   } else if (this->isFile()) {
1082     DIFile(DbgNode).printInternal(OS);
1083   } else if (this->isEnumerator()) {
1084     DIEnumerator(DbgNode).printInternal(OS);
1085   } else if (this->isBasicType()) {
1086     DIType(DbgNode).printInternal(OS);
1087   } else if (this->isDerivedType()) {
1088     DIDerivedType(DbgNode).printInternal(OS);
1089   } else if (this->isCompositeType()) {
1090     DICompositeType(DbgNode).printInternal(OS);
1091   } else if (this->isSubprogram()) {
1092     DISubprogram(DbgNode).printInternal(OS);
1093   } else if (this->isGlobalVariable()) {
1094     DIGlobalVariable(DbgNode).printInternal(OS);
1095   } else if (this->isVariable()) {
1096     DIVariable(DbgNode).printInternal(OS);
1097   } else if (this->isObjCProperty()) {
1098     DIObjCProperty(DbgNode).printInternal(OS);
1099   } else if (this->isNameSpace()) {
1100     DINameSpace(DbgNode).printInternal(OS);
1101   } else if (this->isScope()) {
1102     DIScope(DbgNode).printInternal(OS);
1103   }
1104 }
1105
1106 void DISubrange::printInternal(raw_ostream &OS) const {
1107   int64_t Count = getCount();
1108   if (Count != -1)
1109     OS << " [" << getLo() << ", " << Count - 1 << ']';
1110   else
1111     OS << " [unbounded]";
1112 }
1113
1114 void DIScope::printInternal(raw_ostream &OS) const {
1115   OS << " [" << getDirectory() << "/" << getFilename() << ']';
1116 }
1117
1118 void DICompileUnit::printInternal(raw_ostream &OS) const {
1119   DIScope::printInternal(OS);
1120   OS << " [";
1121   unsigned Lang = getLanguage();
1122   if (const char *LangStr = dwarf::LanguageString(Lang))
1123     OS << LangStr;
1124   else
1125     (OS << "lang 0x").write_hex(Lang);
1126   OS << ']';
1127 }
1128
1129 void DIEnumerator::printInternal(raw_ostream &OS) const {
1130   OS << " [" << getName() << " :: " << getEnumValue() << ']';
1131 }
1132
1133 void DIType::printInternal(raw_ostream &OS) const {
1134   if (!DbgNode) return;
1135
1136   StringRef Res = getName();
1137   if (!Res.empty())
1138     OS << " [" << Res << "]";
1139
1140   // TODO: Print context?
1141
1142   OS << " [line " << getLineNumber()
1143      << ", size " << getSizeInBits()
1144      << ", align " << getAlignInBits()
1145      << ", offset " << getOffsetInBits();
1146   if (isBasicType())
1147     if (const char *Enc =
1148         dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
1149       OS << ", enc " << Enc;
1150   OS << "]";
1151
1152   if (isPrivate())
1153     OS << " [private]";
1154   else if (isProtected())
1155     OS << " [protected]";
1156
1157   if (isArtificial())
1158     OS << " [artificial]";
1159
1160   if (isForwardDecl())
1161     OS << " [decl]";
1162   else if (getTag() == dwarf::DW_TAG_structure_type ||
1163            getTag() == dwarf::DW_TAG_union_type ||
1164            getTag() == dwarf::DW_TAG_enumeration_type ||
1165            getTag() == dwarf::DW_TAG_class_type)
1166     OS << " [def]";
1167   if (isVector())
1168     OS << " [vector]";
1169   if (isStaticMember())
1170     OS << " [static]";
1171 }
1172
1173 void DIDerivedType::printInternal(raw_ostream &OS) const {
1174   DIType::printInternal(OS);
1175   OS << " [from " << getTypeDerivedFrom().getName() << ']';
1176 }
1177
1178 void DICompositeType::printInternal(raw_ostream &OS) const {
1179   DIType::printInternal(OS);
1180   DIArray A = getTypeArray();
1181   OS << " [" << A.getNumElements() << " elements]";
1182 }
1183
1184 void DINameSpace::printInternal(raw_ostream &OS) const {
1185   StringRef Name = getName();
1186   if (!Name.empty())
1187     OS << " [" << Name << ']';
1188
1189   OS << " [line " << getLineNumber() << ']';
1190 }
1191
1192 void DISubprogram::printInternal(raw_ostream &OS) const {
1193   // TODO : Print context
1194   OS << " [line " << getLineNumber() << ']';
1195
1196   if (isLocalToUnit())
1197     OS << " [local]";
1198
1199   if (isDefinition())
1200     OS << " [def]";
1201
1202   if (getScopeLineNumber() != getLineNumber())
1203     OS << " [scope " << getScopeLineNumber() << "]";
1204
1205   if (isPrivate())
1206     OS << " [private]";
1207   else if (isProtected())
1208     OS << " [protected]";
1209
1210   StringRef Res = getName();
1211   if (!Res.empty())
1212     OS << " [" << Res << ']';
1213 }
1214
1215 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
1216   StringRef Res = getName();
1217   if (!Res.empty())
1218     OS << " [" << Res << ']';
1219
1220   OS << " [line " << getLineNumber() << ']';
1221
1222   // TODO : Print context
1223
1224   if (isLocalToUnit())
1225     OS << " [local]";
1226
1227   if (isDefinition())
1228     OS << " [def]";
1229 }
1230
1231 void DIVariable::printInternal(raw_ostream &OS) const {
1232   StringRef Res = getName();
1233   if (!Res.empty())
1234     OS << " [" << Res << ']';
1235
1236   OS << " [line " << getLineNumber() << ']';
1237 }
1238
1239 void DIObjCProperty::printInternal(raw_ostream &OS) const {
1240   StringRef Name = getObjCPropertyName();
1241   if (!Name.empty())
1242     OS << " [" << Name << ']';
1243
1244   OS << " [line " << getLineNumber()
1245      << ", properties " << getUnsignedField(6) << ']';
1246 }
1247
1248 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
1249                           const LLVMContext &Ctx) {
1250   if (!DL.isUnknown()) {          // Print source line info.
1251     DIScope Scope(DL.getScope(Ctx));
1252     assert(Scope.isScope() &&
1253       "Scope of a DebugLoc should be a DIScope.");
1254     // Omit the directory, because it's likely to be long and uninteresting.
1255     CommentOS << Scope.getFilename();
1256     CommentOS << ':' << DL.getLine();
1257     if (DL.getCol() != 0)
1258       CommentOS << ':' << DL.getCol();
1259     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1260     if (!InlinedAtDL.isUnknown()) {
1261       CommentOS << " @[ ";
1262       printDebugLoc(InlinedAtDL, CommentOS, Ctx);
1263       CommentOS << " ]";
1264     }
1265   }
1266 }
1267
1268 void DIVariable::printExtendedName(raw_ostream &OS) const {
1269   const LLVMContext &Ctx = DbgNode->getContext();
1270   StringRef Res = getName();
1271   if (!Res.empty())
1272     OS << Res << "," << getLineNumber();
1273   if (MDNode *InlinedAt = getInlinedAt()) {
1274     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1275     if (!InlinedAtDL.isUnknown()) {
1276       OS << " @[";
1277       printDebugLoc(InlinedAtDL, OS, Ctx);
1278       OS << "]";
1279     }
1280   }
1281 }