1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the helper classes used to build and interpret debug
11 // information in LLVM IR form.
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/DIBuilder.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/ValueHandle.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/raw_ostream.h"
33 using namespace llvm::dwarf;
35 //===----------------------------------------------------------------------===//
37 //===----------------------------------------------------------------------===//
39 bool DIDescriptor::Verify() const {
41 (DIDerivedType(DbgNode).Verify() ||
42 DICompositeType(DbgNode).Verify() || DIBasicType(DbgNode).Verify() ||
43 DIVariable(DbgNode).Verify() || DISubprogram(DbgNode).Verify() ||
44 DIGlobalVariable(DbgNode).Verify() || DIFile(DbgNode).Verify() ||
45 DICompileUnit(DbgNode).Verify() || DINameSpace(DbgNode).Verify() ||
46 DILexicalBlock(DbgNode).Verify() ||
47 DILexicalBlockFile(DbgNode).Verify() ||
48 DISubrange(DbgNode).Verify() || DIEnumerator(DbgNode).Verify() ||
49 DIObjCProperty(DbgNode).Verify() ||
50 DITemplateTypeParameter(DbgNode).Verify() ||
51 DITemplateValueParameter(DbgNode).Verify() ||
52 DIImportedEntity(DbgNode).Verify() || DIExpression(DbgNode).Verify());
55 static Metadata *getField(const MDNode *DbgNode, unsigned Elt) {
56 if (!DbgNode || Elt >= DbgNode->getNumOperands())
58 return DbgNode->getOperand(Elt);
61 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
62 return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
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();
71 StringRef DIDescriptor::getStringField(unsigned Elt) const {
72 return ::getStringField(DbgNode, Elt);
75 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
76 if (auto *C = getConstantField(Elt))
77 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
78 return CI->getZExtValue();
83 int64_t DIDescriptor::getInt64Field(unsigned Elt) const {
84 if (auto *C = getConstantField(Elt))
85 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
86 return CI->getZExtValue();
91 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
92 MDNode *Field = getNodeField(DbgNode, Elt);
93 return DIDescriptor(Field);
96 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
97 return dyn_cast_or_null<GlobalVariable>(getConstantField(Elt));
100 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
104 if (Elt < DbgNode->getNumOperands())
106 dyn_cast_or_null<ConstantAsMetadata>(DbgNode->getOperand(Elt)))
107 return C->getValue();
111 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
112 return dyn_cast_or_null<Function>(getConstantField(Elt));
115 void DIDescriptor::replaceFunctionField(unsigned Elt, Function *F) {
119 if (Elt < DbgNode->getNumOperands()) {
120 MDNode *Node = const_cast<MDNode *>(DbgNode);
121 Node->replaceOperandWith(Elt, F ? ConstantAsMetadata::get(F) : nullptr);
125 static unsigned DIVariableInlinedAtIndex = 4;
126 MDNode *DIVariable::getInlinedAt() const {
127 return getNodeField(DbgNode, DIVariableInlinedAtIndex);
130 /// \brief Return the size reported by the variable's type.
131 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
132 DIType Ty = getType().resolve(Map);
133 // Follow derived types until we reach a type that
134 // reports back a size.
135 while (Ty.isDerivedType() && !Ty.getSizeInBits()) {
136 DIDerivedType DT(&*Ty);
137 Ty = DT.getTypeDerivedFrom().resolve(Map);
139 assert(Ty.getSizeInBits() && "type with size 0");
140 return Ty.getSizeInBits();
143 uint64_t DIExpression::getElement(unsigned Idx) const {
144 unsigned I = Idx + 1;
145 assert(I < getNumHeaderFields() &&
146 "non-existing complex address element requested");
147 return getHeaderFieldAs<int64_t>(I);
150 bool DIExpression::isBitPiece() const {
151 unsigned N = getNumElements();
152 return N >=3 && getElement(N-3) == dwarf::DW_OP_bit_piece;
155 uint64_t DIExpression::getBitPieceOffset() const {
156 assert(isBitPiece() && "not a piece");
157 return getElement(getNumElements()-2);
160 uint64_t DIExpression::getBitPieceSize() const {
161 assert(isBitPiece() && "not a piece");
162 return getElement(getNumElements()-1);
165 DIExpression::iterator DIExpression::begin() const {
166 return DIExpression::iterator(*this);
169 DIExpression::iterator DIExpression::end() const {
170 return DIExpression::iterator();
173 DIExpression::Operand DIExpression::Operand::getNext() const {
178 //===----------------------------------------------------------------------===//
180 //===----------------------------------------------------------------------===//
182 bool DIDescriptor::isSubroutineType() const {
183 return DbgNode && getTag() == dwarf::DW_TAG_subroutine_type;
186 bool DIDescriptor::isBasicType() const {
190 case dwarf::DW_TAG_base_type:
191 case dwarf::DW_TAG_unspecified_type:
198 bool DIDescriptor::isDerivedType() const {
202 case dwarf::DW_TAG_typedef:
203 case dwarf::DW_TAG_pointer_type:
204 case dwarf::DW_TAG_ptr_to_member_type:
205 case dwarf::DW_TAG_reference_type:
206 case dwarf::DW_TAG_rvalue_reference_type:
207 case dwarf::DW_TAG_const_type:
208 case dwarf::DW_TAG_volatile_type:
209 case dwarf::DW_TAG_restrict_type:
210 case dwarf::DW_TAG_member:
211 case dwarf::DW_TAG_inheritance:
212 case dwarf::DW_TAG_friend:
215 // CompositeTypes are currently modelled as DerivedTypes.
216 return isCompositeType();
220 bool DIDescriptor::isCompositeType() const {
224 case dwarf::DW_TAG_array_type:
225 case dwarf::DW_TAG_structure_type:
226 case dwarf::DW_TAG_union_type:
227 case dwarf::DW_TAG_enumeration_type:
228 case dwarf::DW_TAG_subroutine_type:
229 case dwarf::DW_TAG_class_type:
236 bool DIDescriptor::isVariable() const {
240 case dwarf::DW_TAG_auto_variable:
241 case dwarf::DW_TAG_arg_variable:
248 bool DIDescriptor::isType() const {
249 return isBasicType() || isCompositeType() || isDerivedType();
252 bool DIDescriptor::isSubprogram() const {
253 return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
256 bool DIDescriptor::isGlobalVariable() const {
257 return DbgNode && getTag() == dwarf::DW_TAG_variable;
260 bool DIDescriptor::isScope() const {
264 case dwarf::DW_TAG_compile_unit:
265 case dwarf::DW_TAG_lexical_block:
266 case dwarf::DW_TAG_subprogram:
267 case dwarf::DW_TAG_namespace:
268 case dwarf::DW_TAG_file_type:
276 bool DIDescriptor::isTemplateTypeParameter() const {
277 return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter;
280 bool DIDescriptor::isTemplateValueParameter() const {
281 return DbgNode && (getTag() == dwarf::DW_TAG_template_value_parameter ||
282 getTag() == dwarf::DW_TAG_GNU_template_template_param ||
283 getTag() == dwarf::DW_TAG_GNU_template_parameter_pack);
286 bool DIDescriptor::isCompileUnit() const {
287 return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
290 bool DIDescriptor::isFile() const {
291 return DbgNode && getTag() == dwarf::DW_TAG_file_type;
294 bool DIDescriptor::isNameSpace() const {
295 return DbgNode && getTag() == dwarf::DW_TAG_namespace;
298 bool DIDescriptor::isLexicalBlockFile() const {
299 return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
300 DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 2;
303 bool DIDescriptor::isLexicalBlock() const {
304 // FIXME: There are always exactly 4 header fields in DILexicalBlock, but
305 // something relies on this returning true for DILexicalBlockFile.
306 return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
307 DbgNode->getNumOperands() == 3 &&
308 (getNumHeaderFields() == 2 || getNumHeaderFields() == 4);
311 bool DIDescriptor::isSubrange() const {
312 return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
315 bool DIDescriptor::isEnumerator() const {
316 return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
319 bool DIDescriptor::isObjCProperty() const {
320 return DbgNode && getTag() == dwarf::DW_TAG_APPLE_property;
323 bool DIDescriptor::isImportedEntity() const {
324 return DbgNode && (getTag() == dwarf::DW_TAG_imported_module ||
325 getTag() == dwarf::DW_TAG_imported_declaration);
328 bool DIDescriptor::isExpression() const {
329 return DbgNode && (getTag() == dwarf::DW_TAG_expression);
332 //===----------------------------------------------------------------------===//
333 // Simple Descriptor Constructors and other Methods
334 //===----------------------------------------------------------------------===//
336 void DIDescriptor::replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D) {
338 assert(DbgNode && "Trying to replace an unverified type!");
340 // Since we use a TrackingVH for the node, its easy for clients to manufacture
341 // legitimate situations where they want to replaceAllUsesWith() on something
342 // which, due to uniquing, has merged with the source. We shield clients from
343 // this detail by allowing a value to be replaced with replaceAllUsesWith()
345 const MDNode *DN = D;
347 SmallVector<Metadata *, 10> Ops(DbgNode->op_begin(), DbgNode->op_end());
348 DN = MDNode::get(VMContext, Ops);
351 assert(DbgNode->isTemporary() && "Expected temporary node");
352 auto *Node = const_cast<MDNode *>(DbgNode);
353 Node->replaceAllUsesWith(const_cast<MDNode *>(DN));
354 MDNode::deleteTemporary(Node);
358 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
359 assert(DbgNode && "Trying to replace an unverified type!");
360 assert(DbgNode != D && "This replacement should always happen");
361 assert(DbgNode->isTemporary() && "Expected temporary node");
362 auto *Node = const_cast<MDNode *>(DbgNode);
363 Node->replaceAllUsesWith(D);
364 MDNode::deleteTemporary(Node);
367 bool DICompileUnit::Verify() const {
368 if (!isCompileUnit())
371 // Don't bother verifying the compilation directory or producer string
372 // as those could be empty.
373 if (getFilename().empty())
376 return DbgNode->getNumOperands() == 7 && getNumHeaderFields() == 8;
379 bool DIObjCProperty::Verify() const {
380 if (!isObjCProperty())
383 // Don't worry about the rest of the strings for now.
384 return DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 6;
387 /// \brief Check if a field at position Elt of a MDNode is a MDNode.
388 static bool fieldIsMDNode(const MDNode *DbgNode, unsigned Elt) {
389 Metadata *Fld = getField(DbgNode, Elt);
390 return !Fld || isa<MDNode>(Fld);
393 /// \brief Check if a field at position Elt of a MDNode is a MDString.
394 static bool fieldIsMDString(const MDNode *DbgNode, unsigned Elt) {
395 Metadata *Fld = getField(DbgNode, Elt);
396 return !Fld || isa<MDString>(Fld);
399 /// \brief Check if a value can be a reference to a type.
400 static bool isTypeRef(const Metadata *MD) {
403 if (auto *S = dyn_cast<MDString>(MD))
404 return !S->getString().empty();
405 if (auto *N = dyn_cast<MDNode>(MD))
406 return DIType(N).isType();
410 /// \brief Check if referenced field might be a type.
411 static bool fieldIsTypeRef(const MDNode *DbgNode, unsigned Elt) {
412 return isTypeRef(dyn_cast_or_null<Metadata>(getField(DbgNode, Elt)));
415 /// \brief Check if a value can be a ScopeRef.
416 static bool isScopeRef(const Metadata *MD) {
419 if (auto *S = dyn_cast<MDString>(MD))
420 return !S->getString().empty();
421 return isa<MDNode>(MD);
424 /// \brief Check if a field at position Elt of a MDNode can be a ScopeRef.
425 static bool fieldIsScopeRef(const MDNode *DbgNode, unsigned Elt) {
426 return isScopeRef(dyn_cast_or_null<Metadata>(getField(DbgNode, Elt)));
429 bool DIType::Verify() const {
432 // Make sure Context @ field 2 is MDNode.
433 if (!fieldIsScopeRef(DbgNode, 2))
436 // FIXME: Sink this into the various subclass verifies.
437 uint16_t Tag = getTag();
438 if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
439 Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
440 Tag != dwarf::DW_TAG_ptr_to_member_type &&
441 Tag != dwarf::DW_TAG_reference_type &&
442 Tag != dwarf::DW_TAG_rvalue_reference_type &&
443 Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
444 Tag != dwarf::DW_TAG_enumeration_type &&
445 Tag != dwarf::DW_TAG_subroutine_type &&
446 Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
447 getFilename().empty())
450 // DIType is abstract, it should be a BasicType, a DerivedType or
453 return DIBasicType(DbgNode).Verify();
454 else if (isCompositeType())
455 return DICompositeType(DbgNode).Verify();
456 else if (isDerivedType())
457 return DIDerivedType(DbgNode).Verify();
462 bool DIBasicType::Verify() const {
463 return isBasicType() && DbgNode->getNumOperands() == 3 &&
464 getNumHeaderFields() == 8;
467 bool DIDerivedType::Verify() const {
468 // Make sure DerivedFrom @ field 3 is TypeRef.
469 if (!fieldIsTypeRef(DbgNode, 3))
471 if (getTag() == dwarf::DW_TAG_ptr_to_member_type)
472 // Make sure ClassType @ field 4 is a TypeRef.
473 if (!fieldIsTypeRef(DbgNode, 4))
476 return isDerivedType() && DbgNode->getNumOperands() >= 4 &&
477 DbgNode->getNumOperands() <= 8 && getNumHeaderFields() >= 7 &&
478 getNumHeaderFields() <= 8;
481 bool DICompositeType::Verify() const {
482 if (!isCompositeType())
485 // Make sure DerivedFrom @ field 3 and ContainingType @ field 5 are TypeRef.
486 if (!fieldIsTypeRef(DbgNode, 3))
488 if (!fieldIsTypeRef(DbgNode, 5))
491 // Make sure the type identifier at field 7 is MDString, it can be null.
492 if (!fieldIsMDString(DbgNode, 7))
495 // A subroutine type can't be both & and &&.
496 if (isLValueReference() && isRValueReference())
499 return DbgNode->getNumOperands() == 8 && getNumHeaderFields() == 8;
502 bool DISubprogram::Verify() const {
506 // Make sure context @ field 2 is a ScopeRef and type @ field 3 is a MDNode.
507 if (!fieldIsScopeRef(DbgNode, 2))
509 if (!fieldIsMDNode(DbgNode, 3))
511 // Containing type @ field 4.
512 if (!fieldIsTypeRef(DbgNode, 4))
515 // A subprogram can't be both & and &&.
516 if (isLValueReference() && isRValueReference())
519 // If a DISubprogram has an llvm::Function*, then scope chains from all
520 // instructions within the function should lead to this DISubprogram.
521 if (auto *F = getFunction()) {
522 for (auto &BB : *F) {
524 DebugLoc DL = I.getDebugLoc();
528 MDNode *Scope = nullptr;
529 MDNode *IA = nullptr;
530 // walk the inlined-at scopes
531 while ((IA = DL.getInlinedAt()))
532 DL = DebugLoc::getFromDILocation(IA);
533 DL.getScopeAndInlinedAt(Scope, IA);
537 while (!DIDescriptor(Scope).isSubprogram()) {
538 DILexicalBlockFile D(Scope);
539 Scope = D.isLexicalBlockFile()
541 : DebugLoc::getFromDILexicalBlock(Scope).getScope();
545 if (!DISubprogram(Scope).describes(F))
550 return DbgNode->getNumOperands() == 9 && getNumHeaderFields() == 12;
553 bool DIGlobalVariable::Verify() const {
554 if (!isGlobalVariable())
557 if (getDisplayName().empty())
559 // Make sure context @ field 1 is an MDNode.
560 if (!fieldIsMDNode(DbgNode, 1))
562 // Make sure that type @ field 3 is a DITypeRef.
563 if (!fieldIsTypeRef(DbgNode, 3))
565 // Make sure StaticDataMemberDeclaration @ field 5 is MDNode.
566 if (!fieldIsMDNode(DbgNode, 5))
569 return DbgNode->getNumOperands() == 6 && getNumHeaderFields() == 7;
572 bool DIVariable::Verify() const {
576 // Make sure context @ field 1 is an MDNode.
577 if (!fieldIsMDNode(DbgNode, 1))
579 // Make sure that type @ field 3 is a DITypeRef.
580 if (!fieldIsTypeRef(DbgNode, 3))
583 // Check the number of header fields, which is common between complex and
585 if (getNumHeaderFields() != 4)
588 // Variable without an inline location.
589 if (DbgNode->getNumOperands() == 4)
592 // Variable with an inline location.
593 return getInlinedAt() != nullptr && DbgNode->getNumOperands() == 5;
596 bool DIExpression::Verify() const {
597 // Empty DIExpressions may be represented as a nullptr.
601 if (!(isExpression() && DbgNode->getNumOperands() == 1))
604 for (auto Op : *this)
606 case DW_OP_bit_piece:
607 // Must be the last element of the expression.
608 return std::distance(Op.getBase(), DIHeaderFieldIterator()) == 3;
610 if (std::distance(Op.getBase(), DIHeaderFieldIterator()) < 2)
616 // Other operators are not yet supported by the backend.
622 bool DILocation::Verify() const {
623 return DbgNode && isa<MDLocation>(DbgNode);
626 bool DINameSpace::Verify() const {
629 return DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 3;
632 MDNode *DIFile::getFileNode() const { return getNodeField(DbgNode, 1); }
634 bool DIFile::Verify() const {
635 return isFile() && DbgNode->getNumOperands() == 2;
638 bool DIEnumerator::Verify() const {
639 return isEnumerator() && DbgNode->getNumOperands() == 1 &&
640 getNumHeaderFields() == 3;
643 bool DISubrange::Verify() const {
644 return isSubrange() && DbgNode->getNumOperands() == 1 &&
645 getNumHeaderFields() == 3;
648 bool DILexicalBlock::Verify() const {
649 return isLexicalBlock() && DbgNode->getNumOperands() == 3 &&
650 getNumHeaderFields() == 4;
653 bool DILexicalBlockFile::Verify() const {
654 return isLexicalBlockFile() && DbgNode->getNumOperands() == 3 &&
655 getNumHeaderFields() == 2;
658 bool DITemplateTypeParameter::Verify() const {
659 return isTemplateTypeParameter() && DbgNode->getNumOperands() == 4 &&
660 getNumHeaderFields() == 4;
663 bool DITemplateValueParameter::Verify() const {
664 return isTemplateValueParameter() && DbgNode->getNumOperands() == 5 &&
665 getNumHeaderFields() == 4;
668 bool DIImportedEntity::Verify() const {
669 return isImportedEntity() && DbgNode->getNumOperands() == 3 &&
670 getNumHeaderFields() == 3;
673 MDNode *DIDerivedType::getObjCProperty() const {
674 return getNodeField(DbgNode, 4);
677 MDString *DICompositeType::getIdentifier() const {
678 return cast_or_null<MDString>(getField(DbgNode, 7));
682 static void VerifySubsetOf(const MDNode *LHS, const MDNode *RHS) {
683 for (unsigned i = 0; i != LHS->getNumOperands(); ++i) {
684 // Skip the 'empty' list (that's a single i32 0, rather than truly empty).
685 if (i == 0 && mdconst::hasa<ConstantInt>(LHS->getOperand(i)))
687 const MDNode *E = cast<MDNode>(LHS->getOperand(i));
689 for (unsigned j = 0; !found && j != RHS->getNumOperands(); ++j)
690 found = (E == cast<MDNode>(RHS->getOperand(j)));
691 assert(found && "Losing a member during member list replacement");
696 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
697 TrackingMDNodeRef N(*this);
700 // Check that the new list of members contains all the old members as well.
701 if (const MDNode *El = cast_or_null<MDNode>(N->getOperand(4)))
702 VerifySubsetOf(El, Elements);
704 N->replaceOperandWith(4, Elements);
707 N->replaceOperandWith(6, TParams);
711 DIScopeRef DIScope::getRef() const {
712 if (!isCompositeType())
713 return DIScopeRef(*this);
714 DICompositeType DTy(DbgNode);
715 if (!DTy.getIdentifier())
716 return DIScopeRef(*this);
717 return DIScopeRef(DTy.getIdentifier());
720 void DICompositeType::setContainingType(DICompositeType ContainingType) {
721 TrackingMDNodeRef N(*this);
722 N->replaceOperandWith(5, ContainingType.getRef());
726 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
727 assert(CurFn && "Invalid function");
728 if (!getContext().isSubprogram())
730 // This variable is not inlined function argument if its scope
731 // does not describe current function.
732 return !DISubprogram(getContext()).describes(CurFn);
735 bool DISubprogram::describes(const Function *F) {
736 assert(F && "Invalid function");
737 if (F == getFunction())
739 StringRef Name = getLinkageName();
742 if (F->getName() == Name)
747 MDNode *DISubprogram::getVariablesNodes() const {
748 return getNodeField(DbgNode, 8);
751 DIArray DISubprogram::getVariables() const {
752 return DIArray(getNodeField(DbgNode, 8));
755 Metadata *DITemplateValueParameter::getValue() const {
756 return DbgNode->getOperand(3);
759 DIScopeRef DIScope::getContext() const {
762 return DIType(DbgNode).getContext();
765 return DIScopeRef(DISubprogram(DbgNode).getContext());
767 if (isLexicalBlock())
768 return DIScopeRef(DILexicalBlock(DbgNode).getContext());
770 if (isLexicalBlockFile())
771 return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
774 return DIScopeRef(DINameSpace(DbgNode).getContext());
776 assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
777 return DIScopeRef(nullptr);
780 StringRef DIScope::getName() const {
782 return DIType(DbgNode).getName();
784 return DISubprogram(DbgNode).getName();
786 return DINameSpace(DbgNode).getName();
787 assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
789 "Unhandled type of scope.");
793 StringRef DIScope::getFilename() const {
796 return ::getStringField(getNodeField(DbgNode, 1), 0);
799 StringRef DIScope::getDirectory() const {
802 return ::getStringField(getNodeField(DbgNode, 1), 1);
805 DIArray DICompileUnit::getEnumTypes() const {
806 if (!DbgNode || DbgNode->getNumOperands() < 7)
809 return DIArray(getNodeField(DbgNode, 2));
812 DIArray DICompileUnit::getRetainedTypes() const {
813 if (!DbgNode || DbgNode->getNumOperands() < 7)
816 return DIArray(getNodeField(DbgNode, 3));
819 DIArray DICompileUnit::getSubprograms() const {
820 if (!DbgNode || DbgNode->getNumOperands() < 7)
823 return DIArray(getNodeField(DbgNode, 4));
826 DIArray DICompileUnit::getGlobalVariables() const {
827 if (!DbgNode || DbgNode->getNumOperands() < 7)
830 return DIArray(getNodeField(DbgNode, 5));
833 DIArray DICompileUnit::getImportedEntities() const {
834 if (!DbgNode || DbgNode->getNumOperands() < 7)
837 return DIArray(getNodeField(DbgNode, 6));
840 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
841 assert(Verify() && "Expected compile unit");
842 if (Subprograms == getSubprograms())
845 const_cast<MDNode *>(DbgNode)->replaceOperandWith(4, Subprograms);
848 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
849 assert(Verify() && "Expected compile unit");
850 if (GlobalVariables == getGlobalVariables())
853 const_cast<MDNode *>(DbgNode)->replaceOperandWith(5, GlobalVariables);
856 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
857 DILexicalBlockFile NewScope) {
859 assert(NewScope && "Expected valid scope");
861 const auto *Old = cast<MDLocation>(DbgNode);
862 return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
863 NewScope, Old->getInlinedAt()));
866 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
867 std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
868 return ++Ctx.pImpl->DiscriminatorTable[Key];
871 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
872 LLVMContext &VMContext) {
873 assert(DIVariable(DV).Verify() && "Expected a DIVariable");
875 return cleanseInlinedVariable(DV, VMContext);
877 // Insert inlined scope.
878 SmallVector<Metadata *, 8> Elts(DV->op_begin(),
879 DV->op_begin() + DIVariableInlinedAtIndex);
880 Elts.push_back(InlinedScope);
882 DIVariable Inlined(MDNode::get(VMContext, Elts));
883 assert(Inlined.Verify() && "Expected to create a DIVariable");
887 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
888 assert(DIVariable(DV).Verify() && "Expected a DIVariable");
889 if (!DIVariable(DV).getInlinedAt())
890 return DIVariable(DV);
892 // Remove inlined scope.
893 SmallVector<Metadata *, 8> Elts(DV->op_begin(),
894 DV->op_begin() + DIVariableInlinedAtIndex);
896 DIVariable Cleansed(MDNode::get(VMContext, Elts));
897 assert(Cleansed.Verify() && "Expected to create a DIVariable");
901 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
902 DIDescriptor D(Scope);
903 if (D.isSubprogram())
904 return DISubprogram(Scope);
906 if (D.isLexicalBlockFile())
907 return getDISubprogram(DILexicalBlockFile(Scope).getContext());
909 if (D.isLexicalBlock())
910 return getDISubprogram(DILexicalBlock(Scope).getContext());
912 return DISubprogram();
915 DISubprogram llvm::getDISubprogram(const Function *F) {
916 // We look for the first instr that has a debug annotation leading back to F.
917 for (auto &BB : *F) {
918 auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
919 return !Inst.getDebugLoc().isUnknown();
921 if (Inst == BB.end())
923 DebugLoc DLoc = Inst->getDebugLoc();
924 const MDNode *Scope = DLoc.getScopeNode();
925 DISubprogram Subprogram = getDISubprogram(Scope);
926 return Subprogram.describes(F) ? Subprogram : DISubprogram();
929 return DISubprogram();
932 DICompositeType llvm::getDICompositeType(DIType T) {
933 if (T.isCompositeType())
934 return DICompositeType(T);
936 if (T.isDerivedType()) {
937 // This function is currently used by dragonegg and dragonegg does
938 // not generate identifier for types, so using an empty map to resolve
939 // DerivedFrom should be fine.
940 DITypeIdentifierMap EmptyMap;
941 return getDICompositeType(
942 DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
945 return DICompositeType();
949 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
950 DITypeIdentifierMap Map;
951 for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
952 DICompileUnit CU(CU_Nodes->getOperand(CUi));
953 DIArray Retain = CU.getRetainedTypes();
954 for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
955 if (!Retain.getElement(Ti).isCompositeType())
957 DICompositeType Ty(Retain.getElement(Ti));
958 if (MDString *TypeId = Ty.getIdentifier()) {
959 // Definition has priority over declaration.
960 // Try to insert (TypeId, Ty) to Map.
961 std::pair<DITypeIdentifierMap::iterator, bool> P =
962 Map.insert(std::make_pair(TypeId, Ty));
963 // If TypeId already exists in Map and this is a definition, replace
964 // whatever we had (declaration or definition) with the definition.
965 if (!P.second && !Ty.isForwardDecl())
966 P.first->second = Ty;
973 //===----------------------------------------------------------------------===//
974 // DebugInfoFinder implementations.
975 //===----------------------------------------------------------------------===//
977 void DebugInfoFinder::reset() {
984 TypeIdentifierMap.clear();
985 TypeMapInitialized = false;
988 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
989 if (!TypeMapInitialized)
990 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
991 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
992 TypeMapInitialized = true;
996 void DebugInfoFinder::processModule(const Module &M) {
997 InitializeTypeMap(M);
998 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
999 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
1000 DICompileUnit CU(CU_Nodes->getOperand(i));
1002 DIArray GVs = CU.getGlobalVariables();
1003 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
1004 DIGlobalVariable DIG(GVs.getElement(i));
1005 if (addGlobalVariable(DIG)) {
1006 processScope(DIG.getContext());
1007 processType(DIG.getType().resolve(TypeIdentifierMap));
1010 DIArray SPs = CU.getSubprograms();
1011 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
1012 processSubprogram(DISubprogram(SPs.getElement(i)));
1013 DIArray EnumTypes = CU.getEnumTypes();
1014 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
1015 processType(DIType(EnumTypes.getElement(i)));
1016 DIArray RetainedTypes = CU.getRetainedTypes();
1017 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
1018 processType(DIType(RetainedTypes.getElement(i)));
1019 DIArray Imports = CU.getImportedEntities();
1020 for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
1021 DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
1022 DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
1023 if (Entity.isType())
1024 processType(DIType(Entity));
1025 else if (Entity.isSubprogram())
1026 processSubprogram(DISubprogram(Entity));
1027 else if (Entity.isNameSpace())
1028 processScope(DINameSpace(Entity).getContext());
1034 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
1037 InitializeTypeMap(M);
1038 processScope(Loc.getScope());
1039 processLocation(M, Loc.getOrigLocation());
1042 void DebugInfoFinder::processType(DIType DT) {
1045 processScope(DT.getContext().resolve(TypeIdentifierMap));
1046 if (DT.isCompositeType()) {
1047 DICompositeType DCT(DT);
1048 processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1049 if (DT.isSubroutineType()) {
1050 DITypeArray DTA = DISubroutineType(DT).getTypeArray();
1051 for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
1052 processType(DTA.getElement(i).resolve(TypeIdentifierMap));
1055 DIArray DA = DCT.getElements();
1056 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1057 DIDescriptor D = DA.getElement(i);
1059 processType(DIType(D));
1060 else if (D.isSubprogram())
1061 processSubprogram(DISubprogram(D));
1063 } else if (DT.isDerivedType()) {
1064 DIDerivedType DDT(DT);
1065 processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1069 void DebugInfoFinder::processScope(DIScope Scope) {
1070 if (Scope.isType()) {
1075 if (Scope.isCompileUnit()) {
1076 addCompileUnit(DICompileUnit(Scope));
1079 if (Scope.isSubprogram()) {
1080 processSubprogram(DISubprogram(Scope));
1083 if (!addScope(Scope))
1085 if (Scope.isLexicalBlock()) {
1086 DILexicalBlock LB(Scope);
1087 processScope(LB.getContext());
1088 } else if (Scope.isLexicalBlockFile()) {
1089 DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
1090 processScope(LBF.getScope());
1091 } else if (Scope.isNameSpace()) {
1092 DINameSpace NS(Scope);
1093 processScope(NS.getContext());
1097 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1098 if (!addSubprogram(SP))
1100 processScope(SP.getContext().resolve(TypeIdentifierMap));
1101 processType(SP.getType());
1102 DIArray TParams = SP.getTemplateParams();
1103 for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
1104 DIDescriptor Element = TParams.getElement(I);
1105 if (Element.isTemplateTypeParameter()) {
1106 DITemplateTypeParameter TType(Element);
1107 processScope(TType.getContext().resolve(TypeIdentifierMap));
1108 processType(TType.getType().resolve(TypeIdentifierMap));
1109 } else if (Element.isTemplateValueParameter()) {
1110 DITemplateValueParameter TVal(Element);
1111 processScope(TVal.getContext().resolve(TypeIdentifierMap));
1112 processType(TVal.getType().resolve(TypeIdentifierMap));
1117 void DebugInfoFinder::processDeclare(const Module &M,
1118 const DbgDeclareInst *DDI) {
1119 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1122 InitializeTypeMap(M);
1125 if (!DV.isVariable())
1128 if (!NodesSeen.insert(DV).second)
1130 processScope(DIVariable(N).getContext());
1131 processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1134 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
1135 MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
1138 InitializeTypeMap(M);
1141 if (!DV.isVariable())
1144 if (!NodesSeen.insert(DV).second)
1146 processScope(DIVariable(N).getContext());
1147 processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1150 bool DebugInfoFinder::addType(DIType DT) {
1154 if (!NodesSeen.insert(DT).second)
1161 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1164 if (!NodesSeen.insert(CU).second)
1171 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1175 if (!NodesSeen.insert(DIG).second)
1182 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1186 if (!NodesSeen.insert(SP).second)
1193 bool DebugInfoFinder::addScope(DIScope Scope) {
1196 // FIXME: Ocaml binding generates a scope with no content, we treat it
1198 if (Scope->getNumOperands() == 0)
1200 if (!NodesSeen.insert(Scope).second)
1202 Scopes.push_back(Scope);
1206 //===----------------------------------------------------------------------===//
1207 // DIDescriptor: dump routines for all descriptors.
1208 //===----------------------------------------------------------------------===//
1210 void DIDescriptor::dump() const {
1215 void DIDescriptor::print(raw_ostream &OS) const {
1219 if (const char *Tag = dwarf::TagString(getTag()))
1220 OS << "[ " << Tag << " ]";
1222 if (this->isSubrange()) {
1223 DISubrange(DbgNode).printInternal(OS);
1224 } else if (this->isCompileUnit()) {
1225 DICompileUnit(DbgNode).printInternal(OS);
1226 } else if (this->isFile()) {
1227 DIFile(DbgNode).printInternal(OS);
1228 } else if (this->isEnumerator()) {
1229 DIEnumerator(DbgNode).printInternal(OS);
1230 } else if (this->isBasicType()) {
1231 DIType(DbgNode).printInternal(OS);
1232 } else if (this->isDerivedType()) {
1233 DIDerivedType(DbgNode).printInternal(OS);
1234 } else if (this->isCompositeType()) {
1235 DICompositeType(DbgNode).printInternal(OS);
1236 } else if (this->isSubprogram()) {
1237 DISubprogram(DbgNode).printInternal(OS);
1238 } else if (this->isGlobalVariable()) {
1239 DIGlobalVariable(DbgNode).printInternal(OS);
1240 } else if (this->isVariable()) {
1241 DIVariable(DbgNode).printInternal(OS);
1242 } else if (this->isObjCProperty()) {
1243 DIObjCProperty(DbgNode).printInternal(OS);
1244 } else if (this->isNameSpace()) {
1245 DINameSpace(DbgNode).printInternal(OS);
1246 } else if (this->isScope()) {
1247 DIScope(DbgNode).printInternal(OS);
1248 } else if (this->isExpression()) {
1249 DIExpression(DbgNode).printInternal(OS);
1253 void DISubrange::printInternal(raw_ostream &OS) const {
1254 int64_t Count = getCount();
1256 OS << " [" << getLo() << ", " << Count - 1 << ']';
1258 OS << " [unbounded]";
1261 void DIScope::printInternal(raw_ostream &OS) const {
1262 OS << " [" << getDirectory() << "/" << getFilename() << ']';
1265 void DICompileUnit::printInternal(raw_ostream &OS) const {
1266 DIScope::printInternal(OS);
1268 unsigned Lang = getLanguage();
1269 if (const char *LangStr = dwarf::LanguageString(Lang))
1272 (OS << "lang 0x").write_hex(Lang);
1276 void DIEnumerator::printInternal(raw_ostream &OS) const {
1277 OS << " [" << getName() << " :: " << getEnumValue() << ']';
1280 void DIType::printInternal(raw_ostream &OS) const {
1284 StringRef Res = getName();
1286 OS << " [" << Res << "]";
1288 // TODO: Print context?
1290 OS << " [line " << getLineNumber() << ", size " << getSizeInBits()
1291 << ", align " << getAlignInBits() << ", offset " << getOffsetInBits();
1293 if (const char *Enc =
1294 dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
1295 OS << ", enc " << Enc;
1300 else if (isProtected())
1301 OS << " [protected]";
1302 else if (isPublic())
1306 OS << " [artificial]";
1308 if (isForwardDecl())
1310 else if (getTag() == dwarf::DW_TAG_structure_type ||
1311 getTag() == dwarf::DW_TAG_union_type ||
1312 getTag() == dwarf::DW_TAG_enumeration_type ||
1313 getTag() == dwarf::DW_TAG_class_type)
1317 if (isStaticMember())
1320 if (isLValueReference())
1321 OS << " [reference]";
1323 if (isRValueReference())
1324 OS << " [rvalue reference]";
1327 void DIDerivedType::printInternal(raw_ostream &OS) const {
1328 DIType::printInternal(OS);
1329 OS << " [from " << getTypeDerivedFrom().getName() << ']';
1332 void DICompositeType::printInternal(raw_ostream &OS) const {
1333 DIType::printInternal(OS);
1334 DIArray A = getElements();
1335 OS << " [" << A.getNumElements() << " elements]";
1338 void DINameSpace::printInternal(raw_ostream &OS) const {
1339 StringRef Name = getName();
1341 OS << " [" << Name << ']';
1343 OS << " [line " << getLineNumber() << ']';
1346 void DISubprogram::printInternal(raw_ostream &OS) const {
1347 // TODO : Print context
1348 OS << " [line " << getLineNumber() << ']';
1350 if (isLocalToUnit())
1356 if (getScopeLineNumber() != getLineNumber())
1357 OS << " [scope " << getScopeLineNumber() << "]";
1361 else if (isProtected())
1362 OS << " [protected]";
1363 else if (isPublic())
1366 if (isLValueReference())
1367 OS << " [reference]";
1369 if (isRValueReference())
1370 OS << " [rvalue reference]";
1372 StringRef Res = getName();
1374 OS << " [" << Res << ']';
1377 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
1378 StringRef Res = getName();
1380 OS << " [" << Res << ']';
1382 OS << " [line " << getLineNumber() << ']';
1384 // TODO : Print context
1386 if (isLocalToUnit())
1393 void DIVariable::printInternal(raw_ostream &OS) const {
1394 StringRef Res = getName();
1396 OS << " [" << Res << ']';
1398 OS << " [line " << getLineNumber() << ']';
1401 void DIExpression::printInternal(raw_ostream &OS) const {
1402 for (auto Op : *this) {
1403 OS << " [" << OperationEncodingString(Op);
1406 OS << " " << Op.getArg(1);
1409 case DW_OP_bit_piece: {
1410 OS << " offset=" << Op.getArg(1) << ", size=" << Op.getArg(2);
1417 llvm_unreachable("unhandled operation");
1423 void DIObjCProperty::printInternal(raw_ostream &OS) const {
1424 StringRef Name = getObjCPropertyName();
1426 OS << " [" << Name << ']';
1428 OS << " [line " << getLineNumber() << ", properties " << getUnsignedField(6)
1432 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
1433 const LLVMContext &Ctx) {
1434 if (!DL.isUnknown()) { // Print source line info.
1435 DIScope Scope(DL.getScope(Ctx));
1436 assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
1437 // Omit the directory, because it's likely to be long and uninteresting.
1438 CommentOS << Scope.getFilename();
1439 CommentOS << ':' << DL.getLine();
1440 if (DL.getCol() != 0)
1441 CommentOS << ':' << DL.getCol();
1442 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1443 if (!InlinedAtDL.isUnknown()) {
1444 CommentOS << " @[ ";
1445 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
1451 void DIVariable::printExtendedName(raw_ostream &OS) const {
1452 const LLVMContext &Ctx = DbgNode->getContext();
1453 StringRef Res = getName();
1455 OS << Res << "," << getLineNumber();
1456 if (MDNode *InlinedAt = getInlinedAt()) {
1457 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1458 if (!InlinedAtDL.isUnknown()) {
1460 printDebugLoc(InlinedAtDL, OS, Ctx);
1466 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
1467 assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
1469 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
1470 assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
1474 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
1475 return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
1477 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
1478 return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
1481 bool llvm::StripDebugInfo(Module &M) {
1482 bool Changed = false;
1484 // Remove all of the calls to the debugger intrinsics, and remove them from
1486 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
1487 while (!Declare->use_empty()) {
1488 CallInst *CI = cast<CallInst>(Declare->user_back());
1489 CI->eraseFromParent();
1491 Declare->eraseFromParent();
1495 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
1496 while (!DbgVal->use_empty()) {
1497 CallInst *CI = cast<CallInst>(DbgVal->user_back());
1498 CI->eraseFromParent();
1500 DbgVal->eraseFromParent();
1504 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
1505 NME = M.named_metadata_end(); NMI != NME;) {
1506 NamedMDNode *NMD = NMI;
1508 if (NMD->getName().startswith("llvm.dbg.")) {
1509 NMD->eraseFromParent();
1514 for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
1515 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
1517 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
1519 if (!BI->getDebugLoc().isUnknown()) {
1521 BI->setDebugLoc(DebugLoc());
1528 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
1529 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
1530 M.getModuleFlag("Debug Info Version")))
1531 return Val->getZExtValue();
1535 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
1536 llvm::makeSubprogramMap(const Module &M) {
1537 DenseMap<const Function *, DISubprogram> R;
1539 NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
1543 for (MDNode *N : CU_Nodes->operands()) {
1544 DICompileUnit CUNode(N);
1545 DIArray SPs = CUNode.getSubprograms();
1546 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
1547 DISubprogram SP(SPs.getElement(i));
1548 if (Function *F = SP.getFunction())
1549 R.insert(std::make_pair(F, SP));