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 switch (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) const {
86 if (Elt < DbgNode->getNumOperands())
87 if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getOperand(Elt)))
88 return MDS->getString();
93 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
97 if (Elt < DbgNode->getNumOperands())
98 if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getOperand(Elt)))
99 return CI->getZExtValue();
104 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
106 return DIDescriptor();
108 if (Elt < DbgNode->getNumOperands() && DbgNode->getOperand(Elt))
109 return DIDescriptor(dyn_cast<MDNode>(DbgNode->getOperand(Elt)));
111 return DIDescriptor();
114 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
118 if (Elt < DbgNode->getNumOperands())
119 return dyn_cast_or_null<GlobalVariable>(DbgNode->getOperand(Elt));
123 //===----------------------------------------------------------------------===//
125 //===----------------------------------------------------------------------===//
127 /// isBasicType - Return true if the specified tag is legal for
129 bool DIDescriptor::isBasicType() const {
130 assert(!isNull() && "Invalid descriptor!");
131 return getTag() == dwarf::DW_TAG_base_type;
134 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
135 bool DIDescriptor::isDerivedType() const {
136 assert(!isNull() && "Invalid descriptor!");
138 case dwarf::DW_TAG_typedef:
139 case dwarf::DW_TAG_pointer_type:
140 case dwarf::DW_TAG_reference_type:
141 case dwarf::DW_TAG_const_type:
142 case dwarf::DW_TAG_volatile_type:
143 case dwarf::DW_TAG_restrict_type:
144 case dwarf::DW_TAG_member:
145 case dwarf::DW_TAG_inheritance:
148 // CompositeTypes are currently modelled as DerivedTypes.
149 return isCompositeType();
153 /// isCompositeType - Return true if the specified tag is legal for
155 bool DIDescriptor::isCompositeType() const {
156 assert(!isNull() && "Invalid descriptor!");
158 case dwarf::DW_TAG_array_type:
159 case dwarf::DW_TAG_structure_type:
160 case dwarf::DW_TAG_union_type:
161 case dwarf::DW_TAG_enumeration_type:
162 case dwarf::DW_TAG_vector_type:
163 case dwarf::DW_TAG_subroutine_type:
164 case dwarf::DW_TAG_class_type:
171 /// isVariable - Return true if the specified tag is legal for DIVariable.
172 bool DIDescriptor::isVariable() const {
173 assert(!isNull() && "Invalid descriptor!");
175 case dwarf::DW_TAG_auto_variable:
176 case dwarf::DW_TAG_arg_variable:
177 case dwarf::DW_TAG_return_variable:
184 /// isType - Return true if the specified tag is legal for DIType.
185 bool DIDescriptor::isType() const {
186 return isBasicType() || isCompositeType() || isDerivedType();
189 /// isSubprogram - Return true if the specified tag is legal for
191 bool DIDescriptor::isSubprogram() const {
192 assert(!isNull() && "Invalid descriptor!");
193 return getTag() == dwarf::DW_TAG_subprogram;
196 /// isGlobalVariable - Return true if the specified tag is legal for
197 /// DIGlobalVariable.
198 bool DIDescriptor::isGlobalVariable() const {
199 assert(!isNull() && "Invalid descriptor!");
200 return getTag() == dwarf::DW_TAG_variable;
203 /// isGlobal - Return true if the specified tag is legal for DIGlobal.
204 bool DIDescriptor::isGlobal() const {
205 return isGlobalVariable();
208 /// isScope - Return true if the specified tag is one of the scope
210 bool DIDescriptor::isScope() const {
211 assert(!isNull() && "Invalid descriptor!");
213 case dwarf::DW_TAG_compile_unit:
214 case dwarf::DW_TAG_lexical_block:
215 case dwarf::DW_TAG_subprogram:
216 case dwarf::DW_TAG_namespace:
224 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
225 bool DIDescriptor::isCompileUnit() const {
226 assert(!isNull() && "Invalid descriptor!");
227 return getTag() == dwarf::DW_TAG_compile_unit;
230 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
231 bool DIDescriptor::isNameSpace() const {
232 assert(!isNull() && "Invalid descriptor!");
233 return getTag() == dwarf::DW_TAG_namespace;
236 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
237 bool DIDescriptor::isLexicalBlock() const {
238 assert(!isNull() && "Invalid descriptor!");
239 return getTag() == dwarf::DW_TAG_lexical_block;
242 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
243 bool DIDescriptor::isSubrange() const {
244 assert(!isNull() && "Invalid descriptor!");
245 return getTag() == dwarf::DW_TAG_subrange_type;
248 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
249 bool DIDescriptor::isEnumerator() const {
250 assert(!isNull() && "Invalid descriptor!");
251 return getTag() == dwarf::DW_TAG_enumerator;
254 //===----------------------------------------------------------------------===//
255 // Simple Descriptor Constructors and other Methods
256 //===----------------------------------------------------------------------===//
258 DIType::DIType(MDNode *N) : DIDescriptor(N) {
260 if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
265 unsigned DIArray::getNumElements() const {
266 assert(DbgNode && "Invalid DIArray");
267 return DbgNode->getNumOperands();
270 /// replaceAllUsesWith - Replace all uses of debug info referenced by
271 /// this descriptor. After this completes, the current debug info value
273 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
277 assert(!D.isNull() && "Can not replace with null");
279 // Since we use a TrackingVH for the node, its easy for clients to manufacture
280 // legitimate situations where they want to replaceAllUsesWith() on something
281 // which, due to uniquing, has merged with the source. We shield clients from
282 // this detail by allowing a value to be replaced with replaceAllUsesWith()
284 if (getNode() != D.getNode()) {
285 MDNode *Node = DbgNode;
286 Node->replaceAllUsesWith(D.getNode());
291 /// Verify - Verify that a compile unit is well formed.
292 bool DICompileUnit::Verify() const {
295 StringRef N = getFilename();
298 // It is possible that directory and produce string is empty.
302 /// Verify - Verify that a type descriptor is well formed.
303 bool DIType::Verify() const {
306 if (getContext().isNull())
309 DICompileUnit CU = getCompileUnit();
310 if (!CU.isNull() && !CU.Verify())
315 /// Verify - Verify that a composite type descriptor is well formed.
316 bool DICompositeType::Verify() const {
319 if (getContext().isNull())
322 DICompileUnit CU = getCompileUnit();
323 if (!CU.isNull() && !CU.Verify())
328 /// Verify - Verify that a subprogram descriptor is well formed.
329 bool DISubprogram::Verify() const {
333 if (getContext().isNull())
336 DICompileUnit CU = getCompileUnit();
340 DICompositeType Ty = getType();
341 if (!Ty.isNull() && !Ty.Verify())
346 /// Verify - Verify that a global variable descriptor is well formed.
347 bool DIGlobalVariable::Verify() const {
351 if (getDisplayName().empty())
354 if (getContext().isNull())
357 DICompileUnit CU = getCompileUnit();
358 if (!CU.isNull() && !CU.Verify())
361 DIType Ty = getType();
371 /// Verify - Verify that a variable descriptor is well formed.
372 bool DIVariable::Verify() const {
376 if (getContext().isNull())
379 DIType Ty = getType();
386 /// getOriginalTypeSize - If this type is derived from a base type then
387 /// return base type size.
388 uint64_t DIDerivedType::getOriginalTypeSize() const {
389 unsigned Tag = getTag();
390 if (Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef ||
391 Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
392 Tag == dwarf::DW_TAG_restrict_type) {
393 DIType BaseType = getTypeDerivedFrom();
394 // If this type is not derived from any type then take conservative
396 if (BaseType.isNull())
397 return getSizeInBits();
398 if (BaseType.isDerivedType())
399 return DIDerivedType(BaseType.getNode()).getOriginalTypeSize();
401 return BaseType.getSizeInBits();
404 return getSizeInBits();
407 /// describes - Return true if this subprogram provides debugging
408 /// information for the function F.
409 bool DISubprogram::describes(const Function *F) {
410 assert(F && "Invalid function");
411 StringRef Name = getLinkageName();
414 if (F->getName() == Name)
419 StringRef DIScope::getFilename() const {
420 if (isLexicalBlock())
421 return DILexicalBlock(DbgNode).getFilename();
423 return DISubprogram(DbgNode).getFilename();
425 return DICompileUnit(DbgNode).getFilename();
427 return DINameSpace(DbgNode).getFilename();
428 assert(0 && "Invalid DIScope!");
432 StringRef DIScope::getDirectory() const {
433 if (isLexicalBlock())
434 return DILexicalBlock(DbgNode).getDirectory();
436 return DISubprogram(DbgNode).getDirectory();
438 return DICompileUnit(DbgNode).getDirectory();
440 return DINameSpace(DbgNode).getDirectory();
441 assert(0 && "Invalid DIScope!");
445 //===----------------------------------------------------------------------===//
446 // DIDescriptor: dump routines for all descriptors.
447 //===----------------------------------------------------------------------===//
450 /// dump - Print descriptor.
451 void DIDescriptor::dump() const {
452 dbgs() << "[" << dwarf::TagString(getTag()) << "] ";
453 dbgs().write_hex((intptr_t) &*DbgNode) << ']';
456 /// dump - Print compile unit.
457 void DICompileUnit::dump() const {
459 dbgs() << " [" << dwarf::LanguageString(getLanguage()) << "] ";
461 dbgs() << " [" << getDirectory() << "/" << getFilename() << " ]";
464 /// dump - Print type.
465 void DIType::dump() const {
466 if (isNull()) return;
468 StringRef Res = getName();
470 dbgs() << " [" << Res << "] ";
472 unsigned Tag = getTag();
473 dbgs() << " [" << dwarf::TagString(Tag) << "] ";
475 // TODO : Print context
476 getCompileUnit().dump();
478 << getLineNumber() << ", "
479 << getSizeInBits() << ", "
480 << getAlignInBits() << ", "
485 dbgs() << " [private] ";
486 else if (isProtected())
487 dbgs() << " [protected] ";
493 DIBasicType(DbgNode).dump();
494 else if (isDerivedType())
495 DIDerivedType(DbgNode).dump();
496 else if (isCompositeType())
497 DICompositeType(DbgNode).dump();
499 dbgs() << "Invalid DIType\n";
506 /// dump - Print basic type.
507 void DIBasicType::dump() const {
508 dbgs() << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
511 /// dump - Print derived type.
512 void DIDerivedType::dump() const {
513 dbgs() << "\n\t Derived From: "; getTypeDerivedFrom().dump();
516 /// dump - Print composite type.
517 void DICompositeType::dump() const {
518 DIArray A = getTypeArray();
521 dbgs() << " [" << A.getNumElements() << " elements]";
524 /// dump - Print global.
525 void DIGlobal::dump() const {
526 StringRef Res = getName();
528 dbgs() << " [" << Res << "] ";
530 unsigned Tag = getTag();
531 dbgs() << " [" << dwarf::TagString(Tag) << "] ";
533 // TODO : Print context
534 getCompileUnit().dump();
535 dbgs() << " [" << getLineNumber() << "] ";
538 dbgs() << " [local] ";
543 if (isGlobalVariable())
544 DIGlobalVariable(DbgNode).dump();
549 /// dump - Print subprogram.
550 void DISubprogram::dump() const {
551 StringRef Res = getName();
553 dbgs() << " [" << Res << "] ";
555 unsigned Tag = getTag();
556 dbgs() << " [" << dwarf::TagString(Tag) << "] ";
558 // TODO : Print context
559 getCompileUnit().dump();
560 dbgs() << " [" << getLineNumber() << "] ";
563 dbgs() << " [local] ";
571 /// dump - Print global variable.
572 void DIGlobalVariable::dump() const {
578 /// dump - Print variable.
579 void DIVariable::dump() const {
580 StringRef Res = getName();
582 dbgs() << " [" << Res << "] ";
584 getCompileUnit().dump();
585 dbgs() << " [" << getLineNumber() << "] ";
589 // FIXME: Dump complex addresses
592 //===----------------------------------------------------------------------===//
593 // DIFactory: Basic Helpers
594 //===----------------------------------------------------------------------===//
596 DIFactory::DIFactory(Module &m)
597 : M(m), VMContext(M.getContext()), DeclareFn(0) {
598 EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
601 Constant *DIFactory::GetTagConstant(unsigned TAG) {
602 assert((TAG & LLVMDebugVersionMask) == 0 &&
603 "Tag too large for debug encoding!");
604 return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
607 //===----------------------------------------------------------------------===//
608 // DIFactory: Primary Constructors
609 //===----------------------------------------------------------------------===//
611 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
612 /// This implicitly uniques the arrays created.
613 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
614 SmallVector<Value*, 16> Elts;
617 Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
619 for (unsigned i = 0; i != NumTys; ++i)
620 Elts.push_back(Tys[i].getNode());
622 return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
625 /// GetOrCreateSubrange - Create a descriptor for a value range. This
626 /// implicitly uniques the values returned.
627 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
629 GetTagConstant(dwarf::DW_TAG_subrange_type),
630 ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
631 ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
634 return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
639 /// CreateCompileUnit - Create a new descriptor for the specified compile
640 /// unit. Note that this does not unique compile units within the module.
641 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
648 unsigned RunTimeVer) {
650 GetTagConstant(dwarf::DW_TAG_compile_unit),
651 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
652 ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
653 MDString::get(VMContext, Filename),
654 MDString::get(VMContext, Directory),
655 MDString::get(VMContext, Producer),
656 ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
657 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
658 MDString::get(VMContext, Flags),
659 ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
662 return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
665 /// CreateEnumerator - Create a single enumerator value.
666 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
668 GetTagConstant(dwarf::DW_TAG_enumerator),
669 MDString::get(VMContext, Name),
670 ConstantInt::get(Type::getInt64Ty(VMContext), Val)
672 return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
676 /// CreateBasicType - Create a basic type like int, float, etc.
677 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
679 DICompileUnit CompileUnit,
682 uint64_t AlignInBits,
683 uint64_t OffsetInBits, unsigned Flags,
686 GetTagConstant(dwarf::DW_TAG_base_type),
688 MDString::get(VMContext, Name),
689 CompileUnit.getNode(),
690 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
691 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
692 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
693 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
694 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
695 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
697 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
701 /// CreateBasicType - Create a basic type like int, float, etc.
702 DIBasicType DIFactory::CreateBasicTypeEx(DIDescriptor Context,
704 DICompileUnit CompileUnit,
706 Constant *SizeInBits,
707 Constant *AlignInBits,
708 Constant *OffsetInBits, unsigned Flags,
711 GetTagConstant(dwarf::DW_TAG_base_type),
713 MDString::get(VMContext, Name),
714 CompileUnit.getNode(),
715 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
719 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
720 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
722 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
726 /// CreateDerivedType - Create a derived type like const qualified type,
727 /// pointer, typedef, etc.
728 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
729 DIDescriptor Context,
731 DICompileUnit CompileUnit,
734 uint64_t AlignInBits,
735 uint64_t OffsetInBits,
737 DIType DerivedFrom) {
741 MDString::get(VMContext, Name),
742 CompileUnit.getNode(),
743 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
744 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
745 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
746 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
747 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
748 DerivedFrom.getNode(),
750 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
754 /// CreateDerivedType - Create a derived type like const qualified type,
755 /// pointer, typedef, etc.
756 DIDerivedType DIFactory::CreateDerivedTypeEx(unsigned Tag,
757 DIDescriptor Context,
759 DICompileUnit CompileUnit,
761 Constant *SizeInBits,
762 Constant *AlignInBits,
763 Constant *OffsetInBits,
765 DIType DerivedFrom) {
769 MDString::get(VMContext, Name),
770 CompileUnit.getNode(),
771 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
775 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
776 DerivedFrom.getNode(),
778 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
782 /// CreateCompositeType - Create a composite type like array, struct, etc.
783 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
784 DIDescriptor Context,
786 DICompileUnit CompileUnit,
789 uint64_t AlignInBits,
790 uint64_t OffsetInBits,
794 unsigned RuntimeLang) {
799 MDString::get(VMContext, Name),
800 CompileUnit.getNode(),
801 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
802 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
803 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
804 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
805 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
806 DerivedFrom.getNode(),
808 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
810 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
814 /// CreateCompositeType - Create a composite type like array, struct, etc.
815 DICompositeType DIFactory::CreateCompositeTypeEx(unsigned Tag,
816 DIDescriptor Context,
818 DICompileUnit CompileUnit,
820 Constant *SizeInBits,
821 Constant *AlignInBits,
822 Constant *OffsetInBits,
826 unsigned RuntimeLang) {
831 MDString::get(VMContext, Name),
832 CompileUnit.getNode(),
833 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
837 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
838 DerivedFrom.getNode(),
840 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
842 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
846 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
847 /// See comments in DISubprogram for descriptions of these fields. This
848 /// method does not unique the generated descriptors.
849 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
851 StringRef DisplayName,
852 StringRef LinkageName,
853 DICompileUnit CompileUnit,
854 unsigned LineNo, DIType Type,
857 unsigned VK, unsigned VIndex,
858 DIType ContainingType) {
861 GetTagConstant(dwarf::DW_TAG_subprogram),
862 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
864 MDString::get(VMContext, Name),
865 MDString::get(VMContext, DisplayName),
866 MDString::get(VMContext, LinkageName),
867 CompileUnit.getNode(),
868 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
870 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
871 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
872 ConstantInt::get(Type::getInt32Ty(VMContext), (unsigned)VK),
873 ConstantInt::get(Type::getInt32Ty(VMContext), VIndex),
874 ContainingType.getNode()
876 return DISubprogram(MDNode::get(VMContext, &Elts[0], 14));
879 /// CreateSubprogramDefinition - Create new subprogram descriptor for the
880 /// given declaration.
881 DISubprogram DIFactory::CreateSubprogramDefinition(DISubprogram &SPDeclaration) {
882 if (SPDeclaration.isDefinition())
883 return DISubprogram(SPDeclaration.getNode());
885 MDNode *DeclNode = SPDeclaration.getNode();
887 GetTagConstant(dwarf::DW_TAG_subprogram),
888 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
889 DeclNode->getOperand(2), // Context
890 DeclNode->getOperand(3), // Name
891 DeclNode->getOperand(4), // DisplayName
892 DeclNode->getOperand(5), // LinkageName
893 DeclNode->getOperand(6), // CompileUnit
894 DeclNode->getOperand(7), // LineNo
895 DeclNode->getOperand(8), // Type
896 DeclNode->getOperand(9), // isLocalToUnit
897 ConstantInt::get(Type::getInt1Ty(VMContext), true),
898 DeclNode->getOperand(11), // Virtuality
899 DeclNode->getOperand(12), // VIndex
900 DeclNode->getOperand(13) // Containting Type
902 return DISubprogram(MDNode::get(VMContext, &Elts[0], 14));
905 /// CreateGlobalVariable - Create a new descriptor for the specified global.
907 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
908 StringRef DisplayName,
909 StringRef LinkageName,
910 DICompileUnit CompileUnit,
911 unsigned LineNo, DIType Type,bool isLocalToUnit,
912 bool isDefinition, llvm::GlobalVariable *Val) {
914 GetTagConstant(dwarf::DW_TAG_variable),
915 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
917 MDString::get(VMContext, Name),
918 MDString::get(VMContext, DisplayName),
919 MDString::get(VMContext, LinkageName),
920 CompileUnit.getNode(),
921 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
923 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
924 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
928 Value *const *Vs = &Elts[0];
929 MDNode *Node = MDNode::get(VMContext,Vs, 12);
931 // Create a named metadata so that we do not lose this mdnode.
932 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
933 NMD->addOperand(Node);
935 return DIGlobalVariable(Node);
939 /// CreateVariable - Create a new descriptor for the specified variable.
940 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
942 DICompileUnit CompileUnit, unsigned LineNo,
947 MDString::get(VMContext, Name),
948 CompileUnit.getNode(),
949 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
952 return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
956 /// CreateComplexVariable - Create a new descriptor for the specified variable
957 /// which has a complex address expression for its address.
958 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
959 const std::string &Name,
960 DICompileUnit CompileUnit,
962 DIType Type, SmallVector<Value *, 9> &addr) {
963 SmallVector<Value *, 9> Elts;
964 Elts.push_back(GetTagConstant(Tag));
965 Elts.push_back(Context.getNode());
966 Elts.push_back(MDString::get(VMContext, Name));
967 Elts.push_back(CompileUnit.getNode());
968 Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
969 Elts.push_back(Type.getNode());
970 Elts.insert(Elts.end(), addr.begin(), addr.end());
972 return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
976 /// CreateBlock - This creates a descriptor for a lexical block with the
977 /// specified parent VMContext.
978 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context) {
980 GetTagConstant(dwarf::DW_TAG_lexical_block),
983 return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 2));
986 /// CreateNameSpace - This creates new descriptor for a namespace
987 /// with the specified parent context.
988 DINameSpace DIFactory::CreateNameSpace(DIDescriptor Context, StringRef Name,
989 DICompileUnit CompileUnit,
992 GetTagConstant(dwarf::DW_TAG_namespace),
994 MDString::get(VMContext, Name),
995 CompileUnit.getNode(),
996 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
998 return DINameSpace(MDNode::get(VMContext, &Elts[0], 5));
1001 /// CreateLocation - Creates a debug info location.
1002 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1003 DIScope S, DILocation OrigLoc) {
1005 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1006 ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1010 return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1013 /// CreateLocation - Creates a debug info location.
1014 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1015 DIScope S, MDNode *OrigLoc) {
1017 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1018 ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1022 return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1025 //===----------------------------------------------------------------------===//
1026 // DIFactory: Routines for inserting code into a function
1027 //===----------------------------------------------------------------------===//
1029 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1030 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1031 Instruction *InsertBefore) {
1032 // Cast the storage to a {}* for the call to llvm.dbg.declare.
1033 Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertBefore);
1036 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1038 Value *Args[] = { Storage, D.getNode() };
1039 return CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1042 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1043 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1044 BasicBlock *InsertAtEnd) {
1045 // Cast the storage to a {}* for the call to llvm.dbg.declare.
1046 Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertAtEnd);
1049 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1051 Value *Args[] = { Storage, D.getNode() };
1052 return CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);
1055 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1056 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, Value *Offset,
1058 Instruction *InsertBefore) {
1059 assert(V && "no value passed to dbg.value");
1060 assert(Offset->getType() == Type::getInt64Ty(V->getContext()) &&
1061 "offset must be i64");
1063 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1065 Value *Elts[] = { V };
1066 Value *Args[] = { MDNode::get(V->getContext(), Elts, 1), Offset,
1068 return CallInst::Create(ValueFn, Args, Args+3, "", InsertBefore);
1071 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1072 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, Value *Offset,
1074 BasicBlock *InsertAtEnd) {
1075 assert(V && "no value passed to dbg.value");
1076 assert(Offset->getType() == Type::getInt64Ty(V->getContext()) &&
1077 "offset must be i64");
1079 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1081 Value *Elts[] = { V };
1082 Value *Args[] = { MDNode::get(V->getContext(), Elts, 1), Offset,
1084 return CallInst::Create(ValueFn, Args, Args+3, "", InsertAtEnd);
1087 //===----------------------------------------------------------------------===//
1088 // DebugInfoFinder implementations.
1089 //===----------------------------------------------------------------------===//
1091 /// processModule - Process entire module and collect debug info.
1092 void DebugInfoFinder::processModule(Module &M) {
1093 unsigned MDDbgKind = M.getMDKindID("dbg");
1095 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1096 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1097 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1099 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1100 processDeclare(DDI);
1101 else if (MDNode *L = BI->getMetadata(MDDbgKind))
1102 processLocation(DILocation(L));
1105 NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
1109 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1110 DIGlobalVariable DIG(cast<MDNode>(NMD->getOperand(i)));
1111 if (addGlobalVariable(DIG)) {
1112 addCompileUnit(DIG.getCompileUnit());
1113 processType(DIG.getType());
1118 /// processLocation - Process DILocation.
1119 void DebugInfoFinder::processLocation(DILocation Loc) {
1120 if (Loc.isNull()) return;
1121 DIScope S(Loc.getScope().getNode());
1122 if (S.isNull()) return;
1123 if (S.isCompileUnit())
1124 addCompileUnit(DICompileUnit(S.getNode()));
1125 else if (S.isSubprogram())
1126 processSubprogram(DISubprogram(S.getNode()));
1127 else if (S.isLexicalBlock())
1128 processLexicalBlock(DILexicalBlock(S.getNode()));
1129 processLocation(Loc.getOrigLocation());
1132 /// processType - Process DIType.
1133 void DebugInfoFinder::processType(DIType DT) {
1137 addCompileUnit(DT.getCompileUnit());
1138 if (DT.isCompositeType()) {
1139 DICompositeType DCT(DT.getNode());
1140 processType(DCT.getTypeDerivedFrom());
1141 DIArray DA = DCT.getTypeArray();
1143 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1144 DIDescriptor D = DA.getElement(i);
1145 DIType TypeE = DIType(D.getNode());
1146 if (!TypeE.isNull())
1149 processSubprogram(DISubprogram(D.getNode()));
1151 } else if (DT.isDerivedType()) {
1152 DIDerivedType DDT(DT.getNode());
1154 processType(DDT.getTypeDerivedFrom());
1158 /// processLexicalBlock
1159 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1162 DIScope Context = LB.getContext();
1163 if (Context.isLexicalBlock())
1164 return processLexicalBlock(DILexicalBlock(Context.getNode()));
1166 return processSubprogram(DISubprogram(Context.getNode()));
1169 /// processSubprogram - Process DISubprogram.
1170 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1173 if (!addSubprogram(SP))
1175 addCompileUnit(SP.getCompileUnit());
1176 processType(SP.getType());
1179 /// processDeclare - Process DbgDeclareInst.
1180 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1181 DIVariable DV(cast<MDNode>(DDI->getVariable()));
1185 if (!NodesSeen.insert(DV.getNode()))
1188 addCompileUnit(DV.getCompileUnit());
1189 processType(DV.getType());
1192 /// addType - Add type into Tys.
1193 bool DebugInfoFinder::addType(DIType DT) {
1197 if (!NodesSeen.insert(DT.getNode()))
1200 TYs.push_back(DT.getNode());
1204 /// addCompileUnit - Add compile unit into CUs.
1205 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1209 if (!NodesSeen.insert(CU.getNode()))
1212 CUs.push_back(CU.getNode());
1216 /// addGlobalVariable - Add global variable into GVs.
1217 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1221 if (!NodesSeen.insert(DIG.getNode()))
1224 GVs.push_back(DIG.getNode());
1228 // addSubprogram - Add subprgoram into SPs.
1229 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1233 if (!NodesSeen.insert(SP.getNode()))
1236 SPs.push_back(SP.getNode());
1240 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
1241 /// is the stoppoint that dominates this instruction.
1242 const DbgStopPointInst *llvm::findStopPoint(const Instruction *Inst) {
1243 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
1246 const BasicBlock *BB = Inst->getParent();
1247 BasicBlock::const_iterator I = Inst, B;
1251 // A BB consisting only of a terminator can't have a stoppoint.
1254 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1258 // This BB didn't have a stoppoint: if there is only one predecessor, look
1259 // for a stoppoint there. We could use getIDom(), but that would require
1261 BB = I->getParent()->getUniquePredecessor();
1263 I = BB->getTerminator();
1269 /// findBBStopPoint - Find the stoppoint corresponding to first real
1270 /// (non-debug intrinsic) instruction in this Basic Block, and return the
1271 /// stoppoint for it.
1272 const DbgStopPointInst *llvm::findBBStopPoint(const BasicBlock *BB) {
1273 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1274 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1277 // Fallback to looking for stoppoint of unique predecessor. Useful if this
1278 // BB contains no stoppoints, but unique predecessor does.
1279 BB = BB->getUniquePredecessor();
1281 return findStopPoint(BB->getTerminator());
1286 Value *llvm::findDbgGlobalDeclare(GlobalVariable *V) {
1287 const Module *M = V->getParent();
1288 NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1292 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1293 DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getOperand(i)));
1296 if (DIG.getGlobal() == V)
1297 return DIG.getNode();
1302 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1303 /// It looks through pointer casts too.
1304 const DbgDeclareInst *llvm::findDbgDeclare(const Value *V, bool stripCasts) {
1306 V = V->stripPointerCasts();
1308 // Look for the bitcast.
1309 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1311 if (isa<BitCastInst>(I)) {
1312 const DbgDeclareInst *DDI = findDbgDeclare(*I, false);
1313 if (DDI) return DDI;
1318 // Find llvm.dbg.declare among uses of the instruction.
1319 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1321 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1327 bool llvm::getLocationInfo(const Value *V, std::string &DisplayName,
1328 std::string &Type, unsigned &LineNo,
1329 std::string &File, std::string &Dir) {
1333 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1334 Value *DIGV = findDbgGlobalDeclare(GV);
1335 if (!DIGV) return false;
1336 DIGlobalVariable Var(cast<MDNode>(DIGV));
1338 StringRef D = Var.getDisplayName();
1341 LineNo = Var.getLineNumber();
1342 Unit = Var.getCompileUnit();
1343 TypeD = Var.getType();
1345 const DbgDeclareInst *DDI = findDbgDeclare(V);
1346 if (!DDI) return false;
1347 DIVariable Var(cast<MDNode>(DDI->getVariable()));
1349 StringRef D = Var.getName();
1352 LineNo = Var.getLineNumber();
1353 Unit = Var.getCompileUnit();
1354 TypeD = Var.getType();
1357 StringRef T = TypeD.getName();
1360 StringRef F = Unit.getFilename();
1363 StringRef D = Unit.getDirectory();
1369 /// ExtractDebugLocation - Extract debug location information
1370 /// from llvm.dbg.stoppoint intrinsic.
1371 DebugLoc llvm::ExtractDebugLocation(DbgStopPointInst &SPI,
1372 DebugLocTracker &DebugLocInfo) {
1374 Value *Context = SPI.getContext();
1376 // If this location is already tracked then use it.
1377 DebugLocTuple Tuple(cast<MDNode>(Context), NULL, SPI.getLine(),
1379 DenseMap<DebugLocTuple, unsigned>::iterator II
1380 = DebugLocInfo.DebugIdMap.find(Tuple);
1381 if (II != DebugLocInfo.DebugIdMap.end())
1382 return DebugLoc::get(II->second);
1384 // Add a new location entry.
1385 unsigned Id = DebugLocInfo.DebugLocations.size();
1386 DebugLocInfo.DebugLocations.push_back(Tuple);
1387 DebugLocInfo.DebugIdMap[Tuple] = Id;
1389 return DebugLoc::get(Id);
1392 /// ExtractDebugLocation - Extract debug location information
1393 /// from DILocation.
1394 DebugLoc llvm::ExtractDebugLocation(DILocation &Loc,
1395 DebugLocTracker &DebugLocInfo) {
1397 MDNode *Context = Loc.getScope().getNode();
1398 MDNode *InlinedLoc = NULL;
1399 if (!Loc.getOrigLocation().isNull())
1400 InlinedLoc = Loc.getOrigLocation().getNode();
1401 // If this location is already tracked then use it.
1402 DebugLocTuple Tuple(Context, InlinedLoc, Loc.getLineNumber(),
1403 Loc.getColumnNumber());
1404 DenseMap<DebugLocTuple, unsigned>::iterator II
1405 = DebugLocInfo.DebugIdMap.find(Tuple);
1406 if (II != DebugLocInfo.DebugIdMap.end())
1407 return DebugLoc::get(II->second);
1409 // Add a new location entry.
1410 unsigned Id = DebugLocInfo.DebugLocations.size();
1411 DebugLocInfo.DebugLocations.push_back(Tuple);
1412 DebugLocInfo.DebugIdMap[Tuple] = Id;
1414 return DebugLoc::get(Id);
1417 /// ExtractDebugLocation - Extract debug location information
1418 /// from llvm.dbg.func_start intrinsic.
1419 DebugLoc llvm::ExtractDebugLocation(DbgFuncStartInst &FSI,
1420 DebugLocTracker &DebugLocInfo) {
1422 Value *SP = FSI.getSubprogram();
1424 DISubprogram Subprogram(cast<MDNode>(SP));
1425 unsigned Line = Subprogram.getLineNumber();
1426 DICompileUnit CU(Subprogram.getCompileUnit());
1428 // If this location is already tracked then use it.
1429 DebugLocTuple Tuple(CU.getNode(), NULL, Line, /* Column */ 0);
1430 DenseMap<DebugLocTuple, unsigned>::iterator II
1431 = DebugLocInfo.DebugIdMap.find(Tuple);
1432 if (II != DebugLocInfo.DebugIdMap.end())
1433 return DebugLoc::get(II->second);
1435 // Add a new location entry.
1436 unsigned Id = DebugLocInfo.DebugLocations.size();
1437 DebugLocInfo.DebugLocations.push_back(Tuple);
1438 DebugLocInfo.DebugIdMap[Tuple] = Id;
1440 return DebugLoc::get(Id);
1443 /// getDISubprogram - Find subprogram that is enclosing this scope.
1444 DISubprogram llvm::getDISubprogram(MDNode *Scope) {
1445 DIDescriptor D(Scope);
1447 return DISubprogram();
1449 if (D.isCompileUnit())
1450 return DISubprogram();
1452 if (D.isSubprogram())
1453 return DISubprogram(Scope);
1455 if (D.isLexicalBlock())
1456 return getDISubprogram(DILexicalBlock(Scope).getContext().getNode());
1458 return DISubprogram();
1461 /// getDICompositeType - Find underlying composite type.
1462 DICompositeType llvm::getDICompositeType(DIType T) {
1464 return DICompositeType();
1466 if (T.isCompositeType())
1467 return DICompositeType(T.getNode());
1469 if (T.isDerivedType())
1470 return getDICompositeType(DIDerivedType(T.getNode()).getTypeDerivedFrom());
1472 return DICompositeType();