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/ADT/StringSwitch.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DIBuilder.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/ValueHandle.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Dwarf.h"
32 #include "llvm/Support/raw_ostream.h"
34 using namespace llvm::dwarf;
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 unsigned DIDescriptor::getFlag(StringRef Flag) {
41 return StringSwitch<unsigned>(Flag)
42 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
43 #include "llvm/IR/DebugInfoFlags.def"
47 const char *DIDescriptor::getFlagString(unsigned Flag) {
51 #define HANDLE_DI_FLAG(ID, NAME) \
53 return "DIFlag" #NAME;
54 #include "llvm/IR/DebugInfoFlags.def"
58 unsigned DIDescriptor::splitFlags(unsigned Flags,
59 SmallVectorImpl<unsigned> &SplitFlags) {
60 // Accessibility flags need to be specially handled, since they're packed
62 if (unsigned A = Flags & FlagAccessibility) {
64 SplitFlags.push_back(FlagPrivate);
65 else if (A == FlagProtected)
66 SplitFlags.push_back(FlagProtected);
68 SplitFlags.push_back(FlagPublic);
72 #define HANDLE_DI_FLAG(ID, NAME) \
73 if (unsigned Bit = Flags & ID) { \
74 SplitFlags.push_back(Bit); \
77 #include "llvm/IR/DebugInfoFlags.def"
82 bool DIDescriptor::Verify() const {
84 (DIDerivedType(DbgNode).Verify() ||
85 DICompositeType(DbgNode).Verify() || DIBasicType(DbgNode).Verify() ||
86 DIVariable(DbgNode).Verify() || DISubprogram(DbgNode).Verify() ||
87 DIGlobalVariable(DbgNode).Verify() || DIFile(DbgNode).Verify() ||
88 DICompileUnit(DbgNode).Verify() || DINameSpace(DbgNode).Verify() ||
89 DILexicalBlock(DbgNode).Verify() ||
90 DILexicalBlockFile(DbgNode).Verify() ||
91 DISubrange(DbgNode).Verify() || DIEnumerator(DbgNode).Verify() ||
92 DIObjCProperty(DbgNode).Verify() ||
93 DITemplateTypeParameter(DbgNode).Verify() ||
94 DITemplateValueParameter(DbgNode).Verify() ||
95 DIImportedEntity(DbgNode).Verify() || DIExpression(DbgNode).Verify());
98 static Metadata *getField(const MDNode *DbgNode, unsigned Elt) {
99 if (!DbgNode || Elt >= DbgNode->getNumOperands())
101 return DbgNode->getOperand(Elt);
104 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
105 return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
108 static StringRef getStringField(const MDNode *DbgNode, unsigned Elt) {
109 if (MDString *MDS = dyn_cast_or_null<MDString>(getField(DbgNode, Elt)))
110 return MDS->getString();
114 StringRef DIDescriptor::getStringField(unsigned Elt) const {
115 return ::getStringField(DbgNode, Elt);
118 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
119 if (auto *C = getConstantField(Elt))
120 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
121 return CI->getZExtValue();
126 int64_t DIDescriptor::getInt64Field(unsigned Elt) const {
127 if (auto *C = getConstantField(Elt))
128 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
129 return CI->getZExtValue();
134 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
135 MDNode *Field = getNodeField(DbgNode, Elt);
136 return DIDescriptor(Field);
139 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
140 return dyn_cast_or_null<GlobalVariable>(getConstantField(Elt));
143 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
147 if (Elt < DbgNode->getNumOperands())
149 dyn_cast_or_null<ConstantAsMetadata>(DbgNode->getOperand(Elt)))
150 return C->getValue();
154 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
155 return dyn_cast_or_null<Function>(getConstantField(Elt));
158 /// \brief Return the size reported by the variable's type.
159 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
160 DIType Ty = getType().resolve(Map);
161 // Follow derived types until we reach a type that
162 // reports back a size.
163 while (Ty.isDerivedType() && !Ty.getSizeInBits()) {
164 DIDerivedType DT(&*Ty);
165 Ty = DT.getTypeDerivedFrom().resolve(Map);
167 assert(Ty.getSizeInBits() && "type with size 0");
168 return Ty.getSizeInBits();
171 bool DIExpression::isBitPiece() const {
172 unsigned N = getNumElements();
173 return N >=3 && getElement(N-3) == dwarf::DW_OP_bit_piece;
176 uint64_t DIExpression::getBitPieceOffset() const {
177 assert(isBitPiece() && "not a piece");
178 return getElement(getNumElements()-2);
181 uint64_t DIExpression::getBitPieceSize() const {
182 assert(isBitPiece() && "not a piece");
183 return getElement(getNumElements()-1);
186 DIExpression::iterator DIExpression::Operand::getNext() const {
191 //===----------------------------------------------------------------------===//
192 // Simple Descriptor Constructors and other Methods
193 //===----------------------------------------------------------------------===//
195 void DIDescriptor::replaceAllUsesWith(LLVMContext &, DIDescriptor D) {
196 assert(DbgNode && "Trying to replace an unverified type!");
197 assert(DbgNode->isTemporary() && "Expected temporary node");
198 TempMDNode Temp(get());
200 // Since we use a TrackingVH for the node, its easy for clients to manufacture
201 // legitimate situations where they want to replaceAllUsesWith() on something
202 // which, due to uniquing, has merged with the source. We shield clients from
203 // this detail by allowing a value to be replaced with replaceAllUsesWith()
205 if (Temp.get() == D.get()) {
206 DbgNode = MDNode::replaceWithUniqued(std::move(Temp));
210 Temp->replaceAllUsesWith(D.get());
214 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
215 assert(DbgNode && "Trying to replace an unverified type!");
216 assert(DbgNode != D && "This replacement should always happen");
217 assert(DbgNode->isTemporary() && "Expected temporary node");
218 TempMDNode Node(get());
219 Node->replaceAllUsesWith(D);
222 bool DICompileUnit::Verify() const {
223 if (!isCompileUnit())
226 // Don't bother verifying the compilation directory or producer string
227 // as those could be empty.
228 return !getFilename().empty();
231 bool DIObjCProperty::Verify() const { return isObjCProperty(); }
233 /// \brief Check if a value can be a reference to a type.
234 static bool isTypeRef(const Metadata *MD) {
237 if (auto *S = dyn_cast<MDString>(MD))
238 return !S->getString().empty();
239 return isa<MDType>(MD);
242 /// \brief Check if a value can be a ScopeRef.
243 static bool isScopeRef(const Metadata *MD) {
246 if (auto *S = dyn_cast<MDString>(MD))
247 return !S->getString().empty();
248 return isa<MDScope>(MD);
252 /// \brief Check if a value can be a DescriptorRef.
253 static bool isDescriptorRef(const Metadata *MD) {
256 if (auto *S = dyn_cast<MDString>(MD))
257 return !S->getString().empty();
258 return isa<MDNode>(MD);
262 bool DIType::Verify() const {
266 if (!isScopeRef(N->getScope()))
269 // DIType is abstract, it should be a BasicType, a DerivedType or
272 return DIBasicType(DbgNode).Verify();
274 // FIXME: Sink this into the various subclass verifies.
275 if (getFilename().empty()) {
276 // Check whether the filename is allowed to be empty.
277 uint16_t Tag = getTag();
278 if (Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
279 Tag != dwarf::DW_TAG_pointer_type &&
280 Tag != dwarf::DW_TAG_ptr_to_member_type &&
281 Tag != dwarf::DW_TAG_reference_type &&
282 Tag != dwarf::DW_TAG_rvalue_reference_type &&
283 Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
284 Tag != dwarf::DW_TAG_enumeration_type &&
285 Tag != dwarf::DW_TAG_subroutine_type &&
286 Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend)
290 if (isCompositeType())
291 return DICompositeType(DbgNode).Verify();
293 return DIDerivedType(DbgNode).Verify();
297 bool DIBasicType::Verify() const { return getRaw(); }
299 bool DIDerivedType::Verify() const {
303 if (getTag() == dwarf::DW_TAG_ptr_to_member_type) {
304 auto *D = dyn_cast<MDDerivedType>(N);
307 if (!isTypeRef(D->getExtraData()))
310 return isTypeRef(N->getBaseType());
313 bool DICompositeType::Verify() const {
315 return N && isTypeRef(N->getBaseType()) && isTypeRef(N->getVTableHolder()) &&
316 !(isLValueReference() && isRValueReference());
319 bool DISubprogram::Verify() const {
324 if (!isScopeRef(N->getScope()))
327 if (auto *Op = N->getType())
328 if (!isa<MDNode>(Op))
331 if (!isTypeRef(getContainingType()))
334 if (isLValueReference() && isRValueReference())
337 // If a DISubprogram has an llvm::Function*, then scope chains from all
338 // instructions within the function should lead to this DISubprogram.
339 if (auto *F = getFunction()) {
340 for (auto &BB : *F) {
342 DebugLoc DL = I.getDebugLoc();
346 MDNode *Scope = nullptr;
347 MDNode *IA = nullptr;
348 // walk the inlined-at scopes
349 while ((IA = DL.getInlinedAt()))
350 DL = DebugLoc::getFromDILocation(IA);
351 DL.getScopeAndInlinedAt(Scope, IA);
355 while (!DIDescriptor(Scope).isSubprogram()) {
356 DILexicalBlockFile D(Scope);
357 Scope = D.isLexicalBlockFile()
359 : DebugLoc::getFromDILexicalBlock(Scope).getScope();
363 if (!DISubprogram(Scope).describes(F))
372 bool DIGlobalVariable::Verify() const {
378 if (N->getDisplayName().empty())
381 if (auto *Op = N->getScope())
382 if (!isa<MDNode>(Op))
385 if (auto *Op = N->getStaticDataMemberDeclaration())
386 if (!isa<MDNode>(Op))
389 return isTypeRef(N->getType());
392 bool DIVariable::Verify() const {
398 if (auto *Op = N->getScope())
399 if (!isa<MDNode>(Op))
402 return isTypeRef(N->getType());
405 bool DIExpression::Verify() const {
406 // FIXME: This should return false if it's null!
408 return !N || N->isValid();
411 bool DILocation::Verify() const { return getRaw(); }
412 bool DINameSpace::Verify() const { return getRaw(); }
413 bool DIFile::Verify() const { return getRaw(); }
414 bool DIEnumerator::Verify() const { return getRaw(); }
415 bool DISubrange::Verify() const { return getRaw(); }
416 bool DILexicalBlock::Verify() const { return getRaw(); }
417 bool DILexicalBlockFile::Verify() const { return getRaw(); }
418 bool DITemplateTypeParameter::Verify() const { return getRaw(); }
419 bool DITemplateValueParameter::Verify() const { return getRaw(); }
420 bool DIImportedEntity::Verify() const { return getRaw(); }
422 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
423 TypedTrackingMDRef<MDCompositeTypeBase> N(getRaw());
425 N->replaceElements(cast<MDTuple>(Elements));
427 N->replaceTemplateParams(cast<MDTuple>(TParams));
431 DIScopeRef DIScope::getRef() const {
432 if (!isCompositeType())
433 return DIScopeRef(*this);
434 DICompositeType DTy(DbgNode);
435 if (!DTy.getIdentifier())
436 return DIScopeRef(*this);
437 return DIScopeRef(DTy.getIdentifier());
440 void DICompositeType::setContainingType(DICompositeType ContainingType) {
441 TypedTrackingMDRef<MDCompositeTypeBase> N(getRaw());
442 N->replaceVTableHolder(ContainingType.getRef());
446 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
447 assert(CurFn && "Invalid function");
448 if (!getContext().isSubprogram())
450 // This variable is not inlined function argument if its scope
451 // does not describe current function.
452 return !DISubprogram(getContext()).describes(CurFn);
455 Function *DISubprogram::getFunction() const {
456 if (auto *N = getRaw())
457 if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getFunction()))
458 return dyn_cast<Function>(C->getValue());
462 bool DISubprogram::describes(const Function *F) {
463 assert(F && "Invalid function");
464 if (F == getFunction())
466 StringRef Name = getLinkageName();
469 if (F->getName() == Name)
474 GlobalVariable *DIGlobalVariable::getGlobal() const {
475 return dyn_cast_or_null<GlobalVariable>(getConstant());
478 DIScopeRef DIScope::getContext() const {
481 return DIType(DbgNode).getContext();
484 return DIScopeRef(DISubprogram(DbgNode).getContext());
486 if (isLexicalBlock())
487 return DIScopeRef(DILexicalBlock(DbgNode).getContext());
489 if (isLexicalBlockFile())
490 return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
493 return DIScopeRef(DINameSpace(DbgNode).getContext());
495 assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
496 return DIScopeRef(nullptr);
499 StringRef DIScope::getName() const {
501 return DIType(DbgNode).getName();
503 return DISubprogram(DbgNode).getName();
505 return DINameSpace(DbgNode).getName();
506 assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
508 "Unhandled type of scope.");
512 StringRef DIScope::getFilename() const {
513 if (auto *N = getRaw())
514 return ::getStringField(dyn_cast_or_null<MDNode>(N->getFile()), 0);
518 StringRef DIScope::getDirectory() const {
519 if (auto *N = getRaw())
520 return ::getStringField(dyn_cast_or_null<MDNode>(N->getFile()), 1);
524 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
525 assert(Verify() && "Expected compile unit");
526 getRaw()->replaceSubprograms(cast_or_null<MDTuple>(Subprograms.get()));
529 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
530 assert(Verify() && "Expected compile unit");
531 getRaw()->replaceGlobalVariables(
532 cast_or_null<MDTuple>(GlobalVariables.get()));
535 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
536 DILexicalBlockFile NewScope) {
538 assert(NewScope && "Expected valid scope");
540 const auto *Old = cast<MDLocation>(DbgNode);
541 return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
542 NewScope, Old->getInlinedAt()));
545 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
546 std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
547 return ++Ctx.pImpl->DiscriminatorTable[Key];
550 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
551 LLVMContext &VMContext) {
552 assert(DIVariable(DV).Verify() && "Expected a DIVariable");
553 return cast<MDLocalVariable>(DV)
554 ->withInline(cast_or_null<MDLocation>(InlinedScope));
557 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
558 assert(DIVariable(DV).Verify() && "Expected a DIVariable");
559 return cast<MDLocalVariable>(DV)->withoutInline();
562 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
563 DIDescriptor D(Scope);
564 if (D.isSubprogram())
565 return DISubprogram(Scope);
567 if (D.isLexicalBlockFile())
568 return getDISubprogram(DILexicalBlockFile(Scope).getContext());
570 if (D.isLexicalBlock())
571 return getDISubprogram(DILexicalBlock(Scope).getContext());
573 return DISubprogram();
576 DISubprogram llvm::getDISubprogram(const Function *F) {
577 // We look for the first instr that has a debug annotation leading back to F.
578 for (auto &BB : *F) {
579 auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
580 return !Inst.getDebugLoc().isUnknown();
582 if (Inst == BB.end())
584 DebugLoc DLoc = Inst->getDebugLoc();
585 const MDNode *Scope = DLoc.getScopeNode();
586 DISubprogram Subprogram = getDISubprogram(Scope);
587 return Subprogram.describes(F) ? Subprogram : DISubprogram();
590 return DISubprogram();
593 DICompositeType llvm::getDICompositeType(DIType T) {
594 if (T.isCompositeType())
595 return DICompositeType(T);
597 if (T.isDerivedType()) {
598 // This function is currently used by dragonegg and dragonegg does
599 // not generate identifier for types, so using an empty map to resolve
600 // DerivedFrom should be fine.
601 DITypeIdentifierMap EmptyMap;
602 return getDICompositeType(
603 DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
606 return DICompositeType();
610 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
611 DITypeIdentifierMap Map;
612 for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
613 DICompileUnit CU(CU_Nodes->getOperand(CUi));
614 DIArray Retain = CU.getRetainedTypes();
615 for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
616 if (!Retain.getElement(Ti).isCompositeType())
618 DICompositeType Ty(Retain.getElement(Ti));
619 if (MDString *TypeId = Ty.getIdentifier()) {
620 // Definition has priority over declaration.
621 // Try to insert (TypeId, Ty) to Map.
622 std::pair<DITypeIdentifierMap::iterator, bool> P =
623 Map.insert(std::make_pair(TypeId, Ty));
624 // If TypeId already exists in Map and this is a definition, replace
625 // whatever we had (declaration or definition) with the definition.
626 if (!P.second && !Ty.isForwardDecl())
627 P.first->second = Ty;
634 //===----------------------------------------------------------------------===//
635 // DebugInfoFinder implementations.
636 //===----------------------------------------------------------------------===//
638 void DebugInfoFinder::reset() {
645 TypeIdentifierMap.clear();
646 TypeMapInitialized = false;
649 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
650 if (!TypeMapInitialized)
651 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
652 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
653 TypeMapInitialized = true;
657 void DebugInfoFinder::processModule(const Module &M) {
658 InitializeTypeMap(M);
659 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
660 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
661 DICompileUnit CU(CU_Nodes->getOperand(i));
663 DIArray GVs = CU.getGlobalVariables();
664 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
665 DIGlobalVariable DIG(GVs.getElement(i));
666 if (addGlobalVariable(DIG)) {
667 processScope(DIG.getContext());
668 processType(DIG.getType().resolve(TypeIdentifierMap));
671 DIArray SPs = CU.getSubprograms();
672 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
673 processSubprogram(DISubprogram(SPs.getElement(i)));
674 DIArray EnumTypes = CU.getEnumTypes();
675 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
676 processType(DIType(EnumTypes.getElement(i)));
677 DIArray RetainedTypes = CU.getRetainedTypes();
678 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
679 processType(DIType(RetainedTypes.getElement(i)));
680 DIArray Imports = CU.getImportedEntities();
681 for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
682 DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
683 DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
685 processType(DIType(Entity));
686 else if (Entity.isSubprogram())
687 processSubprogram(DISubprogram(Entity));
688 else if (Entity.isNameSpace())
689 processScope(DINameSpace(Entity).getContext());
695 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
698 InitializeTypeMap(M);
699 processScope(Loc.getScope());
700 processLocation(M, Loc.getOrigLocation());
703 void DebugInfoFinder::processType(DIType DT) {
706 processScope(DT.getContext().resolve(TypeIdentifierMap));
707 if (DT.isCompositeType()) {
708 DICompositeType DCT(DT);
709 processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
710 if (DT.isSubroutineType()) {
711 DITypeArray DTA = DISubroutineType(DT).getTypeArray();
712 for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
713 processType(DTA.getElement(i).resolve(TypeIdentifierMap));
716 DIArray DA = DCT.getElements();
717 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
718 DIDescriptor D = DA.getElement(i);
720 processType(DIType(D));
721 else if (D.isSubprogram())
722 processSubprogram(DISubprogram(D));
724 } else if (DT.isDerivedType()) {
725 DIDerivedType DDT(DT);
726 processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
730 void DebugInfoFinder::processScope(DIScope Scope) {
731 if (Scope.isType()) {
736 if (Scope.isCompileUnit()) {
737 addCompileUnit(DICompileUnit(Scope));
740 if (Scope.isSubprogram()) {
741 processSubprogram(DISubprogram(Scope));
744 if (!addScope(Scope))
746 if (Scope.isLexicalBlock()) {
747 DILexicalBlock LB(Scope);
748 processScope(LB.getContext());
749 } else if (Scope.isLexicalBlockFile()) {
750 DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
751 processScope(LBF.getScope());
752 } else if (Scope.isNameSpace()) {
753 DINameSpace NS(Scope);
754 processScope(NS.getContext());
758 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
759 if (!addSubprogram(SP))
761 processScope(SP.getContext().resolve(TypeIdentifierMap));
762 processType(SP.getType());
763 DIArray TParams = SP.getTemplateParams();
764 for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
765 DIDescriptor Element = TParams.getElement(I);
766 if (Element.isTemplateTypeParameter()) {
767 DITemplateTypeParameter TType(Element);
768 processType(TType.getType().resolve(TypeIdentifierMap));
769 } else if (Element.isTemplateValueParameter()) {
770 DITemplateValueParameter TVal(Element);
771 processType(TVal.getType().resolve(TypeIdentifierMap));
776 void DebugInfoFinder::processDeclare(const Module &M,
777 const DbgDeclareInst *DDI) {
778 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
781 InitializeTypeMap(M);
784 if (!DV.isVariable())
787 if (!NodesSeen.insert(DV).second)
789 processScope(DIVariable(N).getContext());
790 processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
793 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
794 MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
797 InitializeTypeMap(M);
800 if (!DV.isVariable())
803 if (!NodesSeen.insert(DV).second)
805 processScope(DIVariable(N).getContext());
806 processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
809 bool DebugInfoFinder::addType(DIType DT) {
813 if (!NodesSeen.insert(DT).second)
820 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
823 if (!NodesSeen.insert(CU).second)
830 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
834 if (!NodesSeen.insert(DIG).second)
841 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
845 if (!NodesSeen.insert(SP).second)
852 bool DebugInfoFinder::addScope(DIScope Scope) {
855 // FIXME: Ocaml binding generates a scope with no content, we treat it
857 if (Scope->getNumOperands() == 0)
859 if (!NodesSeen.insert(Scope).second)
861 Scopes.push_back(Scope);
865 //===----------------------------------------------------------------------===//
866 // DIDescriptor: dump routines for all descriptors.
867 //===----------------------------------------------------------------------===//
869 void DIDescriptor::dump() const {
874 void DIDescriptor::print(raw_ostream &OS) const {
880 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
881 const LLVMContext &Ctx) {
882 if (!DL.isUnknown()) { // Print source line info.
883 DIScope Scope(DL.getScope(Ctx));
884 assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
885 // Omit the directory, because it's likely to be long and uninteresting.
886 CommentOS << Scope.getFilename();
887 CommentOS << ':' << DL.getLine();
888 if (DL.getCol() != 0)
889 CommentOS << ':' << DL.getCol();
890 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
891 if (!InlinedAtDL.isUnknown()) {
893 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
899 void DIVariable::printExtendedName(raw_ostream &OS) const {
900 const LLVMContext &Ctx = DbgNode->getContext();
901 StringRef Res = getName();
903 OS << Res << "," << getLineNumber();
904 if (MDNode *InlinedAt = getInlinedAt()) {
905 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
906 if (!InlinedAtDL.isUnknown()) {
908 printDebugLoc(InlinedAtDL, OS, Ctx);
914 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V) : Val(V) {
915 assert(isDescriptorRef(V) &&
916 "DIDescriptorRef should be a MDString or MDNode");
918 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
919 assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
921 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
922 assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
926 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const {
927 return DIDescriptorRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
930 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
931 return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
933 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
934 return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
937 bool llvm::StripDebugInfo(Module &M) {
938 bool Changed = false;
940 // Remove all of the calls to the debugger intrinsics, and remove them from
942 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
943 while (!Declare->use_empty()) {
944 CallInst *CI = cast<CallInst>(Declare->user_back());
945 CI->eraseFromParent();
947 Declare->eraseFromParent();
951 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
952 while (!DbgVal->use_empty()) {
953 CallInst *CI = cast<CallInst>(DbgVal->user_back());
954 CI->eraseFromParent();
956 DbgVal->eraseFromParent();
960 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
961 NME = M.named_metadata_end(); NMI != NME;) {
962 NamedMDNode *NMD = NMI;
964 if (NMD->getName().startswith("llvm.dbg.")) {
965 NMD->eraseFromParent();
970 for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
971 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
973 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
975 if (!BI->getDebugLoc().isUnknown()) {
977 BI->setDebugLoc(DebugLoc());
984 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
985 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
986 M.getModuleFlag("Debug Info Version")))
987 return Val->getZExtValue();
991 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
992 llvm::makeSubprogramMap(const Module &M) {
993 DenseMap<const Function *, DISubprogram> R;
995 NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
999 for (MDNode *N : CU_Nodes->operands()) {
1000 DICompileUnit CUNode(N);
1001 DIArray SPs = CUNode.getSubprograms();
1002 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
1003 DISubprogram SP(SPs.getElement(i));
1004 if (Function *F = SP.getFunction())
1005 R.insert(std::make_pair(F, SP));