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/Target/TargetMachine.h" // FIXME: LAYERING VIOLATION!
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Intrinsics.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/DebugLoc.h"
28 #include "llvm/Support/raw_ostream.h"
30 using namespace llvm::dwarf;
32 //===----------------------------------------------------------------------===//
34 //===----------------------------------------------------------------------===//
36 /// ValidDebugInfo - Return true if V represents valid debug info value.
37 /// FIXME : Add DIDescriptor.isValid()
38 bool DIDescriptor::ValidDebugInfo(MDNode *N, unsigned OptLevel) {
44 // Check current version. Allow Version6 for now.
45 unsigned Version = DI.getVersion();
46 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
49 unsigned Tag = DI.getTag();
52 assert(DIVariable(N).Verify() && "Invalid DebugInfo value");
54 case DW_TAG_compile_unit:
55 assert(DICompileUnit(N).Verify() && "Invalid DebugInfo value");
57 case DW_TAG_subprogram:
58 assert(DISubprogram(N).Verify() && "Invalid DebugInfo value");
60 case DW_TAG_lexical_block:
61 // FIXME: This interfers with the quality of generated code during
63 if (OptLevel != CodeGenOpt::None)
73 DIDescriptor::DIDescriptor(MDNode *N, unsigned RequiredTag) {
76 // If this is non-null, check to see if the Tag matches. If not, set to null.
77 if (N && getTag() != RequiredTag) {
83 DIDescriptor::getStringField(unsigned Elt) const {
87 if (Elt < DbgNode->getNumElements())
88 if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getElement(Elt)))
89 return MDS->getString();
94 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
98 if (Elt < DbgNode->getNumElements())
99 if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getElement(Elt)))
100 return CI->getZExtValue();
105 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
107 return DIDescriptor();
109 if (Elt < DbgNode->getNumElements() && DbgNode->getElement(Elt))
110 return DIDescriptor(dyn_cast<MDNode>(DbgNode->getElement(Elt)));
112 return DIDescriptor();
115 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
119 if (Elt < DbgNode->getNumElements())
120 return dyn_cast_or_null<GlobalVariable>(DbgNode->getElement(Elt));
124 //===----------------------------------------------------------------------===//
126 //===----------------------------------------------------------------------===//
128 /// isBasicType - Return true if the specified tag is legal for
130 bool DIDescriptor::isBasicType() const {
131 assert (!isNull() && "Invalid descriptor!");
132 unsigned Tag = getTag();
134 return Tag == dwarf::DW_TAG_base_type;
137 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
138 bool DIDescriptor::isDerivedType() const {
139 assert (!isNull() && "Invalid descriptor!");
140 unsigned Tag = getTag();
143 case dwarf::DW_TAG_typedef:
144 case dwarf::DW_TAG_pointer_type:
145 case dwarf::DW_TAG_reference_type:
146 case dwarf::DW_TAG_const_type:
147 case dwarf::DW_TAG_volatile_type:
148 case dwarf::DW_TAG_restrict_type:
149 case dwarf::DW_TAG_member:
150 case dwarf::DW_TAG_inheritance:
153 // CompositeTypes are currently modelled as DerivedTypes.
154 return isCompositeType();
158 /// isCompositeType - Return true if the specified tag is legal for
160 bool DIDescriptor::isCompositeType() const {
161 assert (!isNull() && "Invalid descriptor!");
162 unsigned Tag = getTag();
165 case dwarf::DW_TAG_array_type:
166 case dwarf::DW_TAG_structure_type:
167 case dwarf::DW_TAG_union_type:
168 case dwarf::DW_TAG_enumeration_type:
169 case dwarf::DW_TAG_vector_type:
170 case dwarf::DW_TAG_subroutine_type:
171 case dwarf::DW_TAG_class_type:
178 /// isVariable - Return true if the specified tag is legal for DIVariable.
179 bool DIDescriptor::isVariable() const {
180 assert (!isNull() && "Invalid descriptor!");
181 unsigned Tag = getTag();
184 case dwarf::DW_TAG_auto_variable:
185 case dwarf::DW_TAG_arg_variable:
186 case dwarf::DW_TAG_return_variable:
193 /// isType - Return true if the specified tag is legal for DIType.
194 bool DIDescriptor::isType() const {
195 return isBasicType() || isCompositeType() || isDerivedType();
198 /// isSubprogram - Return true if the specified tag is legal for
200 bool DIDescriptor::isSubprogram() const {
201 assert (!isNull() && "Invalid descriptor!");
202 unsigned Tag = getTag();
204 return Tag == dwarf::DW_TAG_subprogram;
207 /// isGlobalVariable - Return true if the specified tag is legal for
208 /// DIGlobalVariable.
209 bool DIDescriptor::isGlobalVariable() const {
210 assert (!isNull() && "Invalid descriptor!");
211 unsigned Tag = getTag();
213 return Tag == dwarf::DW_TAG_variable;
216 /// isGlobal - Return true if the specified tag is legal for DIGlobal.
217 bool DIDescriptor::isGlobal() const {
218 return isGlobalVariable();
221 /// isScope - Return true if the specified tag is one of the scope
223 bool DIDescriptor::isScope() const {
224 assert (!isNull() && "Invalid descriptor!");
225 unsigned Tag = getTag();
228 case dwarf::DW_TAG_compile_unit:
229 case dwarf::DW_TAG_lexical_block:
230 case dwarf::DW_TAG_subprogram:
231 case dwarf::DW_TAG_namespace:
239 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
240 bool DIDescriptor::isCompileUnit() const {
241 assert (!isNull() && "Invalid descriptor!");
242 unsigned Tag = getTag();
244 return Tag == dwarf::DW_TAG_compile_unit;
247 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
248 bool DIDescriptor::isNameSpace() const {
249 assert (!isNull() && "Invalid descriptor!");
250 unsigned Tag = getTag();
252 return Tag == dwarf::DW_TAG_namespace;
255 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
256 bool DIDescriptor::isLexicalBlock() const {
257 assert (!isNull() && "Invalid descriptor!");
258 unsigned Tag = getTag();
260 return Tag == dwarf::DW_TAG_lexical_block;
263 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
264 bool DIDescriptor::isSubrange() const {
265 assert (!isNull() && "Invalid descriptor!");
266 unsigned Tag = getTag();
268 return Tag == dwarf::DW_TAG_subrange_type;
271 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
272 bool DIDescriptor::isEnumerator() const {
273 assert (!isNull() && "Invalid descriptor!");
274 unsigned Tag = getTag();
276 return Tag == dwarf::DW_TAG_enumerator;
279 //===----------------------------------------------------------------------===//
280 // Simple Descriptor Constructors and other Methods
281 //===----------------------------------------------------------------------===//
283 DIType::DIType(MDNode *N) : DIDescriptor(N) {
285 if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
290 unsigned DIArray::getNumElements() const {
291 assert (DbgNode && "Invalid DIArray");
292 return DbgNode->getNumElements();
295 /// replaceAllUsesWith - Replace all uses of debug info referenced by
296 /// this descriptor. After this completes, the current debug info value
298 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
302 assert (!D.isNull() && "Can not replace with null");
304 // Since we use a TrackingVH for the node, its easy for clients to manufacture
305 // legitimate situations where they want to replaceAllUsesWith() on something
306 // which, due to uniquing, has merged with the source. We shield clients from
307 // this detail by allowing a value to be replaced with replaceAllUsesWith()
309 if (getNode() != D.getNode()) {
310 MDNode *Node = DbgNode;
311 Node->replaceAllUsesWith(D.getNode());
316 /// Verify - Verify that a compile unit is well formed.
317 bool DICompileUnit::Verify() const {
320 StringRef N = getFilename();
323 // It is possible that directory and produce string is empty.
327 /// Verify - Verify that a type descriptor is well formed.
328 bool DIType::Verify() const {
331 if (getContext().isNull())
334 DICompileUnit CU = getCompileUnit();
335 if (!CU.isNull() && !CU.Verify())
340 /// Verify - Verify that a composite type descriptor is well formed.
341 bool DICompositeType::Verify() const {
344 if (getContext().isNull())
347 DICompileUnit CU = getCompileUnit();
348 if (!CU.isNull() && !CU.Verify())
353 /// Verify - Verify that a subprogram descriptor is well formed.
354 bool DISubprogram::Verify() const {
358 if (getContext().isNull())
361 DICompileUnit CU = getCompileUnit();
365 DICompositeType Ty = getType();
366 if (!Ty.isNull() && !Ty.Verify())
371 /// Verify - Verify that a global variable descriptor is well formed.
372 bool DIGlobalVariable::Verify() const {
376 if (getDisplayName().empty())
379 if (getContext().isNull())
382 DICompileUnit CU = getCompileUnit();
383 if (!CU.isNull() && !CU.Verify())
386 DIType Ty = getType();
396 /// Verify - Verify that a variable descriptor is well formed.
397 bool DIVariable::Verify() const {
401 if (getContext().isNull())
404 DIType Ty = getType();
411 /// getOriginalTypeSize - If this type is derived from a base type then
412 /// return base type size.
413 uint64_t DIDerivedType::getOriginalTypeSize() const {
414 unsigned Tag = getTag();
415 if (Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef ||
416 Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
417 Tag == dwarf::DW_TAG_restrict_type) {
418 DIType BaseType = getTypeDerivedFrom();
419 // If this type is not derived from any type then take conservative
421 if (BaseType.isNull())
422 return getSizeInBits();
423 if (BaseType.isDerivedType())
424 return DIDerivedType(BaseType.getNode()).getOriginalTypeSize();
426 return BaseType.getSizeInBits();
429 return getSizeInBits();
432 /// describes - Return true if this subprogram provides debugging
433 /// information for the function F.
434 bool DISubprogram::describes(const Function *F) {
435 assert (F && "Invalid function");
436 StringRef Name = getLinkageName();
439 if (F->getName() == Name)
444 StringRef DIScope::getFilename() const {
445 if (isLexicalBlock())
446 return DILexicalBlock(DbgNode).getFilename();
447 else if (isSubprogram())
448 return DISubprogram(DbgNode).getFilename();
449 else if (isCompileUnit())
450 return DICompileUnit(DbgNode).getFilename();
451 else if (isNameSpace())
452 return DINameSpace(DbgNode).getFilename();
454 assert (0 && "Invalid DIScope!");
458 StringRef DIScope::getDirectory() const {
459 if (isLexicalBlock())
460 return DILexicalBlock(DbgNode).getDirectory();
461 else if (isSubprogram())
462 return DISubprogram(DbgNode).getDirectory();
463 else if (isCompileUnit())
464 return DICompileUnit(DbgNode).getDirectory();
465 else if (isNameSpace())
466 return DINameSpace(DbgNode).getDirectory();
468 assert (0 && "Invalid DIScope!");
472 //===----------------------------------------------------------------------===//
473 // DIDescriptor: dump routines for all descriptors.
474 //===----------------------------------------------------------------------===//
477 /// dump - Print descriptor.
478 void DIDescriptor::dump() const {
479 dbgs() << "[" << dwarf::TagString(getTag()) << "] ";
480 dbgs().write_hex((intptr_t) &*DbgNode) << ']';
483 /// dump - Print compile unit.
484 void DICompileUnit::dump() const {
486 dbgs() << " [" << dwarf::LanguageString(getLanguage()) << "] ";
488 dbgs() << " [" << getDirectory() << "/" << getFilename() << " ]";
491 /// dump - Print type.
492 void DIType::dump() const {
493 if (isNull()) return;
495 StringRef Res = getName();
497 dbgs() << " [" << Res << "] ";
499 unsigned Tag = getTag();
500 dbgs() << " [" << dwarf::TagString(Tag) << "] ";
502 // TODO : Print context
503 getCompileUnit().dump();
505 << getLineNumber() << ", "
506 << getSizeInBits() << ", "
507 << getAlignInBits() << ", "
512 dbgs() << " [private] ";
513 else if (isProtected())
514 dbgs() << " [protected] ";
520 DIBasicType(DbgNode).dump();
521 else if (isDerivedType())
522 DIDerivedType(DbgNode).dump();
523 else if (isCompositeType())
524 DICompositeType(DbgNode).dump();
526 dbgs() << "Invalid DIType\n";
533 /// dump - Print basic type.
534 void DIBasicType::dump() const {
535 dbgs() << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
538 /// dump - Print derived type.
539 void DIDerivedType::dump() const {
540 dbgs() << "\n\t Derived From: "; getTypeDerivedFrom().dump();
543 /// dump - Print composite type.
544 void DICompositeType::dump() const {
545 DIArray A = getTypeArray();
548 dbgs() << " [" << A.getNumElements() << " elements]";
551 /// dump - Print global.
552 void DIGlobal::dump() const {
553 StringRef Res = getName();
555 dbgs() << " [" << Res << "] ";
557 unsigned Tag = getTag();
558 dbgs() << " [" << dwarf::TagString(Tag) << "] ";
560 // TODO : Print context
561 getCompileUnit().dump();
562 dbgs() << " [" << getLineNumber() << "] ";
565 dbgs() << " [local] ";
570 if (isGlobalVariable())
571 DIGlobalVariable(DbgNode).dump();
576 /// dump - Print subprogram.
577 void DISubprogram::dump() const {
578 StringRef Res = getName();
580 dbgs() << " [" << Res << "] ";
582 unsigned Tag = getTag();
583 dbgs() << " [" << dwarf::TagString(Tag) << "] ";
585 // TODO : Print context
586 getCompileUnit().dump();
587 dbgs() << " [" << getLineNumber() << "] ";
590 dbgs() << " [local] ";
598 /// dump - Print global variable.
599 void DIGlobalVariable::dump() const {
605 /// dump - Print variable.
606 void DIVariable::dump() const {
607 StringRef Res = getName();
609 dbgs() << " [" << Res << "] ";
611 getCompileUnit().dump();
612 dbgs() << " [" << getLineNumber() << "] ";
616 // FIXME: Dump complex addresses
619 //===----------------------------------------------------------------------===//
620 // DIFactory: Basic Helpers
621 //===----------------------------------------------------------------------===//
623 DIFactory::DIFactory(Module &m)
624 : M(m), VMContext(M.getContext()), DeclareFn(0) {
625 EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
628 Constant *DIFactory::GetTagConstant(unsigned TAG) {
629 assert((TAG & LLVMDebugVersionMask) == 0 &&
630 "Tag too large for debug encoding!");
631 return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
634 //===----------------------------------------------------------------------===//
635 // DIFactory: Primary Constructors
636 //===----------------------------------------------------------------------===//
638 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
639 /// This implicitly uniques the arrays created.
640 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
641 SmallVector<Value*, 16> Elts;
644 Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
646 for (unsigned i = 0; i != NumTys; ++i)
647 Elts.push_back(Tys[i].getNode());
649 return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
652 /// GetOrCreateSubrange - Create a descriptor for a value range. This
653 /// implicitly uniques the values returned.
654 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
656 GetTagConstant(dwarf::DW_TAG_subrange_type),
657 ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
658 ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
661 return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
666 /// CreateCompileUnit - Create a new descriptor for the specified compile
667 /// unit. Note that this does not unique compile units within the module.
668 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
675 unsigned RunTimeVer) {
677 GetTagConstant(dwarf::DW_TAG_compile_unit),
678 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
679 ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
680 MDString::get(VMContext, Filename),
681 MDString::get(VMContext, Directory),
682 MDString::get(VMContext, Producer),
683 ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
684 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
685 MDString::get(VMContext, Flags),
686 ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
689 return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
692 /// CreateEnumerator - Create a single enumerator value.
693 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
695 GetTagConstant(dwarf::DW_TAG_enumerator),
696 MDString::get(VMContext, Name),
697 ConstantInt::get(Type::getInt64Ty(VMContext), Val)
699 return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
703 /// CreateBasicType - Create a basic type like int, float, etc.
704 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
706 DICompileUnit CompileUnit,
709 uint64_t AlignInBits,
710 uint64_t OffsetInBits, unsigned Flags,
713 GetTagConstant(dwarf::DW_TAG_base_type),
715 MDString::get(VMContext, Name),
716 CompileUnit.getNode(),
717 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
718 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
719 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
720 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
721 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
722 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
724 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
728 /// CreateBasicType - Create a basic type like int, float, etc.
729 DIBasicType DIFactory::CreateBasicTypeEx(DIDescriptor Context,
731 DICompileUnit CompileUnit,
733 Constant *SizeInBits,
734 Constant *AlignInBits,
735 Constant *OffsetInBits, unsigned Flags,
738 GetTagConstant(dwarf::DW_TAG_base_type),
740 MDString::get(VMContext, Name),
741 CompileUnit.getNode(),
742 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
746 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
747 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
749 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
753 /// CreateDerivedType - Create a derived type like const qualified type,
754 /// pointer, typedef, etc.
755 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
756 DIDescriptor Context,
758 DICompileUnit CompileUnit,
761 uint64_t AlignInBits,
762 uint64_t OffsetInBits,
764 DIType DerivedFrom) {
768 MDString::get(VMContext, Name),
769 CompileUnit.getNode(),
770 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
771 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
772 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
773 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
774 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
775 DerivedFrom.getNode(),
777 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
781 /// CreateDerivedType - Create a derived type like const qualified type,
782 /// pointer, typedef, etc.
783 DIDerivedType DIFactory::CreateDerivedTypeEx(unsigned Tag,
784 DIDescriptor Context,
786 DICompileUnit CompileUnit,
788 Constant *SizeInBits,
789 Constant *AlignInBits,
790 Constant *OffsetInBits,
792 DIType DerivedFrom) {
796 MDString::get(VMContext, Name),
797 CompileUnit.getNode(),
798 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
802 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
803 DerivedFrom.getNode(),
805 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
809 /// CreateCompositeType - Create a composite type like array, struct, etc.
810 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
811 DIDescriptor Context,
813 DICompileUnit CompileUnit,
816 uint64_t AlignInBits,
817 uint64_t OffsetInBits,
821 unsigned RuntimeLang) {
826 MDString::get(VMContext, Name),
827 CompileUnit.getNode(),
828 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
829 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
830 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
831 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
832 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
833 DerivedFrom.getNode(),
835 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
837 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
841 /// CreateCompositeType - Create a composite type like array, struct, etc.
842 DICompositeType DIFactory::CreateCompositeTypeEx(unsigned Tag,
843 DIDescriptor Context,
845 DICompileUnit CompileUnit,
847 Constant *SizeInBits,
848 Constant *AlignInBits,
849 Constant *OffsetInBits,
853 unsigned RuntimeLang) {
858 MDString::get(VMContext, Name),
859 CompileUnit.getNode(),
860 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
864 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
865 DerivedFrom.getNode(),
867 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
869 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
873 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
874 /// See comments in DISubprogram for descriptions of these fields. This
875 /// method does not unique the generated descriptors.
876 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
878 StringRef DisplayName,
879 StringRef LinkageName,
880 DICompileUnit CompileUnit,
881 unsigned LineNo, DIType Type,
884 unsigned VK, unsigned VIndex,
885 DIType ContainingType) {
888 GetTagConstant(dwarf::DW_TAG_subprogram),
889 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
891 MDString::get(VMContext, Name),
892 MDString::get(VMContext, DisplayName),
893 MDString::get(VMContext, LinkageName),
894 CompileUnit.getNode(),
895 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
897 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
898 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
899 ConstantInt::get(Type::getInt32Ty(VMContext), (unsigned)VK),
900 ConstantInt::get(Type::getInt32Ty(VMContext), VIndex),
901 ContainingType.getNode()
903 return DISubprogram(MDNode::get(VMContext, &Elts[0], 14));
906 /// CreateSubprogramDefinition - Create new subprogram descriptor for the
907 /// given declaration.
908 DISubprogram DIFactory::CreateSubprogramDefinition(DISubprogram &SPDeclaration) {
909 if (SPDeclaration.isDefinition())
910 return DISubprogram(SPDeclaration.getNode());
912 MDNode *DeclNode = SPDeclaration.getNode();
914 GetTagConstant(dwarf::DW_TAG_subprogram),
915 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
916 DeclNode->getElement(2), // Context
917 DeclNode->getElement(3), // Name
918 DeclNode->getElement(4), // DisplayName
919 DeclNode->getElement(5), // LinkageName
920 DeclNode->getElement(6), // CompileUnit
921 DeclNode->getElement(7), // LineNo
922 DeclNode->getElement(8), // Type
923 DeclNode->getElement(9), // isLocalToUnit
924 ConstantInt::get(Type::getInt1Ty(VMContext), true),
925 DeclNode->getElement(11), // Virtuality
926 DeclNode->getElement(12), // VIndex
927 DeclNode->getElement(13) // Containting Type
929 return DISubprogram(MDNode::get(VMContext, &Elts[0], 14));
932 /// CreateGlobalVariable - Create a new descriptor for the specified global.
934 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
935 StringRef DisplayName,
936 StringRef LinkageName,
937 DICompileUnit CompileUnit,
938 unsigned LineNo, DIType Type,bool isLocalToUnit,
939 bool isDefinition, llvm::GlobalVariable *Val) {
941 GetTagConstant(dwarf::DW_TAG_variable),
942 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
944 MDString::get(VMContext, Name),
945 MDString::get(VMContext, DisplayName),
946 MDString::get(VMContext, LinkageName),
947 CompileUnit.getNode(),
948 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
950 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
951 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
955 Value *const *Vs = &Elts[0];
956 MDNode *Node = MDNode::get(VMContext,Vs, 12);
958 // Create a named metadata so that we do not lose this mdnode.
959 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
960 NMD->addElement(Node);
962 return DIGlobalVariable(Node);
966 /// CreateVariable - Create a new descriptor for the specified variable.
967 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
969 DICompileUnit CompileUnit, unsigned LineNo,
974 MDString::get(VMContext, Name),
975 CompileUnit.getNode(),
976 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
979 return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
983 /// CreateComplexVariable - Create a new descriptor for the specified variable
984 /// which has a complex address expression for its address.
985 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
986 const std::string &Name,
987 DICompileUnit CompileUnit,
989 DIType Type, SmallVector<Value *, 9> &addr) {
990 SmallVector<Value *, 9> Elts;
991 Elts.push_back(GetTagConstant(Tag));
992 Elts.push_back(Context.getNode());
993 Elts.push_back(MDString::get(VMContext, Name));
994 Elts.push_back(CompileUnit.getNode());
995 Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
996 Elts.push_back(Type.getNode());
997 Elts.insert(Elts.end(), addr.begin(), addr.end());
999 return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
1003 /// CreateBlock - This creates a descriptor for a lexical block with the
1004 /// specified parent VMContext.
1005 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context) {
1007 GetTagConstant(dwarf::DW_TAG_lexical_block),
1010 return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 2));
1013 /// CreateNameSpace - This creates new descriptor for a namespace
1014 /// with the specified parent context.
1015 DINameSpace DIFactory::CreateNameSpace(DIDescriptor Context, StringRef Name,
1016 DICompileUnit CompileUnit,
1019 GetTagConstant(dwarf::DW_TAG_namespace),
1021 MDString::get(VMContext, Name),
1022 CompileUnit.getNode(),
1023 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
1025 return DINameSpace(MDNode::get(VMContext, &Elts[0], 5));
1028 /// CreateLocation - Creates a debug info location.
1029 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1030 DIScope S, DILocation OrigLoc) {
1032 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1033 ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1037 return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1040 /// CreateLocation - Creates a debug info location.
1041 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1042 DIScope S, MDNode *OrigLoc) {
1044 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1045 ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1049 return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1052 //===----------------------------------------------------------------------===//
1053 // DIFactory: Routines for inserting code into a function
1054 //===----------------------------------------------------------------------===//
1056 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1057 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1058 Instruction *InsertBefore) {
1059 // Cast the storage to a {}* for the call to llvm.dbg.declare.
1060 Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertBefore);
1063 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1065 Value *Args[] = { Storage, D.getNode() };
1066 return CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1069 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1070 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1071 BasicBlock *InsertAtEnd) {
1072 // Cast the storage to a {}* for the call to llvm.dbg.declare.
1073 Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertAtEnd);
1076 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1078 Value *Args[] = { Storage, D.getNode() };
1079 return CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);
1082 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1083 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, Value *Offset,
1085 Instruction *InsertBefore) {
1086 assert(V && "no value passed to dbg.value");
1087 assert(Offset->getType() == Type::getInt64Ty(V->getContext()) &&
1088 "offset must be i64");
1090 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1092 Value *Elts[] = { V };
1093 Value *Args[] = { MDNode::get(V->getContext(), Elts, 1), Offset,
1095 return CallInst::Create(ValueFn, Args, Args+3, "", InsertBefore);
1098 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1099 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, Value *Offset,
1101 BasicBlock *InsertAtEnd) {
1102 assert(V && "no value passed to dbg.value");
1103 assert(Offset->getType() == Type::getInt64Ty(V->getContext()) &&
1104 "offset must be i64");
1106 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1108 Value *Elts[] = { V };
1109 Value *Args[] = { MDNode::get(V->getContext(), Elts, 1), Offset,
1111 return CallInst::Create(ValueFn, Args, Args+3, "", InsertAtEnd);
1114 //===----------------------------------------------------------------------===//
1115 // DebugInfoFinder implementations.
1116 //===----------------------------------------------------------------------===//
1118 /// processModule - Process entire module and collect debug info.
1119 void DebugInfoFinder::processModule(Module &M) {
1120 unsigned MDDbgKind = M.getMDKindID("dbg");
1122 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1123 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1124 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1126 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1127 processDeclare(DDI);
1128 else if (MDNode *L = BI->getMetadata(MDDbgKind))
1129 processLocation(DILocation(L));
1132 NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
1136 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1137 DIGlobalVariable DIG(cast<MDNode>(NMD->getElement(i)));
1138 if (addGlobalVariable(DIG)) {
1139 addCompileUnit(DIG.getCompileUnit());
1140 processType(DIG.getType());
1145 /// processLocation - Process DILocation.
1146 void DebugInfoFinder::processLocation(DILocation Loc) {
1147 if (Loc.isNull()) return;
1148 DIScope S(Loc.getScope().getNode());
1149 if (S.isNull()) return;
1150 if (S.isCompileUnit())
1151 addCompileUnit(DICompileUnit(S.getNode()));
1152 else if (S.isSubprogram())
1153 processSubprogram(DISubprogram(S.getNode()));
1154 else if (S.isLexicalBlock())
1155 processLexicalBlock(DILexicalBlock(S.getNode()));
1156 processLocation(Loc.getOrigLocation());
1159 /// processType - Process DIType.
1160 void DebugInfoFinder::processType(DIType DT) {
1164 addCompileUnit(DT.getCompileUnit());
1165 if (DT.isCompositeType()) {
1166 DICompositeType DCT(DT.getNode());
1167 processType(DCT.getTypeDerivedFrom());
1168 DIArray DA = DCT.getTypeArray();
1170 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1171 DIDescriptor D = DA.getElement(i);
1172 DIType TypeE = DIType(D.getNode());
1173 if (!TypeE.isNull())
1176 processSubprogram(DISubprogram(D.getNode()));
1178 } else if (DT.isDerivedType()) {
1179 DIDerivedType DDT(DT.getNode());
1181 processType(DDT.getTypeDerivedFrom());
1185 /// processLexicalBlock
1186 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1189 DIScope Context = LB.getContext();
1190 if (Context.isLexicalBlock())
1191 return processLexicalBlock(DILexicalBlock(Context.getNode()));
1193 return processSubprogram(DISubprogram(Context.getNode()));
1196 /// processSubprogram - Process DISubprogram.
1197 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1200 if (!addSubprogram(SP))
1202 addCompileUnit(SP.getCompileUnit());
1203 processType(SP.getType());
1206 /// processDeclare - Process DbgDeclareInst.
1207 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1208 DIVariable DV(cast<MDNode>(DDI->getVariable()));
1212 if (!NodesSeen.insert(DV.getNode()))
1215 addCompileUnit(DV.getCompileUnit());
1216 processType(DV.getType());
1219 /// addType - Add type into Tys.
1220 bool DebugInfoFinder::addType(DIType DT) {
1224 if (!NodesSeen.insert(DT.getNode()))
1227 TYs.push_back(DT.getNode());
1231 /// addCompileUnit - Add compile unit into CUs.
1232 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1236 if (!NodesSeen.insert(CU.getNode()))
1239 CUs.push_back(CU.getNode());
1243 /// addGlobalVariable - Add global variable into GVs.
1244 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1248 if (!NodesSeen.insert(DIG.getNode()))
1251 GVs.push_back(DIG.getNode());
1255 // addSubprogram - Add subprgoram into SPs.
1256 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1260 if (!NodesSeen.insert(SP.getNode()))
1263 SPs.push_back(SP.getNode());
1268 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
1269 /// is the stoppoint that dominates this instruction.
1270 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
1271 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
1274 const BasicBlock *BB = Inst->getParent();
1275 BasicBlock::const_iterator I = Inst, B;
1279 // A BB consisting only of a terminator can't have a stoppoint.
1282 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1286 // This BB didn't have a stoppoint: if there is only one predecessor, look
1287 // for a stoppoint there. We could use getIDom(), but that would require
1289 BB = I->getParent()->getUniquePredecessor();
1291 I = BB->getTerminator();
1297 /// findBBStopPoint - Find the stoppoint corresponding to first real
1298 /// (non-debug intrinsic) instruction in this Basic Block, and return the
1299 /// stoppoint for it.
1300 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
1301 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1302 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1305 // Fallback to looking for stoppoint of unique predecessor. Useful if this
1306 // BB contains no stoppoints, but unique predecessor does.
1307 BB = BB->getUniquePredecessor();
1309 return findStopPoint(BB->getTerminator());
1314 Value *findDbgGlobalDeclare(GlobalVariable *V) {
1315 const Module *M = V->getParent();
1316 NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1320 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1321 DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getElement(i)));
1324 if (DIG.getGlobal() == V)
1325 return DIG.getNode();
1330 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1331 /// It looks through pointer casts too.
1332 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1334 V = V->stripPointerCasts();
1336 // Look for the bitcast.
1337 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1339 if (isa<BitCastInst>(I)) {
1340 const DbgDeclareInst *DDI = findDbgDeclare(*I, false);
1341 if (DDI) return DDI;
1346 // Find llvm.dbg.declare among uses of the instruction.
1347 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1349 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1355 bool getLocationInfo(const Value *V, std::string &DisplayName,
1356 std::string &Type, unsigned &LineNo, std::string &File,
1361 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1362 Value *DIGV = findDbgGlobalDeclare(GV);
1363 if (!DIGV) return false;
1364 DIGlobalVariable Var(cast<MDNode>(DIGV));
1366 StringRef D = Var.getDisplayName();
1369 LineNo = Var.getLineNumber();
1370 Unit = Var.getCompileUnit();
1371 TypeD = Var.getType();
1373 const DbgDeclareInst *DDI = findDbgDeclare(V);
1374 if (!DDI) return false;
1375 DIVariable Var(cast<MDNode>(DDI->getVariable()));
1377 StringRef D = Var.getName();
1380 LineNo = Var.getLineNumber();
1381 Unit = Var.getCompileUnit();
1382 TypeD = Var.getType();
1385 StringRef T = TypeD.getName();
1388 StringRef F = Unit.getFilename();
1391 StringRef D = Unit.getDirectory();
1397 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1399 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI, unsigned OptLev) {
1400 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1403 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1405 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI, unsigned OptLev) {
1406 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1409 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1411 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI, unsigned OptLev) {
1412 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1415 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1417 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI, unsigned OptLev) {
1418 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1422 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1424 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI, unsigned OptLev) {
1425 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1428 /// ExtractDebugLocation - Extract debug location information
1429 /// from llvm.dbg.stoppoint intrinsic.
1430 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1431 DebugLocTracker &DebugLocInfo) {
1433 Value *Context = SPI.getContext();
1435 // If this location is already tracked then use it.
1436 DebugLocTuple Tuple(cast<MDNode>(Context), NULL, SPI.getLine(),
1438 DenseMap<DebugLocTuple, unsigned>::iterator II
1439 = DebugLocInfo.DebugIdMap.find(Tuple);
1440 if (II != DebugLocInfo.DebugIdMap.end())
1441 return DebugLoc::get(II->second);
1443 // Add a new location entry.
1444 unsigned Id = DebugLocInfo.DebugLocations.size();
1445 DebugLocInfo.DebugLocations.push_back(Tuple);
1446 DebugLocInfo.DebugIdMap[Tuple] = Id;
1448 return DebugLoc::get(Id);
1451 /// ExtractDebugLocation - Extract debug location information
1452 /// from DILocation.
1453 DebugLoc ExtractDebugLocation(DILocation &Loc,
1454 DebugLocTracker &DebugLocInfo) {
1456 MDNode *Context = Loc.getScope().getNode();
1457 MDNode *InlinedLoc = NULL;
1458 if (!Loc.getOrigLocation().isNull())
1459 InlinedLoc = Loc.getOrigLocation().getNode();
1460 // If this location is already tracked then use it.
1461 DebugLocTuple Tuple(Context, InlinedLoc, Loc.getLineNumber(),
1462 Loc.getColumnNumber());
1463 DenseMap<DebugLocTuple, unsigned>::iterator II
1464 = DebugLocInfo.DebugIdMap.find(Tuple);
1465 if (II != DebugLocInfo.DebugIdMap.end())
1466 return DebugLoc::get(II->second);
1468 // Add a new location entry.
1469 unsigned Id = DebugLocInfo.DebugLocations.size();
1470 DebugLocInfo.DebugLocations.push_back(Tuple);
1471 DebugLocInfo.DebugIdMap[Tuple] = Id;
1473 return DebugLoc::get(Id);
1476 /// ExtractDebugLocation - Extract debug location information
1477 /// from llvm.dbg.func_start intrinsic.
1478 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1479 DebugLocTracker &DebugLocInfo) {
1481 Value *SP = FSI.getSubprogram();
1483 DISubprogram Subprogram(cast<MDNode>(SP));
1484 unsigned Line = Subprogram.getLineNumber();
1485 DICompileUnit CU(Subprogram.getCompileUnit());
1487 // If this location is already tracked then use it.
1488 DebugLocTuple Tuple(CU.getNode(), NULL, Line, /* Column */ 0);
1489 DenseMap<DebugLocTuple, unsigned>::iterator II
1490 = DebugLocInfo.DebugIdMap.find(Tuple);
1491 if (II != DebugLocInfo.DebugIdMap.end())
1492 return DebugLoc::get(II->second);
1494 // Add a new location entry.
1495 unsigned Id = DebugLocInfo.DebugLocations.size();
1496 DebugLocInfo.DebugLocations.push_back(Tuple);
1497 DebugLocInfo.DebugIdMap[Tuple] = Id;
1499 return DebugLoc::get(Id);
1502 /// getDISubprogram - Find subprogram that is enclosing this scope.
1503 DISubprogram getDISubprogram(MDNode *Scope) {
1504 DIDescriptor D(Scope);
1506 return DISubprogram();
1508 if (D.isCompileUnit())
1509 return DISubprogram();
1511 if (D.isSubprogram())
1512 return DISubprogram(Scope);
1514 if (D.isLexicalBlock())
1515 return getDISubprogram(DILexicalBlock(Scope).getContext().getNode());
1517 return DISubprogram();
1520 /// getDICompositeType - Find underlying composite type.
1521 DICompositeType getDICompositeType(DIType T) {
1523 return DICompositeType();
1525 if (T.isCompositeType())
1526 return DICompositeType(T.getNode());
1528 if (T.isDerivedType())
1529 return getDICompositeType(DIDerivedType(T.getNode()).getTypeDerivedFrom());
1531 return DICompositeType();