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