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/Analysis/DebugInfo.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/Dwarf.h"
26 #include "llvm/Support/DebugLoc.h"
27 #include "llvm/Support/raw_ostream.h"
29 using namespace llvm::dwarf;
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 /// ValidDebugInfo - Return true if V represents valid debug info value.
36 /// FIXME : Add DIDescriptor.isValid()
37 bool DIDescriptor::ValidDebugInfo(MDNode *N, CodeGenOpt::Level OptLevel) {
43 // Check current version. Allow Version6 for now.
44 unsigned Version = DI.getVersion();
45 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
48 unsigned Tag = DI.getTag();
51 assert(DIVariable(N).Verify() && "Invalid DebugInfo value");
53 case DW_TAG_compile_unit:
54 assert(DICompileUnit(N).Verify() && "Invalid DebugInfo value");
56 case DW_TAG_subprogram:
57 assert(DISubprogram(N).Verify() && "Invalid DebugInfo value");
59 case DW_TAG_lexical_block:
60 // FIXME: This interfers with the quality of generated code during
62 if (OptLevel != CodeGenOpt::None)
72 DIDescriptor::DIDescriptor(MDNode *N, unsigned RequiredTag) {
75 // If this is non-null, check to see if the Tag matches. If not, set to null.
76 if (N && getTag() != RequiredTag) {
82 DIDescriptor::getStringField(unsigned Elt, std::string &Result) const {
87 if (Elt < DbgNode->getNumElements())
88 if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getElement(Elt))) {
89 Result.assign(MDS->begin(), MDS->begin() + MDS->length());
96 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
100 if (Elt < DbgNode->getNumElements())
101 if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getElement(Elt)))
102 return CI->getZExtValue();
107 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
109 return DIDescriptor();
111 if (Elt < DbgNode->getNumElements() && DbgNode->getElement(Elt))
112 return DIDescriptor(dyn_cast<MDNode>(DbgNode->getElement(Elt)));
114 return DIDescriptor();
117 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
121 if (Elt < DbgNode->getNumElements())
122 return dyn_cast<GlobalVariable>(DbgNode->getElement(Elt));
126 //===----------------------------------------------------------------------===//
127 // Simple Descriptor Constructors and other Methods
128 //===----------------------------------------------------------------------===//
130 // Needed by DIVariable::getType().
131 DIType::DIType(MDNode *N) : DIDescriptor(N) {
133 unsigned tag = getTag();
134 if (tag != dwarf::DW_TAG_base_type && !DIDerivedType::isDerivedType(tag) &&
135 !DICompositeType::isCompositeType(tag)) {
140 /// isDerivedType - Return true if the specified tag is legal for
142 bool DIType::isDerivedType(unsigned Tag) {
144 case dwarf::DW_TAG_typedef:
145 case dwarf::DW_TAG_pointer_type:
146 case dwarf::DW_TAG_reference_type:
147 case dwarf::DW_TAG_const_type:
148 case dwarf::DW_TAG_volatile_type:
149 case dwarf::DW_TAG_restrict_type:
150 case dwarf::DW_TAG_member:
151 case dwarf::DW_TAG_inheritance:
154 // CompositeTypes are currently modelled as DerivedTypes.
155 return isCompositeType(Tag);
159 /// isCompositeType - Return true if the specified tag is legal for
161 bool DIType::isCompositeType(unsigned TAG) {
163 case dwarf::DW_TAG_array_type:
164 case dwarf::DW_TAG_structure_type:
165 case dwarf::DW_TAG_union_type:
166 case dwarf::DW_TAG_enumeration_type:
167 case dwarf::DW_TAG_vector_type:
168 case dwarf::DW_TAG_subroutine_type:
169 case dwarf::DW_TAG_class_type:
176 /// isVariable - Return true if the specified tag is legal for DIVariable.
177 bool DIVariable::isVariable(unsigned Tag) {
179 case dwarf::DW_TAG_auto_variable:
180 case dwarf::DW_TAG_arg_variable:
181 case dwarf::DW_TAG_return_variable:
188 unsigned DIArray::getNumElements() const {
189 assert (DbgNode && "Invalid DIArray");
190 return DbgNode->getNumElements();
193 /// replaceAllUsesWith - Replace all uses of debug info referenced by
194 /// this descriptor. After this completes, the current debug info value
196 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
200 assert (!D.isNull() && "Can not replace with null");
201 DbgNode->replaceAllUsesWith(D.getNode());
205 /// Verify - Verify that a compile unit is well formed.
206 bool DICompileUnit::Verify() const {
210 if (getFilename(Res).empty())
212 // It is possible that directory and produce string is empty.
216 /// Verify - Verify that a type descriptor is well formed.
217 bool DIType::Verify() const {
220 if (getContext().isNull())
223 DICompileUnit CU = getCompileUnit();
224 if (!CU.isNull() && !CU.Verify())
229 /// Verify - Verify that a composite type descriptor is well formed.
230 bool DICompositeType::Verify() const {
233 if (getContext().isNull())
236 DICompileUnit CU = getCompileUnit();
237 if (!CU.isNull() && !CU.Verify())
242 /// Verify - Verify that a subprogram descriptor is well formed.
243 bool DISubprogram::Verify() const {
247 if (getContext().isNull())
250 DICompileUnit CU = getCompileUnit();
254 DICompositeType Ty = getType();
255 if (!Ty.isNull() && !Ty.Verify())
260 /// Verify - Verify that a global variable descriptor is well formed.
261 bool DIGlobalVariable::Verify() const {
265 if (getContext().isNull())
268 DICompileUnit CU = getCompileUnit();
269 if (!CU.isNull() && !CU.Verify())
272 DIType Ty = getType();
282 /// Verify - Verify that a variable descriptor is well formed.
283 bool DIVariable::Verify() const {
287 if (getContext().isNull())
290 DIType Ty = getType();
297 /// getOriginalTypeSize - If this type is derived from a base type then
298 /// return base type size.
299 uint64_t DIDerivedType::getOriginalTypeSize() const {
300 if (getTag() != dwarf::DW_TAG_member)
301 return getSizeInBits();
302 DIType BT = getTypeDerivedFrom();
303 if (BT.getTag() != dwarf::DW_TAG_base_type)
304 return getSizeInBits();
305 return BT.getSizeInBits();
308 /// describes - Return true if this subprogram provides debugging
309 /// information for the function F.
310 bool DISubprogram::describes(const Function *F) {
311 assert (F && "Invalid function");
313 getLinkageName(Name);
316 if (F->getName() == Name)
321 //===----------------------------------------------------------------------===//
322 // DIDescriptor: dump routines for all descriptors.
323 //===----------------------------------------------------------------------===//
326 /// dump - Print descriptor.
327 void DIDescriptor::dump() const {
328 errs() << "[" << dwarf::TagString(getTag()) << "] ";
329 errs().write_hex((intptr_t)DbgNode) << ']';
332 /// dump - Print compile unit.
333 void DICompileUnit::dump() const {
335 errs() << " [" << dwarf::LanguageString(getLanguage()) << "] ";
337 std::string Res1, Res2;
338 errs() << " [" << getDirectory(Res1) << "/" << getFilename(Res2) << " ]";
341 /// dump - Print type.
342 void DIType::dump() const {
343 if (isNull()) return;
346 if (!getName(Res).empty())
347 errs() << " [" << Res << "] ";
349 unsigned Tag = getTag();
350 errs() << " [" << dwarf::TagString(Tag) << "] ";
352 // TODO : Print context
353 getCompileUnit().dump();
355 << getLineNumber() << ", "
356 << getSizeInBits() << ", "
357 << getAlignInBits() << ", "
362 errs() << " [private] ";
363 else if (isProtected())
364 errs() << " [protected] ";
369 if (isBasicType(Tag))
370 DIBasicType(DbgNode).dump();
371 else if (isDerivedType(Tag))
372 DIDerivedType(DbgNode).dump();
373 else if (isCompositeType(Tag))
374 DICompositeType(DbgNode).dump();
376 errs() << "Invalid DIType\n";
383 /// dump - Print basic type.
384 void DIBasicType::dump() const {
385 errs() << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
388 /// dump - Print derived type.
389 void DIDerivedType::dump() const {
390 errs() << "\n\t Derived From: "; getTypeDerivedFrom().dump();
393 /// dump - Print composite type.
394 void DICompositeType::dump() const {
395 DIArray A = getTypeArray();
398 errs() << " [" << A.getNumElements() << " elements]";
401 /// dump - Print global.
402 void DIGlobal::dump() const {
404 if (!getName(Res).empty())
405 errs() << " [" << Res << "] ";
407 unsigned Tag = getTag();
408 errs() << " [" << dwarf::TagString(Tag) << "] ";
410 // TODO : Print context
411 getCompileUnit().dump();
412 errs() << " [" << getLineNumber() << "] ";
415 errs() << " [local] ";
420 if (isGlobalVariable(Tag))
421 DIGlobalVariable(DbgNode).dump();
426 /// dump - Print subprogram.
427 void DISubprogram::dump() const {
431 /// dump - Print global variable.
432 void DIGlobalVariable::dump() const {
438 /// dump - Print variable.
439 void DIVariable::dump() const {
441 if (!getName(Res).empty())
442 errs() << " [" << Res << "] ";
444 getCompileUnit().dump();
445 errs() << " [" << getLineNumber() << "] ";
450 //===----------------------------------------------------------------------===//
451 // DIFactory: Basic Helpers
452 //===----------------------------------------------------------------------===//
454 DIFactory::DIFactory(Module &m)
455 : M(m), VMContext(M.getContext()), StopPointFn(0), FuncStartFn(0),
456 RegionStartFn(0), RegionEndFn(0),
458 EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
461 Constant *DIFactory::GetTagConstant(unsigned TAG) {
462 assert((TAG & LLVMDebugVersionMask) == 0 &&
463 "Tag too large for debug encoding!");
464 return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
467 //===----------------------------------------------------------------------===//
468 // DIFactory: Primary Constructors
469 //===----------------------------------------------------------------------===//
471 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
472 /// This implicitly uniques the arrays created.
473 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
474 SmallVector<Value*, 16> Elts;
477 Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
479 for (unsigned i = 0; i != NumTys; ++i)
480 Elts.push_back(Tys[i].getNode());
482 return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
485 /// GetOrCreateSubrange - Create a descriptor for a value range. This
486 /// implicitly uniques the values returned.
487 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
489 GetTagConstant(dwarf::DW_TAG_subrange_type),
490 ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
491 ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
494 return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
499 /// CreateCompileUnit - Create a new descriptor for the specified compile
500 /// unit. Note that this does not unique compile units within the module.
501 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
502 const std::string &Filename,
503 const std::string &Directory,
504 const std::string &Producer,
508 unsigned RunTimeVer) {
510 GetTagConstant(dwarf::DW_TAG_compile_unit),
511 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
512 ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
513 MDString::get(VMContext, Filename),
514 MDString::get(VMContext, Directory),
515 MDString::get(VMContext, Producer),
516 ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
517 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
518 MDString::get(VMContext, Flags),
519 ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
522 return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
525 /// CreateEnumerator - Create a single enumerator value.
526 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
528 GetTagConstant(dwarf::DW_TAG_enumerator),
529 MDString::get(VMContext, Name),
530 ConstantInt::get(Type::getInt64Ty(VMContext), Val)
532 return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
536 /// CreateBasicType - Create a basic type like int, float, etc.
537 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
538 const std::string &Name,
539 DICompileUnit CompileUnit,
542 uint64_t AlignInBits,
543 uint64_t OffsetInBits, unsigned Flags,
546 GetTagConstant(dwarf::DW_TAG_base_type),
548 MDString::get(VMContext, Name),
549 CompileUnit.getNode(),
550 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
551 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
552 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
553 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
554 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
555 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
557 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
560 /// CreateDerivedType - Create a derived type like const qualified type,
561 /// pointer, typedef, etc.
562 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
563 DIDescriptor Context,
564 const std::string &Name,
565 DICompileUnit CompileUnit,
568 uint64_t AlignInBits,
569 uint64_t OffsetInBits,
571 DIType DerivedFrom) {
575 MDString::get(VMContext, Name),
576 CompileUnit.getNode(),
577 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
578 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
579 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
580 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
581 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
582 DerivedFrom.getNode(),
584 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
587 /// CreateCompositeType - Create a composite type like array, struct, etc.
588 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
589 DIDescriptor Context,
590 const std::string &Name,
591 DICompileUnit CompileUnit,
594 uint64_t AlignInBits,
595 uint64_t OffsetInBits,
599 unsigned RuntimeLang) {
604 MDString::get(VMContext, Name),
605 CompileUnit.getNode(),
606 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
607 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
608 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
609 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
610 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
611 DerivedFrom.getNode(),
613 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
615 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
619 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
620 /// See comments in DISubprogram for descriptions of these fields. This
621 /// method does not unique the generated descriptors.
622 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
623 const std::string &Name,
624 const std::string &DisplayName,
625 const std::string &LinkageName,
626 DICompileUnit CompileUnit,
627 unsigned LineNo, DIType Type,
632 GetTagConstant(dwarf::DW_TAG_subprogram),
633 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
635 MDString::get(VMContext, Name),
636 MDString::get(VMContext, DisplayName),
637 MDString::get(VMContext, LinkageName),
638 CompileUnit.getNode(),
639 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
641 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
642 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition)
644 return DISubprogram(MDNode::get(VMContext, &Elts[0], 11));
647 /// CreateGlobalVariable - Create a new descriptor for the specified global.
649 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
650 const std::string &DisplayName,
651 const std::string &LinkageName,
652 DICompileUnit CompileUnit,
653 unsigned LineNo, DIType Type,bool isLocalToUnit,
654 bool isDefinition, llvm::GlobalVariable *Val) {
656 GetTagConstant(dwarf::DW_TAG_variable),
657 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
659 MDString::get(VMContext, Name),
660 MDString::get(VMContext, DisplayName),
661 MDString::get(VMContext, LinkageName),
662 CompileUnit.getNode(),
663 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
665 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
666 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
670 Value *const *Vs = &Elts[0];
671 MDNode *Node = MDNode::get(VMContext,Vs, 12);
673 // Create a named metadata so that we do not lose this mdnode.
674 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
675 NMD->addElement(Node);
677 return DIGlobalVariable(Node);
681 /// CreateVariable - Create a new descriptor for the specified variable.
682 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
683 const std::string &Name,
684 DICompileUnit CompileUnit, unsigned LineNo,
689 MDString::get(VMContext, Name),
690 CompileUnit.getNode(),
691 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
694 return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
698 /// CreateBlock - This creates a descriptor for a lexical block with the
699 /// specified parent VMContext.
700 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
702 GetTagConstant(dwarf::DW_TAG_lexical_block),
705 return DIBlock(MDNode::get(VMContext, &Elts[0], 2));
709 //===----------------------------------------------------------------------===//
710 // DIFactory: Routines for inserting code into a function
711 //===----------------------------------------------------------------------===//
713 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
714 /// inserting it at the end of the specified basic block.
715 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
716 unsigned ColNo, BasicBlock *BB) {
718 // Lazily construct llvm.dbg.stoppoint function.
720 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
721 llvm::Intrinsic::dbg_stoppoint);
723 // Invoke llvm.dbg.stoppoint
725 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo),
726 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), ColNo),
729 CallInst::Create(StopPointFn, Args, Args+3, "", BB);
732 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
733 /// mark the start of the specified subprogram.
734 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
735 // Lazily construct llvm.dbg.func.start.
737 FuncStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_func_start);
739 // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
740 CallInst::Create(FuncStartFn, SP.getNode(), "", BB);
743 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
744 /// mark the start of a region for the specified scoping descriptor.
745 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
746 // Lazily construct llvm.dbg.region.start function.
748 RegionStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_start);
750 // Call llvm.dbg.func.start.
751 CallInst::Create(RegionStartFn, D.getNode(), "", BB);
754 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
755 /// mark the end of a region for the specified scoping descriptor.
756 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
757 // Lazily construct llvm.dbg.region.end function.
759 RegionEndFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_end);
761 // Call llvm.dbg.region.end.
762 CallInst::Create(RegionEndFn, D.getNode(), "", BB);
765 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
766 void DIFactory::InsertDeclare(Value *Storage, DIVariable D, BasicBlock *BB) {
767 // Cast the storage to a {}* for the call to llvm.dbg.declare.
768 Storage = new BitCastInst(Storage, EmptyStructPtr, "", BB);
771 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
773 Value *Args[] = { Storage, D.getNode() };
774 CallInst::Create(DeclareFn, Args, Args+2, "", BB);
778 //===----------------------------------------------------------------------===//
779 // DebugInfoFinder implementations.
780 //===----------------------------------------------------------------------===//
782 /// processModule - Process entire module and collect debug info.
783 void DebugInfoFinder::processModule(Module &M) {
786 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
787 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
788 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
790 if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(BI))
791 processStopPoint(SPI);
792 else if (DbgFuncStartInst *FSI = dyn_cast<DbgFuncStartInst>(BI))
793 processFuncStart(FSI);
794 else if (DbgRegionStartInst *DRS = dyn_cast<DbgRegionStartInst>(BI))
795 processRegionStart(DRS);
796 else if (DbgRegionEndInst *DRE = dyn_cast<DbgRegionEndInst>(BI))
797 processRegionEnd(DRE);
798 else if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
802 NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
806 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
807 DIGlobalVariable DIG(cast<MDNode>(NMD->getElement(i)));
808 if (addGlobalVariable(DIG)) {
809 addCompileUnit(DIG.getCompileUnit());
810 processType(DIG.getType());
815 /// processType - Process DIType.
816 void DebugInfoFinder::processType(DIType DT) {
820 addCompileUnit(DT.getCompileUnit());
821 if (DT.isCompositeType(DT.getTag())) {
822 DICompositeType DCT(DT.getNode());
823 processType(DCT.getTypeDerivedFrom());
824 DIArray DA = DCT.getTypeArray();
826 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
827 DIDescriptor D = DA.getElement(i);
828 DIType TypeE = DIType(D.getNode());
832 processSubprogram(DISubprogram(D.getNode()));
834 } else if (DT.isDerivedType(DT.getTag())) {
835 DIDerivedType DDT(DT.getNode());
837 processType(DDT.getTypeDerivedFrom());
841 /// processSubprogram - Process DISubprogram.
842 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
845 if (!addSubprogram(SP))
847 addCompileUnit(SP.getCompileUnit());
848 processType(SP.getType());
851 /// processStopPoint - Process DbgStopPointInst.
852 void DebugInfoFinder::processStopPoint(DbgStopPointInst *SPI) {
853 MDNode *Context = dyn_cast<MDNode>(SPI->getContext());
854 addCompileUnit(DICompileUnit(Context));
857 /// processFuncStart - Process DbgFuncStartInst.
858 void DebugInfoFinder::processFuncStart(DbgFuncStartInst *FSI) {
859 MDNode *SP = dyn_cast<MDNode>(FSI->getSubprogram());
860 processSubprogram(DISubprogram(SP));
863 /// processRegionStart - Process DbgRegionStart.
864 void DebugInfoFinder::processRegionStart(DbgRegionStartInst *DRS) {
865 MDNode *SP = dyn_cast<MDNode>(DRS->getContext());
866 processSubprogram(DISubprogram(SP));
869 /// processRegionEnd - Process DbgRegionEnd.
870 void DebugInfoFinder::processRegionEnd(DbgRegionEndInst *DRE) {
871 MDNode *SP = dyn_cast<MDNode>(DRE->getContext());
872 processSubprogram(DISubprogram(SP));
875 /// processDeclare - Process DbgDeclareInst.
876 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
877 DIVariable DV(cast<MDNode>(DDI->getVariable()));
881 if (!NodesSeen.insert(DV.getNode()))
884 addCompileUnit(DV.getCompileUnit());
885 processType(DV.getType());
888 /// addType - Add type into Tys.
889 bool DebugInfoFinder::addType(DIType DT) {
893 if (!NodesSeen.insert(DT.getNode()))
896 TYs.push_back(DT.getNode());
900 /// addCompileUnit - Add compile unit into CUs.
901 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
905 if (!NodesSeen.insert(CU.getNode()))
908 CUs.push_back(CU.getNode());
912 /// addGlobalVariable - Add global variable into GVs.
913 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
917 if (!NodesSeen.insert(DIG.getNode()))
920 GVs.push_back(DIG.getNode());
924 // addSubprogram - Add subprgoram into SPs.
925 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
929 if (!NodesSeen.insert(SP.getNode()))
932 SPs.push_back(SP.getNode());
937 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
938 /// is the stoppoint that dominates this instruction.
939 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
940 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
943 const BasicBlock *BB = Inst->getParent();
944 BasicBlock::const_iterator I = Inst, B;
948 // A BB consisting only of a terminator can't have a stoppoint.
951 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
955 // This BB didn't have a stoppoint: if there is only one predecessor, look
956 // for a stoppoint there. We could use getIDom(), but that would require
958 BB = I->getParent()->getUniquePredecessor();
960 I = BB->getTerminator();
966 /// findBBStopPoint - Find the stoppoint corresponding to first real
967 /// (non-debug intrinsic) instruction in this Basic Block, and return the
968 /// stoppoint for it.
969 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
970 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
971 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
974 // Fallback to looking for stoppoint of unique predecessor. Useful if this
975 // BB contains no stoppoints, but unique predecessor does.
976 BB = BB->getUniquePredecessor();
978 return findStopPoint(BB->getTerminator());
983 Value *findDbgGlobalDeclare(GlobalVariable *V) {
984 const Module *M = V->getParent();
985 NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
989 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
990 DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getElement(i)));
993 if (DIG.getGlobal() == V)
994 return DIG.getNode();
999 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1000 /// It looks through pointer casts too.
1001 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1003 V = V->stripPointerCasts();
1005 // Look for the bitcast.
1006 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1008 if (isa<BitCastInst>(I))
1009 return findDbgDeclare(*I, false);
1014 // Find llvm.dbg.declare among uses of the instruction.
1015 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1017 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1023 bool getLocationInfo(const Value *V, std::string &DisplayName,
1024 std::string &Type, unsigned &LineNo, std::string &File,
1029 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1030 Value *DIGV = findDbgGlobalDeclare(GV);
1031 if (!DIGV) return false;
1032 DIGlobalVariable Var(cast<MDNode>(DIGV));
1034 Var.getDisplayName(DisplayName);
1035 LineNo = Var.getLineNumber();
1036 Unit = Var.getCompileUnit();
1037 TypeD = Var.getType();
1039 const DbgDeclareInst *DDI = findDbgDeclare(V);
1040 if (!DDI) return false;
1041 DIVariable Var(cast<MDNode>(DDI->getVariable()));
1043 Var.getName(DisplayName);
1044 LineNo = Var.getLineNumber();
1045 Unit = Var.getCompileUnit();
1046 TypeD = Var.getType();
1049 TypeD.getName(Type);
1050 Unit.getFilename(File);
1051 Unit.getDirectory(Dir);
1055 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1057 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1058 CodeGenOpt::Level OptLev) {
1059 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1062 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1064 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1065 CodeGenOpt::Level OptLev) {
1066 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1069 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1071 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1072 CodeGenOpt::Level OptLev) {
1073 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1076 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1078 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1079 CodeGenOpt::Level OptLev) {
1080 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1084 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1086 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1087 CodeGenOpt::Level OptLev) {
1088 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1091 /// ExtractDebugLocation - Extract debug location information
1092 /// from llvm.dbg.stoppoint intrinsic.
1093 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1094 DebugLocTracker &DebugLocInfo) {
1096 Value *Context = SPI.getContext();
1098 // If this location is already tracked then use it.
1099 DebugLocTuple Tuple(cast<MDNode>(Context), SPI.getLine(),
1101 DenseMap<DebugLocTuple, unsigned>::iterator II
1102 = DebugLocInfo.DebugIdMap.find(Tuple);
1103 if (II != DebugLocInfo.DebugIdMap.end())
1104 return DebugLoc::get(II->second);
1106 // Add a new location entry.
1107 unsigned Id = DebugLocInfo.DebugLocations.size();
1108 DebugLocInfo.DebugLocations.push_back(Tuple);
1109 DebugLocInfo.DebugIdMap[Tuple] = Id;
1111 return DebugLoc::get(Id);
1114 /// ExtractDebugLocation - Extract debug location information
1115 /// from llvm.dbg.func_start intrinsic.
1116 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1117 DebugLocTracker &DebugLocInfo) {
1119 Value *SP = FSI.getSubprogram();
1121 DISubprogram Subprogram(cast<MDNode>(SP));
1122 unsigned Line = Subprogram.getLineNumber();
1123 DICompileUnit CU(Subprogram.getCompileUnit());
1125 // If this location is already tracked then use it.
1126 DebugLocTuple Tuple(CU.getNode(), Line, /* Column */ 0);
1127 DenseMap<DebugLocTuple, unsigned>::iterator II
1128 = DebugLocInfo.DebugIdMap.find(Tuple);
1129 if (II != DebugLocInfo.DebugIdMap.end())
1130 return DebugLoc::get(II->second);
1132 // Add a new location entry.
1133 unsigned Id = DebugLocInfo.DebugLocations.size();
1134 DebugLocInfo.DebugLocations.push_back(Tuple);
1135 DebugLocInfo.DebugIdMap[Tuple] = Id;
1137 return DebugLoc::get(Id);
1140 /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1141 bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1142 DISubprogram Subprogram(cast<MDNode>(FSI.getSubprogram()));
1143 if (Subprogram.describes(CurrentFn))
1149 /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1150 bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1151 DISubprogram Subprogram(cast<MDNode>(REI.getContext()));
1152 if (Subprogram.isNull() || Subprogram.describes(CurrentFn))