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