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