]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/IR/DebugInfo.cpp
DebugInfo: Ensure that all debug location scope chains from instructions within a...
[opencl/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 //===----------------------------------------------------------------------===//
15 #include "llvm/IR/DebugInfo.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/ValueHandle.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Dwarf.h"
30 #include "llvm/Support/raw_ostream.h"
31 using namespace llvm;
32 using namespace llvm::dwarf;
34 //===----------------------------------------------------------------------===//
35 // DIDescriptor
36 //===----------------------------------------------------------------------===//
38 bool DIDescriptor::Verify() const {
39   return DbgNode &&
40          (DIDerivedType(DbgNode).Verify() ||
41           DICompositeType(DbgNode).Verify() || DIBasicType(DbgNode).Verify() ||
42           DIVariable(DbgNode).Verify() || DISubprogram(DbgNode).Verify() ||
43           DIGlobalVariable(DbgNode).Verify() || DIFile(DbgNode).Verify() ||
44           DICompileUnit(DbgNode).Verify() || DINameSpace(DbgNode).Verify() ||
45           DILexicalBlock(DbgNode).Verify() ||
46           DILexicalBlockFile(DbgNode).Verify() ||
47           DISubrange(DbgNode).Verify() || DIEnumerator(DbgNode).Verify() ||
48           DIObjCProperty(DbgNode).Verify() ||
49           DIUnspecifiedParameter(DbgNode).Verify() ||
50           DITemplateTypeParameter(DbgNode).Verify() ||
51           DITemplateValueParameter(DbgNode).Verify() ||
52           DIImportedEntity(DbgNode).Verify());
53 }
55 static Value *getField(const MDNode *DbgNode, unsigned Elt) {
56   if (!DbgNode || Elt >= DbgNode->getNumOperands())
57     return nullptr;
58   return DbgNode->getOperand(Elt);
59 }
61 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
62   return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
63 }
65 static StringRef getStringField(const MDNode *DbgNode, unsigned Elt) {
66   if (MDString *MDS = dyn_cast_or_null<MDString>(getField(DbgNode, Elt)))
67     return MDS->getString();
68   return StringRef();
69 }
71 StringRef DIDescriptor::getStringField(unsigned Elt) const {
72   return ::getStringField(DbgNode, Elt);
73 }
75 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
76   if (!DbgNode)
77     return 0;
79   if (Elt < DbgNode->getNumOperands())
80     if (ConstantInt *CI =
81             dyn_cast_or_null<ConstantInt>(DbgNode->getOperand(Elt)))
82       return CI->getZExtValue();
84   return 0;
85 }
87 int64_t DIDescriptor::getInt64Field(unsigned Elt) const {
88   if (!DbgNode)
89     return 0;
91   if (Elt < DbgNode->getNumOperands())
92     if (ConstantInt *CI =
93             dyn_cast_or_null<ConstantInt>(DbgNode->getOperand(Elt)))
94       return CI->getSExtValue();
96   return 0;
97 }
99 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
100   MDNode *Field = getNodeField(DbgNode, Elt);
101   return DIDescriptor(Field);
104 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
105   if (!DbgNode)
106     return nullptr;
108   if (Elt < DbgNode->getNumOperands())
109     return dyn_cast_or_null<GlobalVariable>(DbgNode->getOperand(Elt));
110   return nullptr;
113 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
114   if (!DbgNode)
115     return nullptr;
117   if (Elt < DbgNode->getNumOperands())
118     return dyn_cast_or_null<Constant>(DbgNode->getOperand(Elt));
119   return nullptr;
122 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
123   if (!DbgNode)
124     return nullptr;
126   if (Elt < DbgNode->getNumOperands())
127     return dyn_cast_or_null<Function>(DbgNode->getOperand(Elt));
128   return nullptr;
131 void DIDescriptor::replaceFunctionField(unsigned Elt, Function *F) {
132   if (!DbgNode)
133     return;
135   if (Elt < DbgNode->getNumOperands()) {
136     MDNode *Node = const_cast<MDNode *>(DbgNode);
137     Node->replaceOperandWith(Elt, F);
138   }
141 uint64_t DIVariable::getAddrElement(unsigned Idx) const {
142   DIDescriptor ComplexExpr = getDescriptorField(8);
143   if (Idx < ComplexExpr->getNumOperands())
144     if (auto *CI = dyn_cast_or_null<ConstantInt>(ComplexExpr->getOperand(Idx)))
145       return CI->getZExtValue();
147   assert(false && "non-existing complex address element requested");
148   return 0;
151 /// getInlinedAt - If this variable is inlined then return inline location.
152 MDNode *DIVariable::getInlinedAt() const { return getNodeField(DbgNode, 7); }
154 //===----------------------------------------------------------------------===//
155 // Predicates
156 //===----------------------------------------------------------------------===//
158 /// isBasicType - Return true if the specified tag is legal for
159 /// DIBasicType.
160 bool DIDescriptor::isBasicType() const {
161   if (!DbgNode)
162     return false;
163   switch (getTag()) {
164   case dwarf::DW_TAG_base_type:
165   case dwarf::DW_TAG_unspecified_type:
166     return true;
167   default:
168     return false;
169   }
172 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
173 bool DIDescriptor::isDerivedType() const {
174   if (!DbgNode)
175     return false;
176   switch (getTag()) {
177   case dwarf::DW_TAG_typedef:
178   case dwarf::DW_TAG_pointer_type:
179   case dwarf::DW_TAG_ptr_to_member_type:
180   case dwarf::DW_TAG_reference_type:
181   case dwarf::DW_TAG_rvalue_reference_type:
182   case dwarf::DW_TAG_const_type:
183   case dwarf::DW_TAG_volatile_type:
184   case dwarf::DW_TAG_restrict_type:
185   case dwarf::DW_TAG_member:
186   case dwarf::DW_TAG_inheritance:
187   case dwarf::DW_TAG_friend:
188     return true;
189   default:
190     // CompositeTypes are currently modelled as DerivedTypes.
191     return isCompositeType();
192   }
195 /// isCompositeType - Return true if the specified tag is legal for
196 /// DICompositeType.
197 bool DIDescriptor::isCompositeType() const {
198   if (!DbgNode)
199     return false;
200   switch (getTag()) {
201   case dwarf::DW_TAG_array_type:
202   case dwarf::DW_TAG_structure_type:
203   case dwarf::DW_TAG_union_type:
204   case dwarf::DW_TAG_enumeration_type:
205   case dwarf::DW_TAG_subroutine_type:
206   case dwarf::DW_TAG_class_type:
207     return true;
208   default:
209     return false;
210   }
213 /// isVariable - Return true if the specified tag is legal for DIVariable.
214 bool DIDescriptor::isVariable() const {
215   if (!DbgNode)
216     return false;
217   switch (getTag()) {
218   case dwarf::DW_TAG_auto_variable:
219   case dwarf::DW_TAG_arg_variable:
220     return true;
221   default:
222     return false;
223   }
226 /// isType - Return true if the specified tag is legal for DIType.
227 bool DIDescriptor::isType() const {
228   return isBasicType() || isCompositeType() || isDerivedType();
231 /// isSubprogram - Return true if the specified tag is legal for
232 /// DISubprogram.
233 bool DIDescriptor::isSubprogram() const {
234   return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
237 /// isGlobalVariable - Return true if the specified tag is legal for
238 /// DIGlobalVariable.
239 bool DIDescriptor::isGlobalVariable() const {
240   return DbgNode && (getTag() == dwarf::DW_TAG_variable ||
241                      getTag() == dwarf::DW_TAG_constant);
244 /// isUnspecifiedParmeter - Return true if the specified tag is
245 /// DW_TAG_unspecified_parameters.
246 bool DIDescriptor::isUnspecifiedParameter() const {
247   return DbgNode && getTag() == dwarf::DW_TAG_unspecified_parameters;
250 /// isScope - Return true if the specified tag is one of the scope
251 /// related tag.
252 bool DIDescriptor::isScope() const {
253   if (!DbgNode)
254     return false;
255   switch (getTag()) {
256   case dwarf::DW_TAG_compile_unit:
257   case dwarf::DW_TAG_lexical_block:
258   case dwarf::DW_TAG_subprogram:
259   case dwarf::DW_TAG_namespace:
260   case dwarf::DW_TAG_file_type:
261     return true;
262   default:
263     break;
264   }
265   return isType();
268 /// isTemplateTypeParameter - Return true if the specified tag is
269 /// DW_TAG_template_type_parameter.
270 bool DIDescriptor::isTemplateTypeParameter() const {
271   return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter;
274 /// isTemplateValueParameter - Return true if the specified tag is
275 /// DW_TAG_template_value_parameter.
276 bool DIDescriptor::isTemplateValueParameter() const {
277   return DbgNode && (getTag() == dwarf::DW_TAG_template_value_parameter ||
278                      getTag() == dwarf::DW_TAG_GNU_template_template_param ||
279                      getTag() == dwarf::DW_TAG_GNU_template_parameter_pack);
282 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
283 bool DIDescriptor::isCompileUnit() const {
284   return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
287 /// isFile - Return true if the specified tag is DW_TAG_file_type.
288 bool DIDescriptor::isFile() const {
289   return DbgNode && getTag() == dwarf::DW_TAG_file_type;
292 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
293 bool DIDescriptor::isNameSpace() const {
294   return DbgNode && getTag() == dwarf::DW_TAG_namespace;
297 /// isLexicalBlockFile - Return true if the specified descriptor is a
298 /// lexical block with an extra file.
299 bool DIDescriptor::isLexicalBlockFile() const {
300   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
301          (DbgNode->getNumOperands() == 3);
304 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
305 bool DIDescriptor::isLexicalBlock() const {
306   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
307          (DbgNode->getNumOperands() > 3);
310 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
311 bool DIDescriptor::isSubrange() const {
312   return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
315 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
316 bool DIDescriptor::isEnumerator() const {
317   return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
320 /// isObjCProperty - Return true if the specified tag is DW_TAG_APPLE_property.
321 bool DIDescriptor::isObjCProperty() const {
322   return DbgNode && getTag() == dwarf::DW_TAG_APPLE_property;
325 /// \brief Return true if the specified tag is DW_TAG_imported_module or
326 /// DW_TAG_imported_declaration.
327 bool DIDescriptor::isImportedEntity() const {
328   return DbgNode && (getTag() == dwarf::DW_TAG_imported_module ||
329                      getTag() == dwarf::DW_TAG_imported_declaration);
332 //===----------------------------------------------------------------------===//
333 // Simple Descriptor Constructors and other Methods
334 //===----------------------------------------------------------------------===//
336 unsigned DIArray::getNumElements() const {
337   if (!DbgNode)
338     return 0;
339   return DbgNode->getNumOperands();
342 /// replaceAllUsesWith - Replace all uses of the MDNode used by this
343 /// type with the one in the passed descriptor.
344 void DIType::replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D) {
346   assert(DbgNode && "Trying to replace an unverified type!");
348   // Since we use a TrackingVH for the node, its easy for clients to manufacture
349   // legitimate situations where they want to replaceAllUsesWith() on something
350   // which, due to uniquing, has merged with the source. We shield clients from
351   // this detail by allowing a value to be replaced with replaceAllUsesWith()
352   // itself.
353   const MDNode *DN = D;
354   if (DbgNode == DN) {
355     SmallVector<Value*, 10> Ops(DbgNode->getNumOperands());
356     for (size_t i = 0; i != Ops.size(); ++i)
357       Ops[i] = DbgNode->getOperand(i);
358     DN = MDNode::get(VMContext, Ops);
359   }
361   MDNode *Node = const_cast<MDNode *>(DbgNode);
362   const Value *V = cast_or_null<Value>(DN);
363   Node->replaceAllUsesWith(const_cast<Value *>(V));
364   MDNode::deleteTemporary(Node);
365   DbgNode = D;
368 /// replaceAllUsesWith - Replace all uses of the MDNode used by this
369 /// type with the one in D.
370 void DIType::replaceAllUsesWith(MDNode *D) {
372   assert(DbgNode && "Trying to replace an unverified type!");
373   assert(DbgNode != D && "This replacement should always happen");
374   MDNode *Node = const_cast<MDNode *>(DbgNode);
375   const MDNode *DN = D;
376   const Value *V = cast_or_null<Value>(DN);
377   Node->replaceAllUsesWith(const_cast<Value *>(V));
378   MDNode::deleteTemporary(Node);
381 /// Verify - Verify that a compile unit is well formed.
382 bool DICompileUnit::Verify() const {
383   if (!isCompileUnit())
384     return false;
386   // Don't bother verifying the compilation directory or producer string
387   // as those could be empty.
388   if (getFilename().empty())
389     return false;
391   return DbgNode->getNumOperands() == 14;
394 /// Verify - Verify that an ObjC property is well formed.
395 bool DIObjCProperty::Verify() const {
396   if (!isObjCProperty())
397     return false;
399   // Don't worry about the rest of the strings for now.
400   return DbgNode->getNumOperands() == 8;
403 /// Check if a field at position Elt of a MDNode is a MDNode.
404 /// We currently allow an empty string and an integer.
405 /// But we don't allow a non-empty string in a MDNode field.
406 static bool fieldIsMDNode(const MDNode *DbgNode, unsigned Elt) {
407   // FIXME: This function should return true, if the field is null or the field
408   // is indeed a MDNode: return !Fld || isa<MDNode>(Fld).
409   Value *Fld = getField(DbgNode, Elt);
410   if (Fld && isa<MDString>(Fld) && !cast<MDString>(Fld)->getString().empty())
411     return false;
412   return true;
415 /// Check if a field at position Elt of a MDNode is a MDString.
416 static bool fieldIsMDString(const MDNode *DbgNode, unsigned Elt) {
417   Value *Fld = getField(DbgNode, Elt);
418   return !Fld || isa<MDString>(Fld);
421 /// Check if a value can be a reference to a type.
422 static bool isTypeRef(const Value *Val) {
423   return !Val ||
424          (isa<MDString>(Val) && !cast<MDString>(Val)->getString().empty()) ||
425          (isa<MDNode>(Val) && DIType(cast<MDNode>(Val)).isType());
428 /// Check if a field at position Elt of a MDNode can be a reference to a type.
429 static bool fieldIsTypeRef(const MDNode *DbgNode, unsigned Elt) {
430   Value *Fld = getField(DbgNode, Elt);
431   return isTypeRef(Fld);
434 /// Check if a value can be a ScopeRef.
435 static bool isScopeRef(const Value *Val) {
436   return !Val ||
437     (isa<MDString>(Val) && !cast<MDString>(Val)->getString().empty()) ||
438     // Not checking for Val->isScope() here, because it would work
439     // only for lexical scopes and not all subclasses of DIScope.
440     isa<MDNode>(Val);
443 /// Check if a field at position Elt of a MDNode can be a ScopeRef.
444 static bool fieldIsScopeRef(const MDNode *DbgNode, unsigned Elt) {
445   Value *Fld = getField(DbgNode, Elt);
446   return isScopeRef(Fld);
449 /// Verify - Verify that a type descriptor is well formed.
450 bool DIType::Verify() const {
451   if (!isType())
452     return false;
453   // Make sure Context @ field 2 is MDNode.
454   if (!fieldIsScopeRef(DbgNode, 2))
455     return false;
457   // FIXME: Sink this into the various subclass verifies.
458   uint16_t Tag = getTag();
459   if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
460       Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
461       Tag != dwarf::DW_TAG_ptr_to_member_type &&
462       Tag != dwarf::DW_TAG_reference_type &&
463       Tag != dwarf::DW_TAG_rvalue_reference_type &&
464       Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
465       Tag != dwarf::DW_TAG_enumeration_type &&
466       Tag != dwarf::DW_TAG_subroutine_type &&
467       Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
468       getFilename().empty())
469     return false;
470   // DIType is abstract, it should be a BasicType, a DerivedType or
471   // a CompositeType.
472   if (isBasicType())
473     return DIBasicType(DbgNode).Verify();
474   else if (isCompositeType())
475     return DICompositeType(DbgNode).Verify();
476   else if (isDerivedType())
477     return DIDerivedType(DbgNode).Verify();
478   else
479     return false;
482 /// Verify - Verify that a basic type descriptor is well formed.
483 bool DIBasicType::Verify() const {
484   return isBasicType() && DbgNode->getNumOperands() == 10;
487 /// Verify - Verify that a derived type descriptor is well formed.
488 bool DIDerivedType::Verify() const {
489   // Make sure DerivedFrom @ field 9 is TypeRef.
490   if (!fieldIsTypeRef(DbgNode, 9))
491     return false;
492   if (getTag() == dwarf::DW_TAG_ptr_to_member_type)
493     // Make sure ClassType @ field 10 is a TypeRef.
494     if (!fieldIsTypeRef(DbgNode, 10))
495       return false;
497   return isDerivedType() && DbgNode->getNumOperands() >= 10 &&
498          DbgNode->getNumOperands() <= 14;
501 /// Verify - Verify that a composite type descriptor is well formed.
502 bool DICompositeType::Verify() const {
503   if (!isCompositeType())
504     return false;
506   // Make sure DerivedFrom @ field 9 and ContainingType @ field 12 are TypeRef.
507   if (!fieldIsTypeRef(DbgNode, 9))
508     return false;
509   if (!fieldIsTypeRef(DbgNode, 12))
510     return false;
512   // Make sure the type identifier at field 14 is MDString, it can be null.
513   if (!fieldIsMDString(DbgNode, 14))
514     return false;
516   // A subroutine type can't be both & and &&.
517   if (isLValueReference() && isRValueReference())
518     return false;
520   return DbgNode->getNumOperands() == 15;
523 /// Verify - Verify that a subprogram descriptor is well formed.
524 bool DISubprogram::Verify() const {
525   if (!isSubprogram())
526     return false;
528   // Make sure context @ field 2 is a ScopeRef and type @ field 7 is a MDNode.
529   if (!fieldIsScopeRef(DbgNode, 2))
530     return false;
531   if (!fieldIsMDNode(DbgNode, 7))
532     return false;
533   // Containing type @ field 12.
534   if (!fieldIsTypeRef(DbgNode, 12))
535     return false;
537   // A subprogram can't be both & and &&.
538   if (isLValueReference() && isRValueReference())
539     return false;
541   if (auto *F = getFunction()) {
542     LLVMContext &Ctxt = F->getContext();
543     for (auto &BB : *F) {
544       for (auto &I : BB) {
545         DebugLoc DL = I.getDebugLoc();
546         if (DL.isUnknown())
547           continue;
549         MDNode *Scope = nullptr;
550         MDNode *IA = nullptr;
551         // walk the inlined-at scopes
552         while (DL.getScopeAndInlinedAt(Scope, IA, F->getContext()), IA)
553           DL = DebugLoc::getFromDILocation(IA);
554         DL.getScopeAndInlinedAt(Scope, IA, Ctxt);
555         assert(!IA);
556         while (!DIDescriptor(Scope).isSubprogram()) {
557           DILexicalBlockFile D(Scope);
558           Scope = D.isLexicalBlockFile()
559                       ? D.getScope()
560                       : DebugLoc::getFromDILexicalBlock(Scope).getScope(Ctxt);
561         }
562         if (!DISubprogram(Scope).describes(F))
563           return false;
564       }
565     }
566   }
567   return DbgNode->getNumOperands() == 20;
570 /// Verify - Verify that a global variable descriptor is well formed.
571 bool DIGlobalVariable::Verify() const {
572   if (!isGlobalVariable())
573     return false;
575   if (getDisplayName().empty())
576     return false;
577   // Make sure context @ field 2 is an MDNode.
578   if (!fieldIsMDNode(DbgNode, 2))
579     return false;
580   // Make sure that type @ field 8 is a DITypeRef.
581   if (!fieldIsTypeRef(DbgNode, 8))
582     return false;
583   // Make sure StaticDataMemberDeclaration @ field 12 is MDNode.
584   if (!fieldIsMDNode(DbgNode, 12))
585     return false;
587   return DbgNode->getNumOperands() == 13;
590 /// Verify - Verify that a variable descriptor is well formed.
591 bool DIVariable::Verify() const {
592   if (!isVariable())
593     return false;
595   // Make sure context @ field 1 is an MDNode.
596   if (!fieldIsMDNode(DbgNode, 1))
597     return false;
598   // Make sure that type @ field 5 is a DITypeRef.
599   if (!fieldIsTypeRef(DbgNode, 5))
600     return false;
602   // Variable without a complex expression.
603   if (DbgNode->getNumOperands() == 8)
604     return true;
606   // Make sure the complex expression is an MDNode.
607   return (DbgNode->getNumOperands() == 9 && fieldIsMDNode(DbgNode, 8));
610 /// Verify - Verify that a location descriptor is well formed.
611 bool DILocation::Verify() const {
612   if (!DbgNode)
613     return false;
615   return DbgNode->getNumOperands() == 4;
618 /// Verify - Verify that a namespace descriptor is well formed.
619 bool DINameSpace::Verify() const {
620   if (!isNameSpace())
621     return false;
622   return DbgNode->getNumOperands() == 5;
625 /// \brief Retrieve the MDNode for the directory/file pair.
626 MDNode *DIFile::getFileNode() const { return getNodeField(DbgNode, 1); }
628 /// \brief Verify that the file descriptor is well formed.
629 bool DIFile::Verify() const {
630   return isFile() && DbgNode->getNumOperands() == 2;
633 /// \brief Verify that the enumerator descriptor is well formed.
634 bool DIEnumerator::Verify() const {
635   return isEnumerator() && DbgNode->getNumOperands() == 3;
638 /// \brief Verify that the subrange descriptor is well formed.
639 bool DISubrange::Verify() const {
640   return isSubrange() && DbgNode->getNumOperands() == 3;
643 /// \brief Verify that the lexical block descriptor is well formed.
644 bool DILexicalBlock::Verify() const {
645   return isLexicalBlock() && DbgNode->getNumOperands() == 7;
648 /// \brief Verify that the file-scoped lexical block descriptor is well formed.
649 bool DILexicalBlockFile::Verify() const {
650   return isLexicalBlockFile() && DbgNode->getNumOperands() == 3;
653 /// \brief Verify that an unspecified parameter descriptor is well formed.
654 bool DIUnspecifiedParameter::Verify() const {
655   return isUnspecifiedParameter() && DbgNode->getNumOperands() == 1;
658 /// \brief Verify that the template type parameter descriptor is well formed.
659 bool DITemplateTypeParameter::Verify() const {
660   return isTemplateTypeParameter() && DbgNode->getNumOperands() == 7;
663 /// \brief Verify that the template value parameter descriptor is well formed.
664 bool DITemplateValueParameter::Verify() const {
665   return isTemplateValueParameter() && DbgNode->getNumOperands() == 8;
668 /// \brief Verify that the imported module descriptor is well formed.
669 bool DIImportedEntity::Verify() const {
670   return isImportedEntity() &&
671          (DbgNode->getNumOperands() == 4 || DbgNode->getNumOperands() == 5);
674 /// getObjCProperty - Return property node, if this ivar is associated with one.
675 MDNode *DIDerivedType::getObjCProperty() const {
676   return getNodeField(DbgNode, 10);
679 MDString *DICompositeType::getIdentifier() const {
680   return cast_or_null<MDString>(getField(DbgNode, 14));
683 #ifndef NDEBUG
684 static void VerifySubsetOf(const MDNode *LHS, const MDNode *RHS) {
685   for (unsigned i = 0; i != LHS->getNumOperands(); ++i) {
686     // Skip the 'empty' list (that's a single i32 0, rather than truly empty).
687     if (i == 0 && isa<ConstantInt>(LHS->getOperand(i)))
688       continue;
689     const MDNode *E = cast<MDNode>(LHS->getOperand(i));
690     bool found = false;
691     for (unsigned j = 0; !found && j != RHS->getNumOperands(); ++j)
692       found = E == RHS->getOperand(j);
693     assert(found && "Losing a member during member list replacement");
694   }
696 #endif
698 /// \brief Set the array of member DITypes.
699 void DICompositeType::setTypeArray(DIArray Elements, DIArray TParams) {
700   assert((!TParams || DbgNode->getNumOperands() == 15) &&
701          "If you're setting the template parameters this should include a slot "
702          "for that!");
703   TrackingVH<MDNode> N(*this);
704   if (Elements) {
705 #ifndef NDEBUG
706     // Check that the new list of members contains all the old members as well.
707     if (const MDNode *El = cast_or_null<MDNode>(N->getOperand(10)))
708       VerifySubsetOf(El, Elements);
709 #endif
710     N->replaceOperandWith(10, Elements);
711   }
712   if (TParams)
713     N->replaceOperandWith(13, TParams);
714   DbgNode = N;
717 /// Generate a reference to this DIType. Uses the type identifier instead
718 /// of the actual MDNode if possible, to help type uniquing.
719 DIScopeRef DIScope::getRef() const {
720   if (!isCompositeType())
721     return DIScopeRef(*this);
722   DICompositeType DTy(DbgNode);
723   if (!DTy.getIdentifier())
724     return DIScopeRef(*this);
725   return DIScopeRef(DTy.getIdentifier());
728 /// \brief Set the containing type.
729 void DICompositeType::setContainingType(DICompositeType ContainingType) {
730   TrackingVH<MDNode> N(*this);
731   N->replaceOperandWith(12, ContainingType.getRef());
732   DbgNode = N;
735 /// isInlinedFnArgument - Return true if this variable provides debugging
736 /// information for an inlined function arguments.
737 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
738   assert(CurFn && "Invalid function");
739   if (!getContext().isSubprogram())
740     return false;
741   // This variable is not inlined function argument if its scope
742   // does not describe current function.
743   return !DISubprogram(getContext()).describes(CurFn);
746 /// describes - Return true if this subprogram provides debugging
747 /// information for the function F.
748 bool DISubprogram::describes(const Function *F) {
749   assert(F && "Invalid function");
750   if (F == getFunction())
751     return true;
752   StringRef Name = getLinkageName();
753   if (Name.empty())
754     Name = getName();
755   if (F->getName() == Name)
756     return true;
757   return false;
760 unsigned DISubprogram::isOptimized() const {
761   assert(DbgNode && "Invalid subprogram descriptor!");
762   if (DbgNode->getNumOperands() == 15)
763     return getUnsignedField(14);
764   return 0;
767 MDNode *DISubprogram::getVariablesNodes() const {
768   return getNodeField(DbgNode, 18);
771 DIArray DISubprogram::getVariables() const {
772   return DIArray(getNodeField(DbgNode, 18));
775 Value *DITemplateValueParameter::getValue() const {
776   return getField(DbgNode, 4);
779 // If the current node has a parent scope then return that,
780 // else return an empty scope.
781 DIScopeRef DIScope::getContext() const {
783   if (isType())
784     return DIType(DbgNode).getContext();
786   if (isSubprogram())
787     return DIScopeRef(DISubprogram(DbgNode).getContext());
789   if (isLexicalBlock())
790     return DIScopeRef(DILexicalBlock(DbgNode).getContext());
792   if (isLexicalBlockFile())
793     return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
795   if (isNameSpace())
796     return DIScopeRef(DINameSpace(DbgNode).getContext());
798   assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
799   return DIScopeRef(nullptr);
802 // If the scope node has a name, return that, else return an empty string.
803 StringRef DIScope::getName() const {
804   if (isType())
805     return DIType(DbgNode).getName();
806   if (isSubprogram())
807     return DISubprogram(DbgNode).getName();
808   if (isNameSpace())
809     return DINameSpace(DbgNode).getName();
810   assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
811           isCompileUnit()) &&
812          "Unhandled type of scope.");
813   return StringRef();
816 StringRef DIScope::getFilename() const {
817   if (!DbgNode)
818     return StringRef();
819   return ::getStringField(getNodeField(DbgNode, 1), 0);
822 StringRef DIScope::getDirectory() const {
823   if (!DbgNode)
824     return StringRef();
825   return ::getStringField(getNodeField(DbgNode, 1), 1);
828 DIArray DICompileUnit::getEnumTypes() const {
829   if (!DbgNode || DbgNode->getNumOperands() < 13)
830     return DIArray();
832   return DIArray(getNodeField(DbgNode, 7));
835 DIArray DICompileUnit::getRetainedTypes() const {
836   if (!DbgNode || DbgNode->getNumOperands() < 13)
837     return DIArray();
839   return DIArray(getNodeField(DbgNode, 8));
842 DIArray DICompileUnit::getSubprograms() const {
843   if (!DbgNode || DbgNode->getNumOperands() < 13)
844     return DIArray();
846   return DIArray(getNodeField(DbgNode, 9));
849 DIArray DICompileUnit::getGlobalVariables() const {
850   if (!DbgNode || DbgNode->getNumOperands() < 13)
851     return DIArray();
853   return DIArray(getNodeField(DbgNode, 10));
856 DIArray DICompileUnit::getImportedEntities() const {
857   if (!DbgNode || DbgNode->getNumOperands() < 13)
858     return DIArray();
860   return DIArray(getNodeField(DbgNode, 11));
863 /// copyWithNewScope - Return a copy of this location, replacing the
864 /// current scope with the given one.
865 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
866                                         DILexicalBlock NewScope) {
867   SmallVector<Value *, 10> Elts;
868   assert(Verify());
869   for (unsigned I = 0; I < DbgNode->getNumOperands(); ++I) {
870     if (I != 2)
871       Elts.push_back(DbgNode->getOperand(I));
872     else
873       Elts.push_back(NewScope);
874   }
875   MDNode *NewDIL = MDNode::get(Ctx, Elts);
876   return DILocation(NewDIL);
879 /// computeNewDiscriminator - Generate a new discriminator value for this
880 /// file and line location.
881 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
882   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
883   return ++Ctx.pImpl->DiscriminatorTable[Key];
886 /// fixupSubprogramName - Replace contains special characters used
887 /// in a typical Objective-C names with '.' in a given string.
888 static void fixupSubprogramName(DISubprogram Fn, SmallVectorImpl<char> &Out) {
889   StringRef FName =
890       Fn.getFunction() ? Fn.getFunction()->getName() : Fn.getName();
891   FName = Function::getRealLinkageName(FName);
893   StringRef Prefix("llvm.dbg.lv.");
894   Out.reserve(FName.size() + Prefix.size());
895   Out.append(Prefix.begin(), Prefix.end());
897   bool isObjCLike = false;
898   for (size_t i = 0, e = FName.size(); i < e; ++i) {
899     char C = FName[i];
900     if (C == '[')
901       isObjCLike = true;
903     if (isObjCLike && (C == '[' || C == ']' || C == ' ' || C == ':' ||
904                        C == '+' || C == '(' || C == ')'))
905       Out.push_back('.');
906     else
907       Out.push_back(C);
908   }
911 /// getFnSpecificMDNode - Return a NameMDNode, if available, that is
912 /// suitable to hold function specific information.
913 NamedMDNode *llvm::getFnSpecificMDNode(const Module &M, DISubprogram Fn) {
914   SmallString<32> Name;
915   fixupSubprogramName(Fn, Name);
916   return M.getNamedMetadata(Name.str());
919 /// getOrInsertFnSpecificMDNode - Return a NameMDNode that is suitable
920 /// to hold function specific information.
921 NamedMDNode *llvm::getOrInsertFnSpecificMDNode(Module &M, DISubprogram Fn) {
922   SmallString<32> Name;
923   fixupSubprogramName(Fn, Name);
924   return M.getOrInsertNamedMetadata(Name.str());
927 /// createInlinedVariable - Create a new inlined variable based on current
928 /// variable.
929 /// @param DV            Current Variable.
930 /// @param InlinedScope  Location at current variable is inlined.
931 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
932                                        LLVMContext &VMContext) {
933   SmallVector<Value *, 16> Elts;
934   // Insert inlined scope as 7th element.
935   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
936     i == 7 ? Elts.push_back(InlinedScope) : Elts.push_back(DV->getOperand(i));
937   return DIVariable(MDNode::get(VMContext, Elts));
940 /// cleanseInlinedVariable - Remove inlined scope from the variable.
941 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
942   SmallVector<Value *, 16> Elts;
943   // Insert inlined scope as 7th element.
944   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
945     i == 7 ? Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext)))
946            : Elts.push_back(DV->getOperand(i));
947   return DIVariable(MDNode::get(VMContext, Elts));
950 /// getDISubprogram - Find subprogram that is enclosing this scope.
951 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
952   DIDescriptor D(Scope);
953   if (D.isSubprogram())
954     return DISubprogram(Scope);
956   if (D.isLexicalBlockFile())
957     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
959   if (D.isLexicalBlock())
960     return getDISubprogram(DILexicalBlock(Scope).getContext());
962   return DISubprogram();
965 /// getDICompositeType - Find underlying composite type.
966 DICompositeType llvm::getDICompositeType(DIType T) {
967   if (T.isCompositeType())
968     return DICompositeType(T);
970   if (T.isDerivedType()) {
971     // This function is currently used by dragonegg and dragonegg does
972     // not generate identifier for types, so using an empty map to resolve
973     // DerivedFrom should be fine.
974     DITypeIdentifierMap EmptyMap;
975     return getDICompositeType(
976         DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
977   }
979   return DICompositeType();
982 /// Update DITypeIdentifierMap by going through retained types of each CU.
983 DITypeIdentifierMap
984 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
985   DITypeIdentifierMap Map;
986   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
987     DICompileUnit CU(CU_Nodes->getOperand(CUi));
988     DIArray Retain = CU.getRetainedTypes();
989     for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
990       if (!Retain.getElement(Ti).isCompositeType())
991         continue;
992       DICompositeType Ty(Retain.getElement(Ti));
993       if (MDString *TypeId = Ty.getIdentifier()) {
994         // Definition has priority over declaration.
995         // Try to insert (TypeId, Ty) to Map.
996         std::pair<DITypeIdentifierMap::iterator, bool> P =
997             Map.insert(std::make_pair(TypeId, Ty));
998         // If TypeId already exists in Map and this is a definition, replace
999         // whatever we had (declaration or definition) with the definition.
1000         if (!P.second && !Ty.isForwardDecl())
1001           P.first->second = Ty;
1002       }
1003     }
1004   }
1005   return Map;
1008 //===----------------------------------------------------------------------===//
1009 // DebugInfoFinder implementations.
1010 //===----------------------------------------------------------------------===//
1012 void DebugInfoFinder::reset() {
1013   CUs.clear();
1014   SPs.clear();
1015   GVs.clear();
1016   TYs.clear();
1017   Scopes.clear();
1018   NodesSeen.clear();
1019   TypeIdentifierMap.clear();
1020   TypeMapInitialized = false;
1023 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
1024   if (!TypeMapInitialized)
1025     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
1026       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
1027       TypeMapInitialized = true;
1028     }
1031 /// processModule - Process entire module and collect debug info.
1032 void DebugInfoFinder::processModule(const Module &M) {
1033   InitializeTypeMap(M);
1034   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
1035     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
1036       DICompileUnit CU(CU_Nodes->getOperand(i));
1037       addCompileUnit(CU);
1038       DIArray GVs = CU.getGlobalVariables();
1039       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
1040         DIGlobalVariable DIG(GVs.getElement(i));
1041         if (addGlobalVariable(DIG)) {
1042           processScope(DIG.getContext());
1043           processType(DIG.getType().resolve(TypeIdentifierMap));
1044         }
1045       }
1046       DIArray SPs = CU.getSubprograms();
1047       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
1048         processSubprogram(DISubprogram(SPs.getElement(i)));
1049       DIArray EnumTypes = CU.getEnumTypes();
1050       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
1051         processType(DIType(EnumTypes.getElement(i)));
1052       DIArray RetainedTypes = CU.getRetainedTypes();
1053       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
1054         processType(DIType(RetainedTypes.getElement(i)));
1055       DIArray Imports = CU.getImportedEntities();
1056       for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
1057         DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
1058         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
1059         if (Entity.isType())
1060           processType(DIType(Entity));
1061         else if (Entity.isSubprogram())
1062           processSubprogram(DISubprogram(Entity));
1063         else if (Entity.isNameSpace())
1064           processScope(DINameSpace(Entity).getContext());
1065       }
1066     }
1067   }
1070 /// processLocation - Process DILocation.
1071 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
1072   if (!Loc)
1073     return;
1074   InitializeTypeMap(M);
1075   processScope(Loc.getScope());
1076   processLocation(M, Loc.getOrigLocation());
1079 /// processType - Process DIType.
1080 void DebugInfoFinder::processType(DIType DT) {
1081   if (!addType(DT))
1082     return;
1083   processScope(DT.getContext().resolve(TypeIdentifierMap));
1084   if (DT.isCompositeType()) {
1085     DICompositeType DCT(DT);
1086     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1087     DIArray DA = DCT.getTypeArray();
1088     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1089       DIDescriptor D = DA.getElement(i);
1090       if (D.isType())
1091         processType(DIType(D));
1092       else if (D.isSubprogram())
1093         processSubprogram(DISubprogram(D));
1094     }
1095   } else if (DT.isDerivedType()) {
1096     DIDerivedType DDT(DT);
1097     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1098   }
1101 void DebugInfoFinder::processScope(DIScope Scope) {
1102   if (Scope.isType()) {
1103     DIType Ty(Scope);
1104     processType(Ty);
1105     return;
1106   }
1107   if (Scope.isCompileUnit()) {
1108     addCompileUnit(DICompileUnit(Scope));
1109     return;
1110   }
1111   if (Scope.isSubprogram()) {
1112     processSubprogram(DISubprogram(Scope));
1113     return;
1114   }
1115   if (!addScope(Scope))
1116     return;
1117   if (Scope.isLexicalBlock()) {
1118     DILexicalBlock LB(Scope);
1119     processScope(LB.getContext());
1120   } else if (Scope.isLexicalBlockFile()) {
1121     DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
1122     processScope(LBF.getScope());
1123   } else if (Scope.isNameSpace()) {
1124     DINameSpace NS(Scope);
1125     processScope(NS.getContext());
1126   }
1129 /// processSubprogram - Process DISubprogram.
1130 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1131   if (!addSubprogram(SP))
1132     return;
1133   processScope(SP.getContext().resolve(TypeIdentifierMap));
1134   processType(SP.getType());
1135   DIArray TParams = SP.getTemplateParams();
1136   for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
1137     DIDescriptor Element = TParams.getElement(I);
1138     if (Element.isTemplateTypeParameter()) {
1139       DITemplateTypeParameter TType(Element);
1140       processScope(TType.getContext().resolve(TypeIdentifierMap));
1141       processType(TType.getType().resolve(TypeIdentifierMap));
1142     } else if (Element.isTemplateValueParameter()) {
1143       DITemplateValueParameter TVal(Element);
1144       processScope(TVal.getContext().resolve(TypeIdentifierMap));
1145       processType(TVal.getType().resolve(TypeIdentifierMap));
1146     }
1147   }
1150 /// processDeclare - Process DbgDeclareInst.
1151 void DebugInfoFinder::processDeclare(const Module &M,
1152                                      const DbgDeclareInst *DDI) {
1153   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1154   if (!N)
1155     return;
1156   InitializeTypeMap(M);
1158   DIDescriptor DV(N);
1159   if (!DV.isVariable())
1160     return;
1162   if (!NodesSeen.insert(DV))
1163     return;
1164   processScope(DIVariable(N).getContext());
1165   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1168 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
1169   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
1170   if (!N)
1171     return;
1172   InitializeTypeMap(M);
1174   DIDescriptor DV(N);
1175   if (!DV.isVariable())
1176     return;
1178   if (!NodesSeen.insert(DV))
1179     return;
1180   processScope(DIVariable(N).getContext());
1181   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1184 /// addType - Add type into Tys.
1185 bool DebugInfoFinder::addType(DIType DT) {
1186   if (!DT)
1187     return false;
1189   if (!NodesSeen.insert(DT))
1190     return false;
1192   TYs.push_back(DT);
1193   return true;
1196 /// addCompileUnit - Add compile unit into CUs.
1197 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1198   if (!CU)
1199     return false;
1200   if (!NodesSeen.insert(CU))
1201     return false;
1203   CUs.push_back(CU);
1204   return true;
1207 /// addGlobalVariable - Add global variable into GVs.
1208 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1209   if (!DIG)
1210     return false;
1212   if (!NodesSeen.insert(DIG))
1213     return false;
1215   GVs.push_back(DIG);
1216   return true;
1219 // addSubprogram - Add subprgoram into SPs.
1220 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1221   if (!SP)
1222     return false;
1224   if (!NodesSeen.insert(SP))
1225     return false;
1227   SPs.push_back(SP);
1228   return true;
1231 bool DebugInfoFinder::addScope(DIScope Scope) {
1232   if (!Scope)
1233     return false;
1234   // FIXME: Ocaml binding generates a scope with no content, we treat it
1235   // as null for now.
1236   if (Scope->getNumOperands() == 0)
1237     return false;
1238   if (!NodesSeen.insert(Scope))
1239     return false;
1240   Scopes.push_back(Scope);
1241   return true;
1244 //===----------------------------------------------------------------------===//
1245 // DIDescriptor: dump routines for all descriptors.
1246 //===----------------------------------------------------------------------===//
1248 /// dump - Print descriptor to dbgs() with a newline.
1249 void DIDescriptor::dump() const {
1250   print(dbgs());
1251   dbgs() << '\n';
1254 /// print - Print descriptor.
1255 void DIDescriptor::print(raw_ostream &OS) const {
1256   if (!DbgNode)
1257     return;
1259   if (const char *Tag = dwarf::TagString(getTag()))
1260     OS << "[ " << Tag << " ]";
1262   if (this->isSubrange()) {
1263     DISubrange(DbgNode).printInternal(OS);
1264   } else if (this->isCompileUnit()) {
1265     DICompileUnit(DbgNode).printInternal(OS);
1266   } else if (this->isFile()) {
1267     DIFile(DbgNode).printInternal(OS);
1268   } else if (this->isEnumerator()) {
1269     DIEnumerator(DbgNode).printInternal(OS);
1270   } else if (this->isBasicType()) {
1271     DIType(DbgNode).printInternal(OS);
1272   } else if (this->isDerivedType()) {
1273     DIDerivedType(DbgNode).printInternal(OS);
1274   } else if (this->isCompositeType()) {
1275     DICompositeType(DbgNode).printInternal(OS);
1276   } else if (this->isSubprogram()) {
1277     DISubprogram(DbgNode).printInternal(OS);
1278   } else if (this->isGlobalVariable()) {
1279     DIGlobalVariable(DbgNode).printInternal(OS);
1280   } else if (this->isVariable()) {
1281     DIVariable(DbgNode).printInternal(OS);
1282   } else if (this->isObjCProperty()) {
1283     DIObjCProperty(DbgNode).printInternal(OS);
1284   } else if (this->isNameSpace()) {
1285     DINameSpace(DbgNode).printInternal(OS);
1286   } else if (this->isScope()) {
1287     DIScope(DbgNode).printInternal(OS);
1288   }
1291 void DISubrange::printInternal(raw_ostream &OS) const {
1292   int64_t Count = getCount();
1293   if (Count != -1)
1294     OS << " [" << getLo() << ", " << Count - 1 << ']';
1295   else
1296     OS << " [unbounded]";
1299 void DIScope::printInternal(raw_ostream &OS) const {
1300   OS << " [" << getDirectory() << "/" << getFilename() << ']';
1303 void DICompileUnit::printInternal(raw_ostream &OS) const {
1304   DIScope::printInternal(OS);
1305   OS << " [";
1306   unsigned Lang = getLanguage();
1307   if (const char *LangStr = dwarf::LanguageString(Lang))
1308     OS << LangStr;
1309   else
1310     (OS << "lang 0x").write_hex(Lang);
1311   OS << ']';
1314 void DIEnumerator::printInternal(raw_ostream &OS) const {
1315   OS << " [" << getName() << " :: " << getEnumValue() << ']';
1318 void DIType::printInternal(raw_ostream &OS) const {
1319   if (!DbgNode)
1320     return;
1322   StringRef Res = getName();
1323   if (!Res.empty())
1324     OS << " [" << Res << "]";
1326   // TODO: Print context?
1328   OS << " [line " << getLineNumber() << ", size " << getSizeInBits()
1329      << ", align " << getAlignInBits() << ", offset " << getOffsetInBits();
1330   if (isBasicType())
1331     if (const char *Enc =
1332             dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
1333       OS << ", enc " << Enc;
1334   OS << "]";
1336   if (isPrivate())
1337     OS << " [private]";
1338   else if (isProtected())
1339     OS << " [protected]";
1341   if (isArtificial())
1342     OS << " [artificial]";
1344   if (isForwardDecl())
1345     OS << " [decl]";
1346   else if (getTag() == dwarf::DW_TAG_structure_type ||
1347            getTag() == dwarf::DW_TAG_union_type ||
1348            getTag() == dwarf::DW_TAG_enumeration_type ||
1349            getTag() == dwarf::DW_TAG_class_type)
1350     OS << " [def]";
1351   if (isVector())
1352     OS << " [vector]";
1353   if (isStaticMember())
1354     OS << " [static]";
1356   if (isLValueReference())
1357     OS << " [reference]";
1359   if (isRValueReference())
1360     OS << " [rvalue reference]";
1363 void DIDerivedType::printInternal(raw_ostream &OS) const {
1364   DIType::printInternal(OS);
1365   OS << " [from " << getTypeDerivedFrom().getName() << ']';
1368 void DICompositeType::printInternal(raw_ostream &OS) const {
1369   DIType::printInternal(OS);
1370   DIArray A = getTypeArray();
1371   OS << " [" << A.getNumElements() << " elements]";
1374 void DINameSpace::printInternal(raw_ostream &OS) const {
1375   StringRef Name = getName();
1376   if (!Name.empty())
1377     OS << " [" << Name << ']';
1379   OS << " [line " << getLineNumber() << ']';
1382 void DISubprogram::printInternal(raw_ostream &OS) const {
1383   // TODO : Print context
1384   OS << " [line " << getLineNumber() << ']';
1386   if (isLocalToUnit())
1387     OS << " [local]";
1389   if (isDefinition())
1390     OS << " [def]";
1392   if (getScopeLineNumber() != getLineNumber())
1393     OS << " [scope " << getScopeLineNumber() << "]";
1395   if (isPrivate())
1396     OS << " [private]";
1397   else if (isProtected())
1398     OS << " [protected]";
1400   if (isLValueReference())
1401     OS << " [reference]";
1403   if (isRValueReference())
1404     OS << " [rvalue reference]";
1406   StringRef Res = getName();
1407   if (!Res.empty())
1408     OS << " [" << Res << ']';
1411 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
1412   StringRef Res = getName();
1413   if (!Res.empty())
1414     OS << " [" << Res << ']';
1416   OS << " [line " << getLineNumber() << ']';
1418   // TODO : Print context
1420   if (isLocalToUnit())
1421     OS << " [local]";
1423   if (isDefinition())
1424     OS << " [def]";
1427 void DIVariable::printInternal(raw_ostream &OS) const {
1428   StringRef Res = getName();
1429   if (!Res.empty())
1430     OS << " [" << Res << ']';
1432   OS << " [line " << getLineNumber() << ']';
1435 void DIObjCProperty::printInternal(raw_ostream &OS) const {
1436   StringRef Name = getObjCPropertyName();
1437   if (!Name.empty())
1438     OS << " [" << Name << ']';
1440   OS << " [line " << getLineNumber() << ", properties " << getUnsignedField(6)
1441      << ']';
1444 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
1445                           const LLVMContext &Ctx) {
1446   if (!DL.isUnknown()) { // Print source line info.
1447     DIScope Scope(DL.getScope(Ctx));
1448     assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
1449     // Omit the directory, because it's likely to be long and uninteresting.
1450     CommentOS << Scope.getFilename();
1451     CommentOS << ':' << DL.getLine();
1452     if (DL.getCol() != 0)
1453       CommentOS << ':' << DL.getCol();
1454     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1455     if (!InlinedAtDL.isUnknown()) {
1456       CommentOS << " @[ ";
1457       printDebugLoc(InlinedAtDL, CommentOS, Ctx);
1458       CommentOS << " ]";
1459     }
1460   }
1463 void DIVariable::printExtendedName(raw_ostream &OS) const {
1464   const LLVMContext &Ctx = DbgNode->getContext();
1465   StringRef Res = getName();
1466   if (!Res.empty())
1467     OS << Res << "," << getLineNumber();
1468   if (MDNode *InlinedAt = getInlinedAt()) {
1469     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1470     if (!InlinedAtDL.isUnknown()) {
1471       OS << " @[";
1472       printDebugLoc(InlinedAtDL, OS, Ctx);
1473       OS << "]";
1474     }
1475   }
1478 /// Specialize constructor to make sure it has the correct type.
1479 template <> DIRef<DIScope>::DIRef(const Value *V) : Val(V) {
1480   assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
1482 template <> DIRef<DIType>::DIRef(const Value *V) : Val(V) {
1483   assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
1486 /// Specialize getFieldAs to handle fields that are references to DIScopes.
1487 template <>
1488 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
1489   return DIScopeRef(getField(DbgNode, Elt));
1491 /// Specialize getFieldAs to handle fields that are references to DITypes.
1492 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
1493   return DITypeRef(getField(DbgNode, Elt));
1496 /// Strip debug info in the module if it exists.
1497 /// To do this, we remove all calls to the debugger intrinsics and any named
1498 /// metadata for debugging. We also remove debug locations for instructions.
1499 /// Return true if module is modified.
1500 bool llvm::StripDebugInfo(Module &M) {
1502   bool Changed = false;
1504   // Remove all of the calls to the debugger intrinsics, and remove them from
1505   // the module.
1506   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
1507     while (!Declare->use_empty()) {
1508       CallInst *CI = cast<CallInst>(Declare->user_back());
1509       CI->eraseFromParent();
1510     }
1511     Declare->eraseFromParent();
1512     Changed = true;
1513   }
1515   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
1516     while (!DbgVal->use_empty()) {
1517       CallInst *CI = cast<CallInst>(DbgVal->user_back());
1518       CI->eraseFromParent();
1519     }
1520     DbgVal->eraseFromParent();
1521     Changed = true;
1522   }
1524   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
1525          NME = M.named_metadata_end(); NMI != NME;) {
1526     NamedMDNode *NMD = NMI;
1527     ++NMI;
1528     if (NMD->getName().startswith("llvm.dbg.")) {
1529       NMD->eraseFromParent();
1530       Changed = true;
1531     }
1532   }
1534   for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
1535     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
1536          ++FI)
1537       for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
1538            ++BI) {
1539         if (!BI->getDebugLoc().isUnknown()) {
1540           Changed = true;
1541           BI->setDebugLoc(DebugLoc());
1542         }
1543       }
1545   return Changed;
1548 /// Return Debug Info Metadata Version by checking module flags.
1549 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
1550   Value *Val = M.getModuleFlag("Debug Info Version");
1551   if (!Val)
1552     return 0;
1553   return cast<ConstantInt>(Val)->getZExtValue();