Fix typo.
[oota-llvm.git] / lib / Analysis / 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/Analysis/DebugInfo.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/raw_ostream.h"
29 using namespace llvm;
30 using namespace llvm::dwarf;
31
32 //===----------------------------------------------------------------------===//
33 // DIDescriptor
34 //===----------------------------------------------------------------------===//
35
36 DIDescriptor::DIDescriptor(const DIFile F) : DbgNode(F.DbgNode) {
37 }
38
39 DIDescriptor::DIDescriptor(const DISubprogram F) : DbgNode(F.DbgNode) {
40 }
41
42 DIDescriptor::DIDescriptor(const DILexicalBlock F) : DbgNode(F.DbgNode) {
43 }
44
45 DIDescriptor::DIDescriptor(const DIVariable F) : DbgNode(F.DbgNode) {
46 }
47
48 DIDescriptor::DIDescriptor(const DIType F) : DbgNode(F.DbgNode) {
49 }
50
51 StringRef
52 DIDescriptor::getStringField(unsigned Elt) const {
53   if (DbgNode == 0)
54     return StringRef();
55
56   if (Elt < DbgNode->getNumOperands())
57     if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getOperand(Elt)))
58       return MDS->getString();
59
60   return StringRef();
61 }
62
63 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
64   if (DbgNode == 0)
65     return 0;
66
67   if (Elt < DbgNode->getNumOperands())
68     if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getOperand(Elt)))
69       return CI->getZExtValue();
70
71   return 0;
72 }
73
74 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
75   if (DbgNode == 0)
76     return DIDescriptor();
77
78   if (Elt < DbgNode->getNumOperands())
79     return
80       DIDescriptor(dyn_cast_or_null<const MDNode>(DbgNode->getOperand(Elt)));
81   return DIDescriptor();
82 }
83
84 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
85   if (DbgNode == 0)
86     return 0;
87
88   if (Elt < DbgNode->getNumOperands())
89       return dyn_cast_or_null<GlobalVariable>(DbgNode->getOperand(Elt));
90   return 0;
91 }
92
93 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
94   if (DbgNode == 0)
95     return 0;
96
97   if (Elt < DbgNode->getNumOperands())
98       return dyn_cast_or_null<Constant>(DbgNode->getOperand(Elt));
99   return 0;
100 }
101
102 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
103   if (DbgNode == 0)
104     return 0;
105
106   if (Elt < DbgNode->getNumOperands())
107       return dyn_cast_or_null<Function>(DbgNode->getOperand(Elt));
108   return 0;
109 }
110
111 unsigned DIVariable::getNumAddrElements() const {
112   if (getVersion() <= llvm::LLVMDebugVersion8)
113     return DbgNode->getNumOperands()-6;
114   if (getVersion() == llvm::LLVMDebugVersion9)
115     return DbgNode->getNumOperands()-7;
116   return DbgNode->getNumOperands()-8;
117 }
118
119 /// getInlinedAt - If this variable is inlined then return inline location.
120 MDNode *DIVariable::getInlinedAt() const {
121   if (getVersion() <= llvm::LLVMDebugVersion9)
122     return NULL;
123   return dyn_cast_or_null<MDNode>(DbgNode->getOperand(7));
124 }
125
126 //===----------------------------------------------------------------------===//
127 // Predicates
128 //===----------------------------------------------------------------------===//
129
130 /// isBasicType - Return true if the specified tag is legal for
131 /// DIBasicType.
132 bool DIDescriptor::isBasicType() const {
133   return DbgNode && getTag() == dwarf::DW_TAG_base_type;
134 }
135
136 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
137 bool DIDescriptor::isDerivedType() const {
138   if (!DbgNode) return false;
139   switch (getTag()) {
140   case dwarf::DW_TAG_typedef:
141   case dwarf::DW_TAG_pointer_type:
142   case dwarf::DW_TAG_reference_type:
143   case dwarf::DW_TAG_const_type:
144   case dwarf::DW_TAG_volatile_type:
145   case dwarf::DW_TAG_restrict_type:
146   case dwarf::DW_TAG_member:
147   case dwarf::DW_TAG_inheritance:
148   case dwarf::DW_TAG_friend:
149     return true;
150   default:
151     // CompositeTypes are currently modelled as DerivedTypes.
152     return isCompositeType();
153   }
154 }
155
156 /// isCompositeType - Return true if the specified tag is legal for
157 /// DICompositeType.
158 bool DIDescriptor::isCompositeType() const {
159   if (!DbgNode) return false;
160   switch (getTag()) {
161   case dwarf::DW_TAG_array_type:
162   case dwarf::DW_TAG_structure_type:
163   case dwarf::DW_TAG_union_type:
164   case dwarf::DW_TAG_enumeration_type:
165   case dwarf::DW_TAG_vector_type:
166   case dwarf::DW_TAG_subroutine_type:
167   case dwarf::DW_TAG_class_type:
168     return true;
169   default:
170     return false;
171   }
172 }
173
174 /// isVariable - Return true if the specified tag is legal for DIVariable.
175 bool DIDescriptor::isVariable() const {
176   if (!DbgNode) return false;
177   switch (getTag()) {
178   case dwarf::DW_TAG_auto_variable:
179   case dwarf::DW_TAG_arg_variable:
180   case dwarf::DW_TAG_return_variable:
181     return true;
182   default:
183     return false;
184   }
185 }
186
187 /// isType - Return true if the specified tag is legal for DIType.
188 bool DIDescriptor::isType() const {
189   return isBasicType() || isCompositeType() || isDerivedType();
190 }
191
192 /// isSubprogram - Return true if the specified tag is legal for
193 /// DISubprogram.
194 bool DIDescriptor::isSubprogram() const {
195   return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
196 }
197
198 /// isGlobalVariable - Return true if the specified tag is legal for
199 /// DIGlobalVariable.
200 bool DIDescriptor::isGlobalVariable() const {
201   return DbgNode && (getTag() == dwarf::DW_TAG_variable ||
202                      getTag() == dwarf::DW_TAG_constant);
203 }
204
205 /// isGlobal - Return true if the specified tag is legal for DIGlobal.
206 bool DIDescriptor::isGlobal() const {
207   return isGlobalVariable();
208 }
209
210 /// isUnspecifiedParmeter - Return true if the specified tag is
211 /// DW_TAG_unspecified_parameters.
212 bool DIDescriptor::isUnspecifiedParameter() const {
213   return DbgNode && getTag() == dwarf::DW_TAG_unspecified_parameters;
214 }
215
216 /// isScope - Return true if the specified tag is one of the scope
217 /// related tag.
218 bool DIDescriptor::isScope() const {
219   if (!DbgNode) return false;
220   switch (getTag()) {
221   case dwarf::DW_TAG_compile_unit:
222   case dwarf::DW_TAG_lexical_block:
223   case dwarf::DW_TAG_subprogram:
224   case dwarf::DW_TAG_namespace:
225     return true;
226   default:
227     break;
228   }
229   return false;
230 }
231
232 /// isTemplateTypeParameter - Return true if the specified tag is
233 /// DW_TAG_template_type_parameter.
234 bool DIDescriptor::isTemplateTypeParameter() const {
235   return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter;
236 }
237
238 /// isTemplateValueParameter - Return true if the specified tag is
239 /// DW_TAG_template_value_parameter.
240 bool DIDescriptor::isTemplateValueParameter() const {
241   return DbgNode && getTag() == dwarf::DW_TAG_template_value_parameter;
242 }
243
244 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
245 bool DIDescriptor::isCompileUnit() const {
246   return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
247 }
248
249 /// isFile - Return true if the specified tag is DW_TAG_file_type.
250 bool DIDescriptor::isFile() const {
251   return DbgNode && getTag() == dwarf::DW_TAG_file_type;
252 }
253
254 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
255 bool DIDescriptor::isNameSpace() const {
256   return DbgNode && getTag() == dwarf::DW_TAG_namespace;
257 }
258
259 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
260 bool DIDescriptor::isLexicalBlock() const {
261   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block;
262 }
263
264 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
265 bool DIDescriptor::isSubrange() const {
266   return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
267 }
268
269 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
270 bool DIDescriptor::isEnumerator() const {
271   return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
272 }
273
274 //===----------------------------------------------------------------------===//
275 // Simple Descriptor Constructors and other Methods
276 //===----------------------------------------------------------------------===//
277
278 DIType::DIType(const MDNode *N) : DIScope(N) {
279   if (!N) return;
280   if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
281     DbgNode = 0;
282   }
283 }
284
285 unsigned DIArray::getNumElements() const {
286   if (!DbgNode)
287     return 0;
288   return DbgNode->getNumOperands();
289 }
290
291 /// replaceAllUsesWith - Replace all uses of debug info referenced by
292 /// this descriptor.
293 void DIType::replaceAllUsesWith(DIDescriptor &D) {
294   if (!DbgNode)
295     return;
296
297   // Since we use a TrackingVH for the node, its easy for clients to manufacture
298   // legitimate situations where they want to replaceAllUsesWith() on something
299   // which, due to uniquing, has merged with the source. We shield clients from
300   // this detail by allowing a value to be replaced with replaceAllUsesWith()
301   // itself.
302   if (DbgNode != D) {
303     MDNode *Node = const_cast<MDNode*>(DbgNode);
304     const MDNode *DN = D;
305     const Value *V = cast_or_null<Value>(DN);
306     Node->replaceAllUsesWith(const_cast<Value*>(V));
307     MDNode::deleteTemporary(Node);
308   }
309 }
310
311 /// replaceAllUsesWith - Replace all uses of debug info referenced by
312 /// this descriptor.
313 void DIType::replaceAllUsesWith(MDNode *D) {
314   if (!DbgNode)
315     return;
316
317   // Since we use a TrackingVH for the node, its easy for clients to manufacture
318   // legitimate situations where they want to replaceAllUsesWith() on something
319   // which, due to uniquing, has merged with the source. We shield clients from
320   // this detail by allowing a value to be replaced with replaceAllUsesWith()
321   // itself.
322   if (DbgNode != D) {
323     MDNode *Node = const_cast<MDNode*>(DbgNode);
324     const MDNode *DN = D;
325     const Value *V = cast_or_null<Value>(DN);
326     Node->replaceAllUsesWith(const_cast<Value*>(V));
327     MDNode::deleteTemporary(Node);
328   }
329 }
330
331 /// isUnsignedDIType - Return true if type encoding is unsigned.
332 bool DIType::isUnsignedDIType() {
333   DIDerivedType DTy(DbgNode);
334   if (DTy.Verify())
335     return DTy.getTypeDerivedFrom().isUnsignedDIType();
336
337   DIBasicType BTy(DbgNode);
338   if (BTy.Verify()) {
339     unsigned Encoding = BTy.getEncoding();
340     if (Encoding == dwarf::DW_ATE_unsigned ||
341         Encoding == dwarf::DW_ATE_unsigned_char)
342       return true;
343   }
344   return false;
345 }
346
347 /// Verify - Verify that a compile unit is well formed.
348 bool DICompileUnit::Verify() const {
349   if (!DbgNode)
350     return false;
351   StringRef N = getFilename();
352   if (N.empty())
353     return false;
354   // It is possible that directory and produce string is empty.
355   return true;
356 }
357
358 /// Verify - Verify that a type descriptor is well formed.
359 bool DIType::Verify() const {
360   if (!DbgNode)
361     return false;
362   if (getContext() && !getContext().Verify())
363     return false;
364   unsigned Tag = getTag();
365   if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
366       Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
367       Tag != dwarf::DW_TAG_reference_type && Tag != dwarf::DW_TAG_restrict_type 
368       && Tag != dwarf::DW_TAG_vector_type && Tag != dwarf::DW_TAG_array_type
369       && Tag != dwarf::DW_TAG_enumeration_type 
370       && Tag != dwarf::DW_TAG_subroutine_type
371       && getFilename().empty())
372     return false;
373   return true;
374 }
375
376 /// Verify - Verify that a basic type descriptor is well formed.
377 bool DIBasicType::Verify() const {
378   return isBasicType();
379 }
380
381 /// Verify - Verify that a derived type descriptor is well formed.
382 bool DIDerivedType::Verify() const {
383   return isDerivedType();
384 }
385
386 /// Verify - Verify that a composite type descriptor is well formed.
387 bool DICompositeType::Verify() const {
388   if (!DbgNode)
389     return false;
390   if (getContext() && !getContext().Verify())
391     return false;
392
393   return true;
394 }
395
396 /// Verify - Verify that a subprogram descriptor is well formed.
397 bool DISubprogram::Verify() const {
398   if (!DbgNode)
399     return false;
400
401   if (getContext() && !getContext().Verify())
402     return false;
403
404   DICompositeType Ty = getType();
405   if (!Ty.Verify())
406     return false;
407   return true;
408 }
409
410 /// Verify - Verify that a global variable descriptor is well formed.
411 bool DIGlobalVariable::Verify() const {
412   if (!DbgNode)
413     return false;
414
415   if (getDisplayName().empty())
416     return false;
417
418   if (getContext() && !getContext().Verify())
419     return false;
420
421   DIType Ty = getType();
422   if (!Ty.Verify())
423     return false;
424
425   if (!getGlobal() && !getConstant())
426     return false;
427
428   return true;
429 }
430
431 /// Verify - Verify that a variable descriptor is well formed.
432 bool DIVariable::Verify() const {
433   if (!DbgNode)
434     return false;
435
436   if (getContext() && !getContext().Verify())
437     return false;
438
439   DIType Ty = getType();
440   if (!Ty.Verify())
441     return false;
442
443   return true;
444 }
445
446 /// Verify - Verify that a location descriptor is well formed.
447 bool DILocation::Verify() const {
448   if (!DbgNode)
449     return false;
450
451   return DbgNode->getNumOperands() == 4;
452 }
453
454 /// Verify - Verify that a namespace descriptor is well formed.
455 bool DINameSpace::Verify() const {
456   if (!DbgNode)
457     return false;
458   if (getName().empty())
459     return false;
460   return true;
461 }
462
463 /// getOriginalTypeSize - If this type is derived from a base type then
464 /// return base type size.
465 uint64_t DIDerivedType::getOriginalTypeSize() const {
466   unsigned Tag = getTag();
467   if (Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef ||
468       Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
469       Tag == dwarf::DW_TAG_restrict_type) {
470     DIType BaseType = getTypeDerivedFrom();
471     // If this type is not derived from any type then take conservative
472     // approach.
473     if (!BaseType.isValid())
474       return getSizeInBits();
475     if (BaseType.isDerivedType())
476       return DIDerivedType(BaseType).getOriginalTypeSize();
477     else
478       return BaseType.getSizeInBits();
479   }
480
481   return getSizeInBits();
482 }
483
484 /// isInlinedFnArgument - Return true if this variable provides debugging
485 /// information for an inlined function arguments.
486 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
487   assert(CurFn && "Invalid function");
488   if (!getContext().isSubprogram())
489     return false;
490   // This variable is not inlined function argument if its scope
491   // does not describe current function.
492   return !(DISubprogram(getContext()).describes(CurFn));
493 }
494
495 /// describes - Return true if this subprogram provides debugging
496 /// information for the function F.
497 bool DISubprogram::describes(const Function *F) {
498   assert(F && "Invalid function");
499   if (F == getFunction())
500     return true;
501   StringRef Name = getLinkageName();
502   if (Name.empty())
503     Name = getName();
504   if (F->getName() == Name)
505     return true;
506   return false;
507 }
508
509 unsigned DISubprogram::isOptimized() const {
510   assert (DbgNode && "Invalid subprogram descriptor!");
511   if (DbgNode->getNumOperands() == 16)
512     return getUnsignedField(15);
513   return 0;
514 }
515
516 MDNode *DISubprogram::getVariablesNodes() const {
517   if (!DbgNode || DbgNode->getNumOperands() <= 19)
518     return NULL;
519   if (MDNode *Temp = dyn_cast_or_null<MDNode>(DbgNode->getOperand(19)))
520     return dyn_cast_or_null<MDNode>(Temp->getOperand(0));
521   return NULL;
522 }
523
524 DIArray DISubprogram::getVariables() const {
525   if (!DbgNode || DbgNode->getNumOperands() <= 19)
526     return DIArray();
527   if (MDNode *T = dyn_cast_or_null<MDNode>(DbgNode->getOperand(19)))
528     if (MDNode *A = dyn_cast_or_null<MDNode>(T->getOperand(0)))
529       return DIArray(A);
530   return DIArray();
531 }
532
533 StringRef DIScope::getFilename() const {
534   if (!DbgNode)
535     return StringRef();
536   if (isLexicalBlock())
537     return DILexicalBlock(DbgNode).getFilename();
538   if (isSubprogram())
539     return DISubprogram(DbgNode).getFilename();
540   if (isCompileUnit())
541     return DICompileUnit(DbgNode).getFilename();
542   if (isNameSpace())
543     return DINameSpace(DbgNode).getFilename();
544   if (isType())
545     return DIType(DbgNode).getFilename();
546   if (isFile())
547     return DIFile(DbgNode).getFilename();
548   assert(0 && "Invalid DIScope!");
549   return StringRef();
550 }
551
552 StringRef DIScope::getDirectory() const {
553   if (!DbgNode)
554     return StringRef();
555   if (isLexicalBlock())
556     return DILexicalBlock(DbgNode).getDirectory();
557   if (isSubprogram())
558     return DISubprogram(DbgNode).getDirectory();
559   if (isCompileUnit())
560     return DICompileUnit(DbgNode).getDirectory();
561   if (isNameSpace())
562     return DINameSpace(DbgNode).getDirectory();
563   if (isType())
564     return DIType(DbgNode).getDirectory();
565   if (isFile())
566     return DIFile(DbgNode).getDirectory();
567   assert(0 && "Invalid DIScope!");
568   return StringRef();
569 }
570
571 DIArray DICompileUnit::getEnumTypes() const {
572   if (!DbgNode || DbgNode->getNumOperands() < 14)
573     return DIArray();
574
575   if (MDNode *N = dyn_cast_or_null<MDNode>(DbgNode->getOperand(10)))
576     if (MDNode *A = dyn_cast_or_null<MDNode>(N->getOperand(0)))
577       return DIArray(A);
578   return DIArray();
579 }
580
581 DIArray DICompileUnit::getRetainedTypes() const {
582   if (!DbgNode || DbgNode->getNumOperands() < 14)
583     return DIArray();
584
585   if (MDNode *N = dyn_cast_or_null<MDNode>(DbgNode->getOperand(11)))
586     if (MDNode *A = dyn_cast_or_null<MDNode>(N->getOperand(0)))
587       return DIArray(A);
588   return DIArray();
589 }
590
591 DIArray DICompileUnit::getSubprograms() const {
592   if (!DbgNode || DbgNode->getNumOperands() < 14)
593     return DIArray();
594
595   if (MDNode *N = dyn_cast_or_null<MDNode>(DbgNode->getOperand(12)))
596     if (MDNode *A = dyn_cast_or_null<MDNode>(N->getOperand(0)))
597       return DIArray(A);
598   return DIArray();
599 }
600
601
602 DIArray DICompileUnit::getGlobalVariables() const {
603   if (!DbgNode || DbgNode->getNumOperands() < 14)
604     return DIArray();
605
606   if (MDNode *N = dyn_cast_or_null<MDNode>(DbgNode->getOperand(13)))
607     if (MDNode *A = dyn_cast_or_null<MDNode>(N->getOperand(0)))
608       return DIArray(A);
609   return DIArray();
610 }
611
612 //===----------------------------------------------------------------------===//
613 // DIDescriptor: dump routines for all descriptors.
614 //===----------------------------------------------------------------------===//
615
616
617 /// print - Print descriptor.
618 void DIDescriptor::print(raw_ostream &OS) const {
619   OS << "[" << dwarf::TagString(getTag()) << "] ";
620   OS.write_hex((intptr_t) &*DbgNode) << ']';
621 }
622
623 /// print - Print compile unit.
624 void DICompileUnit::print(raw_ostream &OS) const {
625   if (getLanguage())
626     OS << " [" << dwarf::LanguageString(getLanguage()) << "] ";
627
628   OS << " [" << getDirectory() << "/" << getFilename() << "]";
629 }
630
631 /// print - Print type.
632 void DIType::print(raw_ostream &OS) const {
633   if (!DbgNode) return;
634
635   StringRef Res = getName();
636   if (!Res.empty())
637     OS << " [" << Res << "] ";
638
639   unsigned Tag = getTag();
640   OS << " [" << dwarf::TagString(Tag) << "] ";
641
642   // TODO : Print context
643   OS << " ["
644          << "line " << getLineNumber() << ", "
645          << getSizeInBits() << " bits, "
646          << getAlignInBits() << " bit alignment, "
647          << getOffsetInBits() << " bit offset"
648          << "] ";
649
650   if (isPrivate())
651     OS << " [private] ";
652   else if (isProtected())
653     OS << " [protected] ";
654
655   if (isForwardDecl())
656     OS << " [fwd] ";
657
658   if (isBasicType())
659     DIBasicType(DbgNode).print(OS);
660   else if (isDerivedType())
661     DIDerivedType(DbgNode).print(OS);
662   else if (isCompositeType())
663     DICompositeType(DbgNode).print(OS);
664   else {
665     OS << "Invalid DIType\n";
666     return;
667   }
668
669   OS << "\n";
670 }
671
672 /// print - Print basic type.
673 void DIBasicType::print(raw_ostream &OS) const {
674   OS << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
675 }
676
677 /// print - Print derived type.
678 void DIDerivedType::print(raw_ostream &OS) const {
679   OS << "\n\t Derived From: "; getTypeDerivedFrom().print(OS);
680 }
681
682 /// print - Print composite type.
683 void DICompositeType::print(raw_ostream &OS) const {
684   DIArray A = getTypeArray();
685   OS << " [" << A.getNumElements() << " elements]";
686 }
687
688 /// print - Print subprogram.
689 void DISubprogram::print(raw_ostream &OS) const {
690   StringRef Res = getName();
691   if (!Res.empty())
692     OS << " [" << Res << "] ";
693
694   unsigned Tag = getTag();
695   OS << " [" << dwarf::TagString(Tag) << "] ";
696
697   // TODO : Print context
698   OS << " [" << getLineNumber() << "] ";
699
700   if (isLocalToUnit())
701     OS << " [local] ";
702
703   if (isDefinition())
704     OS << " [def] ";
705
706   OS << "\n";
707 }
708
709 /// print - Print global variable.
710 void DIGlobalVariable::print(raw_ostream &OS) const {
711   OS << " [";
712   StringRef Res = getName();
713   if (!Res.empty())
714     OS << " [" << Res << "] ";
715
716   unsigned Tag = getTag();
717   OS << " [" << dwarf::TagString(Tag) << "] ";
718
719   // TODO : Print context
720   OS << " [" << getLineNumber() << "] ";
721
722   if (isLocalToUnit())
723     OS << " [local] ";
724
725   if (isDefinition())
726     OS << " [def] ";
727
728   if (isGlobalVariable())
729     DIGlobalVariable(DbgNode).print(OS);
730   OS << "]\n";
731 }
732
733 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
734                           const LLVMContext &Ctx) {
735   if (!DL.isUnknown()) {          // Print source line info.
736     DIScope Scope(DL.getScope(Ctx));
737     // Omit the directory, because it's likely to be long and uninteresting.
738     if (Scope.Verify())
739       CommentOS << Scope.getFilename();
740     else
741       CommentOS << "<unknown>";
742     CommentOS << ':' << DL.getLine();
743     if (DL.getCol() != 0)
744       CommentOS << ':' << DL.getCol();
745     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
746     if (!InlinedAtDL.isUnknown()) {
747       CommentOS << " @[ ";
748       printDebugLoc(InlinedAtDL, CommentOS, Ctx);
749       CommentOS << " ]";
750     }
751   }
752 }
753
754 void DIVariable::printExtendedName(raw_ostream &OS) const {
755   const LLVMContext &Ctx = DbgNode->getContext();
756   StringRef Res = getName();
757   if (!Res.empty())
758     OS << Res << "," << getLineNumber();
759   if (MDNode *InlinedAt = getInlinedAt()) {
760     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
761     if (!InlinedAtDL.isUnknown()) {
762       OS << " @[";
763       printDebugLoc(InlinedAtDL, OS, Ctx);
764       OS << "]";
765     }
766   }
767 }
768
769 /// print - Print variable.
770 void DIVariable::print(raw_ostream &OS) const {
771   StringRef Res = getName();
772   if (!Res.empty())
773     OS << " [" << Res << "] ";
774
775   OS << " [" << getLineNumber() << "] ";
776   getType().print(OS);
777   OS << "\n";
778
779   // FIXME: Dump complex addresses
780 }
781
782 /// dump - Print descriptor to dbgs() with a newline.
783 void DIDescriptor::dump() const {
784   print(dbgs()); dbgs() << '\n';
785 }
786
787 /// dump - Print compile unit to dbgs() with a newline.
788 void DICompileUnit::dump() const {
789   print(dbgs()); dbgs() << '\n';
790 }
791
792 /// dump - Print type to dbgs() with a newline.
793 void DIType::dump() const {
794   print(dbgs()); dbgs() << '\n';
795 }
796
797 /// dump - Print basic type to dbgs() with a newline.
798 void DIBasicType::dump() const {
799   print(dbgs()); dbgs() << '\n';
800 }
801
802 /// dump - Print derived type to dbgs() with a newline.
803 void DIDerivedType::dump() const {
804   print(dbgs()); dbgs() << '\n';
805 }
806
807 /// dump - Print composite type to dbgs() with a newline.
808 void DICompositeType::dump() const {
809   print(dbgs()); dbgs() << '\n';
810 }
811
812 /// dump - Print subprogram to dbgs() with a newline.
813 void DISubprogram::dump() const {
814   print(dbgs()); dbgs() << '\n';
815 }
816
817 /// dump - Print global variable.
818 void DIGlobalVariable::dump() const {
819   print(dbgs()); dbgs() << '\n';
820 }
821
822 /// dump - Print variable.
823 void DIVariable::dump() const {
824   print(dbgs()); dbgs() << '\n';
825 }
826
827 /// fixupObjcLikeName - Replace contains special characters used
828 /// in a typical Objective-C names with '.' in a given string.
829 static void fixupObjcLikeName(StringRef Str, SmallVectorImpl<char> &Out) {
830   bool isObjCLike = false;
831   for (size_t i = 0, e = Str.size(); i < e; ++i) {
832     char C = Str[i];
833     if (C == '[')
834       isObjCLike = true;
835
836     if (isObjCLike && (C == '[' || C == ']' || C == ' ' || C == ':' ||
837                        C == '+' || C == '(' || C == ')'))
838       Out.push_back('.');
839     else
840       Out.push_back(C);
841   }
842 }
843
844 /// getFnSpecificMDNode - Return a NameMDNode, if available, that is 
845 /// suitable to hold function specific information.
846 NamedMDNode *llvm::getFnSpecificMDNode(const Module &M, DISubprogram Fn) {
847   SmallString<32> Name = StringRef("llvm.dbg.lv.");
848   StringRef FName = "fn";
849   if (Fn.getFunction())
850     FName = Fn.getFunction()->getName();
851   else
852     FName = Fn.getName();
853   char One = '\1';
854   if (FName.startswith(StringRef(&One, 1)))
855     FName = FName.substr(1);
856   fixupObjcLikeName(FName, Name);
857   return M.getNamedMetadata(Name.str());
858 }
859
860 /// getOrInsertFnSpecificMDNode - Return a NameMDNode that is suitable
861 /// to hold function specific information.
862 NamedMDNode *llvm::getOrInsertFnSpecificMDNode(Module &M, DISubprogram Fn) {
863   SmallString<32> Name = StringRef("llvm.dbg.lv.");
864   StringRef FName = "fn";
865   if (Fn.getFunction())
866     FName = Fn.getFunction()->getName();
867   else
868     FName = Fn.getName();
869   char One = '\1';
870   if (FName.startswith(StringRef(&One, 1)))
871     FName = FName.substr(1);
872   fixupObjcLikeName(FName, Name);
873   
874   return M.getOrInsertNamedMetadata(Name.str());
875 }
876
877 /// createInlinedVariable - Create a new inlined variable based on current
878 /// variable.
879 /// @param DV            Current Variable.
880 /// @param InlinedScope  Location at current variable is inlined.
881 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
882                                        LLVMContext &VMContext) {
883   SmallVector<Value *, 16> Elts;
884   // Insert inlined scope as 7th element.
885   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
886     i == 7 ? Elts.push_back(InlinedScope) :
887              Elts.push_back(DV->getOperand(i));
888   return DIVariable(MDNode::get(VMContext, Elts));
889 }
890
891 /// cleanseInlinedVariable - Remove inlined scope from the variable.
892 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
893   SmallVector<Value *, 16> Elts;
894   // Insert inlined scope as 7th element.
895   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
896     i == 7 ? 
897       Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext))):
898       Elts.push_back(DV->getOperand(i));
899   return DIVariable(MDNode::get(VMContext, Elts));
900 }
901
902 //===----------------------------------------------------------------------===//
903 // DebugInfoFinder implementations.
904 //===----------------------------------------------------------------------===//
905
906 /// processModule - Process entire module and collect debug info.
907 void DebugInfoFinder::processModule(Module &M) {
908   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu"))
909     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i)
910       addCompileUnit(DICompileUnit(CU_Nodes->getOperand(i)));
911
912   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
913     for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
914       for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
915            ++BI) {
916         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
917           processDeclare(DDI);
918
919         DebugLoc Loc = BI->getDebugLoc();
920         if (Loc.isUnknown())
921           continue;
922
923         LLVMContext &Ctx = BI->getContext();
924         DIDescriptor Scope(Loc.getScope(Ctx));
925
926         if (Scope.isCompileUnit())
927           addCompileUnit(DICompileUnit(Scope));
928         else if (Scope.isSubprogram())
929           processSubprogram(DISubprogram(Scope));
930         else if (Scope.isLexicalBlock())
931           processLexicalBlock(DILexicalBlock(Scope));
932
933         if (MDNode *IA = Loc.getInlinedAt(Ctx))
934           processLocation(DILocation(IA));
935       }
936
937   if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv")) {
938     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
939       DIGlobalVariable DIG(cast<MDNode>(NMD->getOperand(i)));
940       if (addGlobalVariable(DIG)) {
941         if (DIG.getVersion() <= LLVMDebugVersion10)
942           addCompileUnit(DIG.getCompileUnit());
943         processType(DIG.getType());
944       }
945     }
946   }
947
948   if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
949     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
950       processSubprogram(DISubprogram(NMD->getOperand(i)));
951 }
952
953 /// processLocation - Process DILocation.
954 void DebugInfoFinder::processLocation(DILocation Loc) {
955   if (!Loc.Verify()) return;
956   DIDescriptor S(Loc.getScope());
957   if (S.isCompileUnit())
958     addCompileUnit(DICompileUnit(S));
959   else if (S.isSubprogram())
960     processSubprogram(DISubprogram(S));
961   else if (S.isLexicalBlock())
962     processLexicalBlock(DILexicalBlock(S));
963   processLocation(Loc.getOrigLocation());
964 }
965
966 /// processType - Process DIType.
967 void DebugInfoFinder::processType(DIType DT) {
968   if (!addType(DT))
969     return;
970   if (DT.getVersion() <= LLVMDebugVersion10)
971     addCompileUnit(DT.getCompileUnit());
972   if (DT.isCompositeType()) {
973     DICompositeType DCT(DT);
974     processType(DCT.getTypeDerivedFrom());
975     DIArray DA = DCT.getTypeArray();
976     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
977       DIDescriptor D = DA.getElement(i);
978       if (D.isType())
979         processType(DIType(D));
980       else if (D.isSubprogram())
981         processSubprogram(DISubprogram(D));
982     }
983   } else if (DT.isDerivedType()) {
984     DIDerivedType DDT(DT);
985     processType(DDT.getTypeDerivedFrom());
986   }
987 }
988
989 /// processLexicalBlock
990 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
991   DIScope Context = LB.getContext();
992   if (Context.isLexicalBlock())
993     return processLexicalBlock(DILexicalBlock(Context));
994   else
995     return processSubprogram(DISubprogram(Context));
996 }
997
998 /// processSubprogram - Process DISubprogram.
999 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1000   if (!addSubprogram(SP))
1001     return;
1002   if (SP.getVersion() <= LLVMDebugVersion10)
1003     addCompileUnit(SP.getCompileUnit());
1004   processType(SP.getType());
1005 }
1006
1007 /// processDeclare - Process DbgDeclareInst.
1008 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1009   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1010   if (!N) return;
1011
1012   DIDescriptor DV(N);
1013   if (!DV.isVariable())
1014     return;
1015
1016   if (!NodesSeen.insert(DV))
1017     return;
1018   if (DIVariable(N).getVersion() <= LLVMDebugVersion10)
1019     addCompileUnit(DIVariable(N).getCompileUnit());
1020   processType(DIVariable(N).getType());
1021 }
1022
1023 /// addType - Add type into Tys.
1024 bool DebugInfoFinder::addType(DIType DT) {
1025   if (!DT.isValid())
1026     return false;
1027
1028   if (!NodesSeen.insert(DT))
1029     return false;
1030
1031   TYs.push_back(DT);
1032   return true;
1033 }
1034
1035 /// addCompileUnit - Add compile unit into CUs.
1036 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1037   if (!CU.Verify())
1038     return false;
1039
1040   if (!NodesSeen.insert(CU))
1041     return false;
1042
1043   CUs.push_back(CU);
1044   return true;
1045 }
1046
1047 /// addGlobalVariable - Add global variable into GVs.
1048 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1049   if (!DIDescriptor(DIG).isGlobalVariable())
1050     return false;
1051
1052   if (!NodesSeen.insert(DIG))
1053     return false;
1054
1055   GVs.push_back(DIG);
1056   return true;
1057 }
1058
1059 // addSubprogram - Add subprgoram into SPs.
1060 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1061   if (!DIDescriptor(SP).isSubprogram())
1062     return false;
1063
1064   if (!NodesSeen.insert(SP))
1065     return false;
1066
1067   SPs.push_back(SP);
1068   return true;
1069 }
1070
1071 /// getDISubprogram - Find subprogram that is enclosing this scope.
1072 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
1073   DIDescriptor D(Scope);
1074   if (D.isSubprogram())
1075     return DISubprogram(Scope);
1076
1077   if (D.isLexicalBlock())
1078     return getDISubprogram(DILexicalBlock(Scope).getContext());
1079
1080   return DISubprogram();
1081 }
1082
1083 /// getDICompositeType - Find underlying composite type.
1084 DICompositeType llvm::getDICompositeType(DIType T) {
1085   if (T.isCompositeType())
1086     return DICompositeType(T);
1087
1088   if (T.isDerivedType())
1089     return getDICompositeType(DIDerivedType(T).getTypeDerivedFrom());
1090
1091   return DICompositeType();
1092 }
1093
1094 /// isSubprogramContext - Return true if Context is either a subprogram
1095 /// or another context nested inside a subprogram.
1096 bool llvm::isSubprogramContext(const MDNode *Context) {
1097   if (!Context)
1098     return false;
1099   DIDescriptor D(Context);
1100   if (D.isSubprogram())
1101     return true;
1102   if (D.isType())
1103     return isSubprogramContext(DIType(Context).getContext());
1104   return false;
1105 }
1106