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());
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 {
263 auto *N = dyn_cast_or_null<MDType>(DbgNode);
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 &&
287 Tag != dwarf::DW_TAG_structure_type && Tag != dwarf::DW_TAG_member &&
288 Tag != dwarf::DW_TAG_typedef)
292 if (isCompositeType())
293 return DICompositeType(DbgNode).Verify();
295 return DIDerivedType(DbgNode).Verify();
299 bool DIBasicType::Verify() const {
300 return dyn_cast_or_null<MDBasicType>(DbgNode);
303 bool DIDerivedType::Verify() const {
304 auto *N = dyn_cast_or_null<MDDerivedTypeBase>(DbgNode);
307 if (getTag() == dwarf::DW_TAG_ptr_to_member_type) {
308 auto *D = dyn_cast<MDDerivedType>(N);
311 if (!isTypeRef(D->getExtraData()))
314 return isTypeRef(N->getBaseType());
317 bool DICompositeType::Verify() const {
318 auto *N = dyn_cast_or_null<MDCompositeTypeBase>(DbgNode);
319 return N && isTypeRef(N->getBaseType()) && isTypeRef(N->getVTableHolder()) &&
320 !(isLValueReference() && isRValueReference());
323 bool DISubprogram::Verify() const {
324 auto *N = dyn_cast_or_null<MDSubprogram>(DbgNode);
328 if (!isScopeRef(N->getScope()))
331 if (auto *Op = N->getType())
332 if (!isa<MDNode>(Op))
335 if (!isTypeRef(getContainingType()))
338 if (isLValueReference() && isRValueReference())
341 // If a DISubprogram has an llvm::Function*, then scope chains from all
342 // instructions within the function should lead to this DISubprogram.
343 if (auto *F = getFunction()) {
344 for (auto &BB : *F) {
346 DebugLoc DL = I.getDebugLoc();
350 MDNode *Scope = nullptr;
351 MDNode *IA = nullptr;
352 // walk the inlined-at scopes
353 while ((IA = DL.getInlinedAt()))
354 DL = DebugLoc::getFromDILocation(IA);
355 DL.getScopeAndInlinedAt(Scope, IA);
359 while (!DIDescriptor(Scope).isSubprogram()) {
360 DILexicalBlockFile D(Scope);
361 Scope = D.isLexicalBlockFile()
363 : DebugLoc::getFromDILexicalBlock(Scope).getScope();
367 if (!DISubprogram(Scope).describes(F))
376 bool DIGlobalVariable::Verify() const {
377 auto *N = dyn_cast_or_null<MDGlobalVariable>(DbgNode);
382 if (N->getDisplayName().empty())
385 if (auto *Op = N->getScope())
386 if (!isa<MDNode>(Op))
389 if (auto *Op = N->getStaticDataMemberDeclaration())
390 if (!isa<MDNode>(Op))
393 return isTypeRef(N->getType());
396 bool DIVariable::Verify() const {
397 auto *N = dyn_cast_or_null<MDLocalVariable>(DbgNode);
402 if (auto *Op = N->getScope())
403 if (!isa<MDNode>(Op))
406 return isTypeRef(N->getType());
409 bool DILocation::Verify() const {
410 return dyn_cast_or_null<MDLocation>(DbgNode);
412 bool DINameSpace::Verify() const {
413 return dyn_cast_or_null<MDNamespace>(DbgNode);
415 bool DIFile::Verify() const { return dyn_cast_or_null<MDFile>(DbgNode); }
416 bool DIEnumerator::Verify() const {
417 return dyn_cast_or_null<MDEnumerator>(DbgNode);
419 bool DISubrange::Verify() const {
420 return dyn_cast_or_null<MDSubrange>(DbgNode);
422 bool DILexicalBlock::Verify() const {
423 return dyn_cast_or_null<MDLexicalBlock>(DbgNode);
425 bool DILexicalBlockFile::Verify() const {
426 return dyn_cast_or_null<MDLexicalBlockFile>(DbgNode);
428 bool DITemplateTypeParameter::Verify() const {
429 return dyn_cast_or_null<MDTemplateTypeParameter>(DbgNode);
431 bool DITemplateValueParameter::Verify() const {
432 return dyn_cast_or_null<MDTemplateValueParameter>(DbgNode);
434 bool DIImportedEntity::Verify() const {
435 return dyn_cast_or_null<MDImportedEntity>(DbgNode);
438 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
439 TypedTrackingMDRef<MDCompositeTypeBase> N(get());
441 N->replaceElements(cast<MDTuple>(Elements));
443 N->replaceTemplateParams(cast<MDTuple>(TParams));
447 DIScopeRef DIScope::getRef() const {
448 if (!isCompositeType())
449 return DIScopeRef(*this);
450 DICompositeType DTy(DbgNode);
451 if (!DTy.getIdentifier())
452 return DIScopeRef(*this);
453 return DIScopeRef(DTy.getIdentifier());
456 void DICompositeType::setContainingType(DICompositeType ContainingType) {
457 TypedTrackingMDRef<MDCompositeTypeBase> N(get());
458 N->replaceVTableHolder(ContainingType.getRef());
462 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
463 assert(CurFn && "Invalid function");
464 if (!getContext().isSubprogram())
466 // This variable is not inlined function argument if its scope
467 // does not describe current function.
468 return !DISubprogram(getContext()).describes(CurFn);
471 Function *DISubprogram::getFunction() const {
473 if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getFunction()))
474 return dyn_cast<Function>(C->getValue());
478 bool DISubprogram::describes(const Function *F) {
479 assert(F && "Invalid function");
480 if (F == getFunction())
482 StringRef Name = getLinkageName();
485 if (F->getName() == Name)
490 GlobalVariable *DIGlobalVariable::getGlobal() const {
491 return dyn_cast_or_null<GlobalVariable>(getConstant());
494 DIScopeRef DIScope::getContext() const {
497 return DIType(DbgNode).getContext();
500 return DIScopeRef(DISubprogram(DbgNode).getContext());
502 if (isLexicalBlock())
503 return DIScopeRef(DILexicalBlock(DbgNode).getContext());
505 if (isLexicalBlockFile())
506 return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
509 return DIScopeRef(DINameSpace(DbgNode).getContext());
511 assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
512 return DIScopeRef(nullptr);
515 StringRef DIScope::getName() const {
517 return DIType(DbgNode).getName();
519 return DISubprogram(DbgNode).getName();
521 return DINameSpace(DbgNode).getName();
522 assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
524 "Unhandled type of scope.");
528 StringRef DIScope::getFilename() const {
530 return ::getStringField(dyn_cast_or_null<MDNode>(N->getFile()), 0);
534 StringRef DIScope::getDirectory() const {
536 return ::getStringField(dyn_cast_or_null<MDNode>(N->getFile()), 1);
540 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
541 assert(Verify() && "Expected compile unit");
542 get()->replaceSubprograms(cast_or_null<MDTuple>(Subprograms.get()));
545 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
546 assert(Verify() && "Expected compile unit");
547 get()->replaceGlobalVariables(cast_or_null<MDTuple>(GlobalVariables.get()));
550 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
551 DILexicalBlockFile NewScope) {
553 assert(NewScope && "Expected valid scope");
555 const auto *Old = cast<MDLocation>(DbgNode);
556 return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
557 NewScope, Old->getInlinedAt()));
560 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
561 std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
562 return ++Ctx.pImpl->DiscriminatorTable[Key];
565 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
566 LLVMContext &VMContext) {
567 assert(DIVariable(DV).Verify() && "Expected a DIVariable");
568 return cast<MDLocalVariable>(DV)
569 ->withInline(cast_or_null<MDLocation>(InlinedScope));
572 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
573 assert(DIVariable(DV).Verify() && "Expected a DIVariable");
574 return cast<MDLocalVariable>(DV)->withoutInline();
577 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
578 DIDescriptor D(Scope);
579 if (D.isSubprogram())
580 return DISubprogram(Scope);
582 if (D.isLexicalBlockFile())
583 return getDISubprogram(DILexicalBlockFile(Scope).getContext());
585 if (D.isLexicalBlock())
586 return getDISubprogram(DILexicalBlock(Scope).getContext());
588 return DISubprogram();
591 DISubprogram llvm::getDISubprogram(const Function *F) {
592 // We look for the first instr that has a debug annotation leading back to F.
593 for (auto &BB : *F) {
594 auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
595 return !Inst.getDebugLoc().isUnknown();
597 if (Inst == BB.end())
599 DebugLoc DLoc = Inst->getDebugLoc();
600 const MDNode *Scope = DLoc.getScopeNode();
601 DISubprogram Subprogram = getDISubprogram(Scope);
602 return Subprogram.describes(F) ? Subprogram : DISubprogram();
605 return DISubprogram();
608 DICompositeType llvm::getDICompositeType(DIType T) {
609 if (T.isCompositeType())
610 return DICompositeType(T);
612 if (T.isDerivedType()) {
613 // This function is currently used by dragonegg and dragonegg does
614 // not generate identifier for types, so using an empty map to resolve
615 // DerivedFrom should be fine.
616 DITypeIdentifierMap EmptyMap;
617 return getDICompositeType(
618 DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
621 return DICompositeType();
625 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
626 DITypeIdentifierMap Map;
627 for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
628 DICompileUnit CU(CU_Nodes->getOperand(CUi));
629 DIArray Retain = CU.getRetainedTypes();
630 for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
631 if (!Retain.getElement(Ti).isCompositeType())
633 DICompositeType Ty(Retain.getElement(Ti));
634 if (MDString *TypeId = Ty.getIdentifier()) {
635 // Definition has priority over declaration.
636 // Try to insert (TypeId, Ty) to Map.
637 std::pair<DITypeIdentifierMap::iterator, bool> P =
638 Map.insert(std::make_pair(TypeId, Ty));
639 // If TypeId already exists in Map and this is a definition, replace
640 // whatever we had (declaration or definition) with the definition.
641 if (!P.second && !Ty.isForwardDecl())
642 P.first->second = Ty;
649 //===----------------------------------------------------------------------===//
650 // DebugInfoFinder implementations.
651 //===----------------------------------------------------------------------===//
653 void DebugInfoFinder::reset() {
660 TypeIdentifierMap.clear();
661 TypeMapInitialized = false;
664 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
665 if (!TypeMapInitialized)
666 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
667 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
668 TypeMapInitialized = true;
672 void DebugInfoFinder::processModule(const Module &M) {
673 InitializeTypeMap(M);
674 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
675 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
676 DICompileUnit CU(CU_Nodes->getOperand(i));
678 DIArray GVs = CU.getGlobalVariables();
679 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
680 DIGlobalVariable DIG(GVs.getElement(i));
681 if (addGlobalVariable(DIG)) {
682 processScope(DIG.getContext());
683 processType(DIG.getType().resolve(TypeIdentifierMap));
686 DIArray SPs = CU.getSubprograms();
687 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
688 processSubprogram(DISubprogram(SPs.getElement(i)));
689 DIArray EnumTypes = CU.getEnumTypes();
690 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
691 processType(DIType(EnumTypes.getElement(i)));
692 DIArray RetainedTypes = CU.getRetainedTypes();
693 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
694 processType(DIType(RetainedTypes.getElement(i)));
695 DIArray Imports = CU.getImportedEntities();
696 for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
697 DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
700 DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
702 processType(DIType(Entity));
703 else if (Entity.isSubprogram())
704 processSubprogram(DISubprogram(Entity));
705 else if (Entity.isNameSpace())
706 processScope(DINameSpace(Entity).getContext());
712 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
715 InitializeTypeMap(M);
716 processScope(Loc.getScope());
717 processLocation(M, Loc.getOrigLocation());
720 void DebugInfoFinder::processType(DIType DT) {
723 processScope(DT.getContext().resolve(TypeIdentifierMap));
724 if (DT.isCompositeType()) {
725 DICompositeType DCT(DT);
726 processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
727 if (DT.isSubroutineType()) {
728 DITypeArray DTA = DISubroutineType(DT).getTypeArray();
729 for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
730 processType(DTA.getElement(i).resolve(TypeIdentifierMap));
733 DIArray DA = DCT.getElements();
734 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
735 DIDescriptor D = DA.getElement(i);
737 processType(DIType(D));
738 else if (D.isSubprogram())
739 processSubprogram(DISubprogram(D));
741 } else if (DT.isDerivedType()) {
742 DIDerivedType DDT(DT);
743 processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
747 void DebugInfoFinder::processScope(DIScope Scope) {
748 if (Scope.isType()) {
753 if (Scope.isCompileUnit()) {
754 addCompileUnit(DICompileUnit(Scope));
757 if (Scope.isSubprogram()) {
758 processSubprogram(DISubprogram(Scope));
761 if (!addScope(Scope))
763 if (Scope.isLexicalBlock()) {
764 DILexicalBlock LB(Scope);
765 processScope(LB.getContext());
766 } else if (Scope.isLexicalBlockFile()) {
767 DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
768 processScope(LBF.getScope());
769 } else if (Scope.isNameSpace()) {
770 DINameSpace NS(Scope);
771 processScope(NS.getContext());
775 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
776 if (!addSubprogram(SP))
778 processScope(SP.getContext().resolve(TypeIdentifierMap));
779 processType(SP.getType());
780 DIArray TParams = SP.getTemplateParams();
781 for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
782 DIDescriptor Element = TParams.getElement(I);
783 if (Element.isTemplateTypeParameter()) {
784 DITemplateTypeParameter TType(Element);
785 processType(TType.getType().resolve(TypeIdentifierMap));
786 } else if (Element.isTemplateValueParameter()) {
787 DITemplateValueParameter TVal(Element);
788 processType(TVal.getType().resolve(TypeIdentifierMap));
793 void DebugInfoFinder::processDeclare(const Module &M,
794 const DbgDeclareInst *DDI) {
795 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
798 InitializeTypeMap(M);
801 if (!DV.isVariable())
804 if (!NodesSeen.insert(DV).second)
806 processScope(DIVariable(N).getContext());
807 processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
810 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
811 MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
814 InitializeTypeMap(M);
817 if (!DV.isVariable())
820 if (!NodesSeen.insert(DV).second)
822 processScope(DIVariable(N).getContext());
823 processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
826 bool DebugInfoFinder::addType(DIType DT) {
830 if (!NodesSeen.insert(DT).second)
837 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
840 if (!NodesSeen.insert(CU).second)
847 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
851 if (!NodesSeen.insert(DIG).second)
858 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
862 if (!NodesSeen.insert(SP).second)
869 bool DebugInfoFinder::addScope(DIScope Scope) {
872 // FIXME: Ocaml binding generates a scope with no content, we treat it
874 if (Scope->getNumOperands() == 0)
876 if (!NodesSeen.insert(Scope).second)
878 Scopes.push_back(Scope);
882 //===----------------------------------------------------------------------===//
883 // DIDescriptor: dump routines for all descriptors.
884 //===----------------------------------------------------------------------===//
886 void DIDescriptor::dump() const {
891 void DIDescriptor::print(raw_ostream &OS) const {
897 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
898 const LLVMContext &Ctx) {
899 if (!DL.isUnknown()) { // Print source line info.
900 DIScope Scope(DL.getScope(Ctx));
901 assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
902 // Omit the directory, because it's likely to be long and uninteresting.
903 CommentOS << Scope.getFilename();
904 CommentOS << ':' << DL.getLine();
905 if (DL.getCol() != 0)
906 CommentOS << ':' << DL.getCol();
907 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
908 if (!InlinedAtDL.isUnknown()) {
910 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
916 void DIVariable::printExtendedName(raw_ostream &OS) const {
917 const LLVMContext &Ctx = DbgNode->getContext();
918 StringRef Res = getName();
920 OS << Res << "," << getLineNumber();
921 if (MDNode *InlinedAt = getInlinedAt()) {
922 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
923 if (!InlinedAtDL.isUnknown()) {
925 printDebugLoc(InlinedAtDL, OS, Ctx);
931 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V) : Val(V) {
932 assert(isDescriptorRef(V) &&
933 "DIDescriptorRef should be a MDString or MDNode");
935 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
936 assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
938 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
939 assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
943 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const {
944 return DIDescriptorRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
947 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
948 return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
950 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
951 return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
954 bool llvm::StripDebugInfo(Module &M) {
955 bool Changed = false;
957 // Remove all of the calls to the debugger intrinsics, and remove them from
959 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
960 while (!Declare->use_empty()) {
961 CallInst *CI = cast<CallInst>(Declare->user_back());
962 CI->eraseFromParent();
964 Declare->eraseFromParent();
968 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
969 while (!DbgVal->use_empty()) {
970 CallInst *CI = cast<CallInst>(DbgVal->user_back());
971 CI->eraseFromParent();
973 DbgVal->eraseFromParent();
977 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
978 NME = M.named_metadata_end(); NMI != NME;) {
979 NamedMDNode *NMD = NMI;
981 if (NMD->getName().startswith("llvm.dbg.")) {
982 NMD->eraseFromParent();
987 for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
988 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
990 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
992 if (!BI->getDebugLoc().isUnknown()) {
994 BI->setDebugLoc(DebugLoc());
1001 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
1002 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
1003 M.getModuleFlag("Debug Info Version")))
1004 return Val->getZExtValue();
1008 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
1009 llvm::makeSubprogramMap(const Module &M) {
1010 DenseMap<const Function *, DISubprogram> R;
1012 NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
1016 for (MDNode *N : CU_Nodes->operands()) {
1017 DICompileUnit CUNode(N);
1018 DIArray SPs = CUNode.getSubprograms();
1019 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
1020 DISubprogram SP(SPs.getElement(i));
1021 if (Function *F = SP.getFunction())
1022 R.insert(std::make_pair(F, SP));