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