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) const {
86 if (Elt < DbgNode->getNumElements())
87 if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getElement(Elt))) {
88 if (MDS->getLength() == 0)
90 return MDS->getString().data();
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_or_null<GlobalVariable>(DbgNode->getElement(Elt));
126 //===----------------------------------------------------------------------===//
128 //===----------------------------------------------------------------------===//
130 /// isBasicType - Return true if the specified tag is legal for
132 bool DIDescriptor::isBasicType() const {
133 assert (!isNull() && "Invalid descriptor!");
134 unsigned Tag = getTag();
136 return Tag == dwarf::DW_TAG_base_type;
139 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
140 bool DIDescriptor::isDerivedType() const {
141 assert (!isNull() && "Invalid descriptor!");
142 unsigned Tag = getTag();
145 case dwarf::DW_TAG_typedef:
146 case dwarf::DW_TAG_pointer_type:
147 case dwarf::DW_TAG_reference_type:
148 case dwarf::DW_TAG_const_type:
149 case dwarf::DW_TAG_volatile_type:
150 case dwarf::DW_TAG_restrict_type:
151 case dwarf::DW_TAG_member:
152 case dwarf::DW_TAG_inheritance:
155 // CompositeTypes are currently modelled as DerivedTypes.
156 return isCompositeType();
160 /// isCompositeType - Return true if the specified tag is legal for
162 bool DIDescriptor::isCompositeType() const {
163 assert (!isNull() && "Invalid descriptor!");
164 unsigned Tag = getTag();
167 case dwarf::DW_TAG_array_type:
168 case dwarf::DW_TAG_structure_type:
169 case dwarf::DW_TAG_union_type:
170 case dwarf::DW_TAG_enumeration_type:
171 case dwarf::DW_TAG_vector_type:
172 case dwarf::DW_TAG_subroutine_type:
173 case dwarf::DW_TAG_class_type:
180 /// isVariable - Return true if the specified tag is legal for DIVariable.
181 bool DIDescriptor::isVariable() const {
182 assert (!isNull() && "Invalid descriptor!");
183 unsigned Tag = getTag();
186 case dwarf::DW_TAG_auto_variable:
187 case dwarf::DW_TAG_arg_variable:
188 case dwarf::DW_TAG_return_variable:
195 /// isType - Return true if the specified tag is legal for DIType.
196 bool DIDescriptor::isType() const {
197 return isBasicType() || isCompositeType() || isDerivedType();
200 /// isSubprogram - Return true if the specified tag is legal for
202 bool DIDescriptor::isSubprogram() const {
203 assert (!isNull() && "Invalid descriptor!");
204 unsigned Tag = getTag();
206 return Tag == dwarf::DW_TAG_subprogram;
209 /// isGlobalVariable - Return true if the specified tag is legal for
210 /// DIGlobalVariable.
211 bool DIDescriptor::isGlobalVariable() const {
212 assert (!isNull() && "Invalid descriptor!");
213 unsigned Tag = getTag();
215 return Tag == dwarf::DW_TAG_variable;
218 /// isGlobal - Return true if the specified tag is legal for DIGlobal.
219 bool DIDescriptor::isGlobal() const {
220 return isGlobalVariable();
223 /// isScope - Return true if the specified tag is one of the scope
225 bool DIDescriptor::isScope() const {
226 assert (!isNull() && "Invalid descriptor!");
227 unsigned Tag = getTag();
230 case dwarf::DW_TAG_compile_unit:
231 case dwarf::DW_TAG_lexical_block:
232 case dwarf::DW_TAG_subprogram:
240 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
241 bool DIDescriptor::isCompileUnit() const {
242 assert (!isNull() && "Invalid descriptor!");
243 unsigned Tag = getTag();
245 return Tag == dwarf::DW_TAG_compile_unit;
248 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
249 bool DIDescriptor::isLexicalBlock() const {
250 assert (!isNull() && "Invalid descriptor!");
251 unsigned Tag = getTag();
253 return Tag == dwarf::DW_TAG_lexical_block;
256 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
257 bool DIDescriptor::isSubrange() const {
258 assert (!isNull() && "Invalid descriptor!");
259 unsigned Tag = getTag();
261 return Tag == dwarf::DW_TAG_subrange_type;
264 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
265 bool DIDescriptor::isEnumerator() const {
266 assert (!isNull() && "Invalid descriptor!");
267 unsigned Tag = getTag();
269 return Tag == dwarf::DW_TAG_enumerator;
272 //===----------------------------------------------------------------------===//
273 // Simple Descriptor Constructors and other Methods
274 //===----------------------------------------------------------------------===//
276 DIType::DIType(MDNode *N) : DIDescriptor(N) {
278 if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
283 unsigned DIArray::getNumElements() const {
284 assert (DbgNode && "Invalid DIArray");
285 return DbgNode->getNumElements();
288 /// replaceAllUsesWith - Replace all uses of debug info referenced by
289 /// this descriptor. After this completes, the current debug info value
291 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
295 assert (!D.isNull() && "Can not replace with null");
297 // Since we use a TrackingVH for the node, its easy for clients to manufacture
298 // legitimate situations where they want to replaceAllUsesWith() on something
299 // which, due to uniquing, has merged with the source. We shield clients from
300 // this detail by allowing a value to be replaced with replaceAllUsesWith()
302 if (getNode() != D.getNode()) {
303 MDNode *Node = DbgNode;
304 Node->replaceAllUsesWith(D.getNode());
309 /// Verify - Verify that a compile unit is well formed.
310 bool DICompileUnit::Verify() const {
313 const char *N = getFilename();
316 // It is possible that directory and produce string is empty.
320 /// Verify - Verify that a type descriptor is well formed.
321 bool DIType::Verify() const {
324 if (getContext().isNull())
327 DICompileUnit CU = getCompileUnit();
328 if (!CU.isNull() && !CU.Verify())
333 /// Verify - Verify that a composite type descriptor is well formed.
334 bool DICompositeType::Verify() const {
337 if (getContext().isNull())
340 DICompileUnit CU = getCompileUnit();
341 if (!CU.isNull() && !CU.Verify())
346 /// Verify - Verify that a subprogram descriptor is well formed.
347 bool DISubprogram::Verify() const {
351 if (getContext().isNull())
354 DICompileUnit CU = getCompileUnit();
358 DICompositeType Ty = getType();
359 if (!Ty.isNull() && !Ty.Verify())
364 /// Verify - Verify that a global variable descriptor is well formed.
365 bool DIGlobalVariable::Verify() const {
369 if (!getDisplayName())
372 if (getContext().isNull())
375 DICompileUnit CU = getCompileUnit();
376 if (!CU.isNull() && !CU.Verify())
379 DIType Ty = getType();
389 /// Verify - Verify that a variable descriptor is well formed.
390 bool DIVariable::Verify() const {
394 if (getContext().isNull())
397 DIType Ty = getType();
404 /// getOriginalTypeSize - If this type is derived from a base type then
405 /// return base type size.
406 uint64_t DIDerivedType::getOriginalTypeSize() const {
407 unsigned Tag = getTag();
408 if (Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef ||
409 Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
410 Tag == dwarf::DW_TAG_restrict_type) {
411 DIType BaseType = getTypeDerivedFrom();
412 // If this type is not derived from any type then take conservative
414 if (BaseType.isNull())
415 return getSizeInBits();
416 if (BaseType.isDerivedType())
417 return DIDerivedType(BaseType.getNode()).getOriginalTypeSize();
419 return BaseType.getSizeInBits();
422 return getSizeInBits();
425 /// describes - Return true if this subprogram provides debugging
426 /// information for the function F.
427 bool DISubprogram::describes(const Function *F) {
428 assert (F && "Invalid function");
429 const char *Name = getLinkageName();
432 if (strcmp(F->getName().data(), Name) == 0)
437 const char *DIScope::getFilename() const {
438 if (isLexicalBlock())
439 return DILexicalBlock(DbgNode).getFilename();
440 else if (isSubprogram())
441 return DISubprogram(DbgNode).getFilename();
442 else if (isCompileUnit())
443 return DICompileUnit(DbgNode).getFilename();
445 assert (0 && "Invalid DIScope!");
449 const char *DIScope::getDirectory() const {
450 if (isLexicalBlock())
451 return DILexicalBlock(DbgNode).getDirectory();
452 else if (isSubprogram())
453 return DISubprogram(DbgNode).getDirectory();
454 else if (isCompileUnit())
455 return DICompileUnit(DbgNode).getDirectory();
457 assert (0 && "Invalid DIScope!");
461 //===----------------------------------------------------------------------===//
462 // DIDescriptor: dump routines for all descriptors.
463 //===----------------------------------------------------------------------===//
466 /// dump - Print descriptor.
467 void DIDescriptor::dump() const {
468 errs() << "[" << dwarf::TagString(getTag()) << "] ";
469 errs().write_hex((intptr_t) &*DbgNode) << ']';
472 /// dump - Print compile unit.
473 void DICompileUnit::dump() const {
475 errs() << " [" << dwarf::LanguageString(getLanguage()) << "] ";
477 errs() << " [" << getDirectory() << "/" << getFilename() << " ]";
480 /// dump - Print type.
481 void DIType::dump() const {
482 if (isNull()) return;
484 if (const char *Res = getName())
485 errs() << " [" << Res << "] ";
487 unsigned Tag = getTag();
488 errs() << " [" << dwarf::TagString(Tag) << "] ";
490 // TODO : Print context
491 getCompileUnit().dump();
493 << getLineNumber() << ", "
494 << getSizeInBits() << ", "
495 << getAlignInBits() << ", "
500 errs() << " [private] ";
501 else if (isProtected())
502 errs() << " [protected] ";
508 DIBasicType(DbgNode).dump();
509 else if (isDerivedType())
510 DIDerivedType(DbgNode).dump();
511 else if (isCompositeType())
512 DICompositeType(DbgNode).dump();
514 errs() << "Invalid DIType\n";
521 /// dump - Print basic type.
522 void DIBasicType::dump() const {
523 errs() << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
526 /// dump - Print derived type.
527 void DIDerivedType::dump() const {
528 errs() << "\n\t Derived From: "; getTypeDerivedFrom().dump();
531 /// dump - Print composite type.
532 void DICompositeType::dump() const {
533 DIArray A = getTypeArray();
536 errs() << " [" << A.getNumElements() << " elements]";
539 /// dump - Print global.
540 void DIGlobal::dump() const {
541 if (const char *Res = getName())
542 errs() << " [" << Res << "] ";
544 unsigned Tag = getTag();
545 errs() << " [" << dwarf::TagString(Tag) << "] ";
547 // TODO : Print context
548 getCompileUnit().dump();
549 errs() << " [" << getLineNumber() << "] ";
552 errs() << " [local] ";
557 if (isGlobalVariable())
558 DIGlobalVariable(DbgNode).dump();
563 /// dump - Print subprogram.
564 void DISubprogram::dump() const {
565 if (const char *Res = getName())
566 errs() << " [" << Res << "] ";
568 unsigned Tag = getTag();
569 errs() << " [" << dwarf::TagString(Tag) << "] ";
571 // TODO : Print context
572 getCompileUnit().dump();
573 errs() << " [" << getLineNumber() << "] ";
576 errs() << " [local] ";
584 /// dump - Print global variable.
585 void DIGlobalVariable::dump() const {
591 /// dump - Print variable.
592 void DIVariable::dump() const {
593 if (const char *Res = getName())
594 errs() << " [" << Res << "] ";
596 getCompileUnit().dump();
597 errs() << " [" << getLineNumber() << "] ";
601 // FIXME: Dump complex addresses
604 //===----------------------------------------------------------------------===//
605 // DIFactory: Basic Helpers
606 //===----------------------------------------------------------------------===//
608 DIFactory::DIFactory(Module &m)
609 : M(m), VMContext(M.getContext()), DeclareFn(0) {
610 EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
613 Constant *DIFactory::GetTagConstant(unsigned TAG) {
614 assert((TAG & LLVMDebugVersionMask) == 0 &&
615 "Tag too large for debug encoding!");
616 return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
619 //===----------------------------------------------------------------------===//
620 // DIFactory: Primary Constructors
621 //===----------------------------------------------------------------------===//
623 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
624 /// This implicitly uniques the arrays created.
625 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
626 SmallVector<Value*, 16> Elts;
629 Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
631 for (unsigned i = 0; i != NumTys; ++i)
632 Elts.push_back(Tys[i].getNode());
634 return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
637 /// GetOrCreateSubrange - Create a descriptor for a value range. This
638 /// implicitly uniques the values returned.
639 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
641 GetTagConstant(dwarf::DW_TAG_subrange_type),
642 ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
643 ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
646 return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
651 /// CreateCompileUnit - Create a new descriptor for the specified compile
652 /// unit. Note that this does not unique compile units within the module.
653 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
654 const char * Filename,
655 const char * Directory,
656 const char * Producer,
660 unsigned RunTimeVer) {
662 GetTagConstant(dwarf::DW_TAG_compile_unit),
663 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
664 ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
665 MDString::get(VMContext, Filename),
666 MDString::get(VMContext, Directory),
667 MDString::get(VMContext, Producer),
668 ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
669 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
670 MDString::get(VMContext, Flags),
671 ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
674 return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
677 /// CreateEnumerator - Create a single enumerator value.
678 DIEnumerator DIFactory::CreateEnumerator(const char * Name, uint64_t Val){
680 GetTagConstant(dwarf::DW_TAG_enumerator),
681 MDString::get(VMContext, Name),
682 ConstantInt::get(Type::getInt64Ty(VMContext), Val)
684 return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
688 /// CreateBasicType - Create a basic type like int, float, etc.
689 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
691 DICompileUnit CompileUnit,
694 uint64_t AlignInBits,
695 uint64_t OffsetInBits, unsigned Flags,
698 GetTagConstant(dwarf::DW_TAG_base_type),
700 MDString::get(VMContext, Name),
701 CompileUnit.getNode(),
702 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
703 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
704 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
705 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
706 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
707 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
709 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
713 /// CreateBasicType - Create a basic type like int, float, etc.
714 DIBasicType DIFactory::CreateBasicTypeEx(DIDescriptor Context,
716 DICompileUnit CompileUnit,
718 Constant *SizeInBits,
719 Constant *AlignInBits,
720 Constant *OffsetInBits, unsigned Flags,
723 GetTagConstant(dwarf::DW_TAG_base_type),
725 MDString::get(VMContext, Name),
726 CompileUnit.getNode(),
727 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
731 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
732 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
734 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
738 /// CreateDerivedType - Create a derived type like const qualified type,
739 /// pointer, typedef, etc.
740 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
741 DIDescriptor Context,
743 DICompileUnit CompileUnit,
746 uint64_t AlignInBits,
747 uint64_t OffsetInBits,
749 DIType DerivedFrom) {
753 MDString::get(VMContext, Name),
754 CompileUnit.getNode(),
755 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
756 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
757 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
758 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
759 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
760 DerivedFrom.getNode(),
762 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
766 /// CreateDerivedType - Create a derived type like const qualified type,
767 /// pointer, typedef, etc.
768 DIDerivedType DIFactory::CreateDerivedTypeEx(unsigned Tag,
769 DIDescriptor Context,
771 DICompileUnit CompileUnit,
773 Constant *SizeInBits,
774 Constant *AlignInBits,
775 Constant *OffsetInBits,
777 DIType DerivedFrom) {
781 MDString::get(VMContext, Name),
782 CompileUnit.getNode(),
783 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
787 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
788 DerivedFrom.getNode(),
790 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
794 /// CreateCompositeType - Create a composite type like array, struct, etc.
795 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
796 DIDescriptor Context,
798 DICompileUnit CompileUnit,
801 uint64_t AlignInBits,
802 uint64_t OffsetInBits,
806 unsigned RuntimeLang) {
811 MDString::get(VMContext, Name),
812 CompileUnit.getNode(),
813 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
814 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
815 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
816 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
817 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
818 DerivedFrom.getNode(),
820 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
822 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
826 /// CreateCompositeType - Create a composite type like array, struct, etc.
827 DICompositeType DIFactory::CreateCompositeTypeEx(unsigned Tag,
828 DIDescriptor Context,
830 DICompileUnit CompileUnit,
832 Constant *SizeInBits,
833 Constant *AlignInBits,
834 Constant *OffsetInBits,
838 unsigned RuntimeLang) {
843 MDString::get(VMContext, Name),
844 CompileUnit.getNode(),
845 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
849 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
850 DerivedFrom.getNode(),
852 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
854 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
858 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
859 /// See comments in DISubprogram for descriptions of these fields. This
860 /// method does not unique the generated descriptors.
861 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
863 const char * DisplayName,
864 const char * LinkageName,
865 DICompileUnit CompileUnit,
866 unsigned LineNo, DIType Type,
871 GetTagConstant(dwarf::DW_TAG_subprogram),
872 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
874 MDString::get(VMContext, Name),
875 MDString::get(VMContext, DisplayName),
876 MDString::get(VMContext, LinkageName),
877 CompileUnit.getNode(),
878 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
880 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
881 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition)
883 return DISubprogram(MDNode::get(VMContext, &Elts[0], 11));
886 /// CreateGlobalVariable - Create a new descriptor for the specified global.
888 DIFactory::CreateGlobalVariable(DIDescriptor Context, const char * Name,
889 const char * DisplayName,
890 const char * LinkageName,
891 DICompileUnit CompileUnit,
892 unsigned LineNo, DIType Type,bool isLocalToUnit,
893 bool isDefinition, llvm::GlobalVariable *Val) {
895 GetTagConstant(dwarf::DW_TAG_variable),
896 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
898 MDString::get(VMContext, Name),
899 MDString::get(VMContext, DisplayName),
900 MDString::get(VMContext, LinkageName),
901 CompileUnit.getNode(),
902 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
904 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
905 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
909 Value *const *Vs = &Elts[0];
910 MDNode *Node = MDNode::get(VMContext,Vs, 12);
912 // Create a named metadata so that we do not lose this mdnode.
913 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
914 NMD->addElement(Node);
916 return DIGlobalVariable(Node);
920 /// CreateVariable - Create a new descriptor for the specified variable.
921 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
923 DICompileUnit CompileUnit, unsigned LineNo,
928 MDString::get(VMContext, Name),
929 CompileUnit.getNode(),
930 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
933 return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
937 /// CreateComplexVariable - Create a new descriptor for the specified variable
938 /// which has a complex address expression for its address.
939 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
940 const std::string &Name,
941 DICompileUnit CompileUnit,
943 DIType Type, SmallVector<Value *, 9> &addr) {
944 SmallVector<Value *, 9> Elts;
945 Elts.push_back(GetTagConstant(Tag));
946 Elts.push_back(Context.getNode());
947 Elts.push_back(MDString::get(VMContext, Name));
948 Elts.push_back(CompileUnit.getNode());
949 Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
950 Elts.push_back(Type.getNode());
951 Elts.insert(Elts.end(), addr.begin(), addr.end());
953 return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
957 /// CreateBlock - This creates a descriptor for a lexical block with the
958 /// specified parent VMContext.
959 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context) {
961 GetTagConstant(dwarf::DW_TAG_lexical_block),
964 return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 2));
967 /// CreateLocation - Creates a debug info location.
968 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
969 DIScope S, DILocation OrigLoc) {
971 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
972 ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
976 return DILocation(MDNode::get(VMContext, &Elts[0], 4));
979 /// CreateLocation - Creates a debug info location.
980 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
981 DIScope S, MDNode *OrigLoc) {
983 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
984 ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
988 return DILocation(MDNode::get(VMContext, &Elts[0], 4));
991 //===----------------------------------------------------------------------===//
992 // DIFactory: Routines for inserting code into a function
993 //===----------------------------------------------------------------------===//
995 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
996 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
997 Instruction *InsertBefore) {
998 // Cast the storage to a {}* for the call to llvm.dbg.declare.
999 Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertBefore);
1002 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1004 Value *Args[] = { Storage, D.getNode() };
1005 return CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1008 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1009 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1010 BasicBlock *InsertAtEnd) {
1011 // Cast the storage to a {}* for the call to llvm.dbg.declare.
1012 Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertAtEnd);
1015 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1017 Value *Args[] = { Storage, D.getNode() };
1018 return CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);
1022 //===----------------------------------------------------------------------===//
1023 // DebugInfoFinder implementations.
1024 //===----------------------------------------------------------------------===//
1026 /// processModule - Process entire module and collect debug info.
1027 void DebugInfoFinder::processModule(Module &M) {
1029 MetadataContext &TheMetadata = M.getContext().getMetadata();
1030 unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
1032 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1033 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1034 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1036 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1037 processDeclare(DDI);
1039 if (MDNode *L = TheMetadata.getMD(MDDbgKind, BI))
1040 processLocation(DILocation(L));
1043 NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
1047 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1048 DIGlobalVariable DIG(cast<MDNode>(NMD->getElement(i)));
1049 if (addGlobalVariable(DIG)) {
1050 addCompileUnit(DIG.getCompileUnit());
1051 processType(DIG.getType());
1056 /// processLocation - Process DILocation.
1057 void DebugInfoFinder::processLocation(DILocation Loc) {
1058 if (Loc.isNull()) return;
1059 DIScope S(Loc.getScope().getNode());
1060 if (S.isNull()) return;
1061 if (S.isCompileUnit())
1062 addCompileUnit(DICompileUnit(S.getNode()));
1063 else if (S.isSubprogram())
1064 processSubprogram(DISubprogram(S.getNode()));
1065 else if (S.isLexicalBlock())
1066 processLexicalBlock(DILexicalBlock(S.getNode()));
1067 processLocation(Loc.getOrigLocation());
1070 /// processType - Process DIType.
1071 void DebugInfoFinder::processType(DIType DT) {
1075 addCompileUnit(DT.getCompileUnit());
1076 if (DT.isCompositeType()) {
1077 DICompositeType DCT(DT.getNode());
1078 processType(DCT.getTypeDerivedFrom());
1079 DIArray DA = DCT.getTypeArray();
1081 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1082 DIDescriptor D = DA.getElement(i);
1083 DIType TypeE = DIType(D.getNode());
1084 if (!TypeE.isNull())
1087 processSubprogram(DISubprogram(D.getNode()));
1089 } else if (DT.isDerivedType()) {
1090 DIDerivedType DDT(DT.getNode());
1092 processType(DDT.getTypeDerivedFrom());
1096 /// processLexicalBlock
1097 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1100 DIScope Context = LB.getContext();
1101 if (Context.isLexicalBlock())
1102 return processLexicalBlock(DILexicalBlock(Context.getNode()));
1104 return processSubprogram(DISubprogram(Context.getNode()));
1107 /// processSubprogram - Process DISubprogram.
1108 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1111 if (!addSubprogram(SP))
1113 addCompileUnit(SP.getCompileUnit());
1114 processType(SP.getType());
1117 /// processDeclare - Process DbgDeclareInst.
1118 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1119 DIVariable DV(cast<MDNode>(DDI->getVariable()));
1123 if (!NodesSeen.insert(DV.getNode()))
1126 addCompileUnit(DV.getCompileUnit());
1127 processType(DV.getType());
1130 /// addType - Add type into Tys.
1131 bool DebugInfoFinder::addType(DIType DT) {
1135 if (!NodesSeen.insert(DT.getNode()))
1138 TYs.push_back(DT.getNode());
1142 /// addCompileUnit - Add compile unit into CUs.
1143 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1147 if (!NodesSeen.insert(CU.getNode()))
1150 CUs.push_back(CU.getNode());
1154 /// addGlobalVariable - Add global variable into GVs.
1155 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1159 if (!NodesSeen.insert(DIG.getNode()))
1162 GVs.push_back(DIG.getNode());
1166 // addSubprogram - Add subprgoram into SPs.
1167 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1171 if (!NodesSeen.insert(SP.getNode()))
1174 SPs.push_back(SP.getNode());
1179 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
1180 /// is the stoppoint that dominates this instruction.
1181 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
1182 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
1185 const BasicBlock *BB = Inst->getParent();
1186 BasicBlock::const_iterator I = Inst, B;
1190 // A BB consisting only of a terminator can't have a stoppoint.
1193 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1197 // This BB didn't have a stoppoint: if there is only one predecessor, look
1198 // for a stoppoint there. We could use getIDom(), but that would require
1200 BB = I->getParent()->getUniquePredecessor();
1202 I = BB->getTerminator();
1208 /// findBBStopPoint - Find the stoppoint corresponding to first real
1209 /// (non-debug intrinsic) instruction in this Basic Block, and return the
1210 /// stoppoint for it.
1211 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
1212 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1213 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1216 // Fallback to looking for stoppoint of unique predecessor. Useful if this
1217 // BB contains no stoppoints, but unique predecessor does.
1218 BB = BB->getUniquePredecessor();
1220 return findStopPoint(BB->getTerminator());
1225 Value *findDbgGlobalDeclare(GlobalVariable *V) {
1226 const Module *M = V->getParent();
1227 NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1231 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1232 DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getElement(i)));
1235 if (DIG.getGlobal() == V)
1236 return DIG.getNode();
1241 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1242 /// It looks through pointer casts too.
1243 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1245 V = V->stripPointerCasts();
1247 // Look for the bitcast.
1248 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1250 if (isa<BitCastInst>(I)) {
1251 const DbgDeclareInst *DDI = findDbgDeclare(*I, false);
1252 if (DDI) return DDI;
1257 // Find llvm.dbg.declare among uses of the instruction.
1258 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1260 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1266 bool getLocationInfo(const Value *V, std::string &DisplayName,
1267 std::string &Type, unsigned &LineNo, std::string &File,
1272 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1273 Value *DIGV = findDbgGlobalDeclare(GV);
1274 if (!DIGV) return false;
1275 DIGlobalVariable Var(cast<MDNode>(DIGV));
1277 if (const char *D = Var.getDisplayName())
1279 LineNo = Var.getLineNumber();
1280 Unit = Var.getCompileUnit();
1281 TypeD = Var.getType();
1283 const DbgDeclareInst *DDI = findDbgDeclare(V);
1284 if (!DDI) return false;
1285 DIVariable Var(cast<MDNode>(DDI->getVariable()));
1287 if (const char *D = Var.getName())
1289 LineNo = Var.getLineNumber();
1290 Unit = Var.getCompileUnit();
1291 TypeD = Var.getType();
1294 if (const char *T = TypeD.getName())
1296 if (const char *F = Unit.getFilename())
1298 if (const char *D = Unit.getDirectory())
1303 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1305 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1306 CodeGenOpt::Level OptLev) {
1307 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1310 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1312 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1313 CodeGenOpt::Level OptLev) {
1314 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1317 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1319 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1320 CodeGenOpt::Level OptLev) {
1321 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1324 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1326 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1327 CodeGenOpt::Level OptLev) {
1328 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1332 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1334 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1335 CodeGenOpt::Level OptLev) {
1336 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1339 /// ExtractDebugLocation - Extract debug location information
1340 /// from llvm.dbg.stoppoint intrinsic.
1341 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1342 DebugLocTracker &DebugLocInfo) {
1344 Value *Context = SPI.getContext();
1346 // If this location is already tracked then use it.
1347 DebugLocTuple Tuple(cast<MDNode>(Context), NULL, SPI.getLine(),
1349 DenseMap<DebugLocTuple, unsigned>::iterator II
1350 = DebugLocInfo.DebugIdMap.find(Tuple);
1351 if (II != DebugLocInfo.DebugIdMap.end())
1352 return DebugLoc::get(II->second);
1354 // Add a new location entry.
1355 unsigned Id = DebugLocInfo.DebugLocations.size();
1356 DebugLocInfo.DebugLocations.push_back(Tuple);
1357 DebugLocInfo.DebugIdMap[Tuple] = Id;
1359 return DebugLoc::get(Id);
1362 /// ExtractDebugLocation - Extract debug location information
1363 /// from DILocation.
1364 DebugLoc ExtractDebugLocation(DILocation &Loc,
1365 DebugLocTracker &DebugLocInfo) {
1367 MDNode *Context = Loc.getScope().getNode();
1368 MDNode *InlinedLoc = NULL;
1369 if (!Loc.getOrigLocation().isNull())
1370 InlinedLoc = Loc.getOrigLocation().getNode();
1371 // If this location is already tracked then use it.
1372 DebugLocTuple Tuple(Context, InlinedLoc, Loc.getLineNumber(),
1373 Loc.getColumnNumber());
1374 DenseMap<DebugLocTuple, unsigned>::iterator II
1375 = DebugLocInfo.DebugIdMap.find(Tuple);
1376 if (II != DebugLocInfo.DebugIdMap.end())
1377 return DebugLoc::get(II->second);
1379 // Add a new location entry.
1380 unsigned Id = DebugLocInfo.DebugLocations.size();
1381 DebugLocInfo.DebugLocations.push_back(Tuple);
1382 DebugLocInfo.DebugIdMap[Tuple] = Id;
1384 return DebugLoc::get(Id);
1387 /// ExtractDebugLocation - Extract debug location information
1388 /// from llvm.dbg.func_start intrinsic.
1389 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1390 DebugLocTracker &DebugLocInfo) {
1392 Value *SP = FSI.getSubprogram();
1394 DISubprogram Subprogram(cast<MDNode>(SP));
1395 unsigned Line = Subprogram.getLineNumber();
1396 DICompileUnit CU(Subprogram.getCompileUnit());
1398 // If this location is already tracked then use it.
1399 DebugLocTuple Tuple(CU.getNode(), NULL, Line, /* Column */ 0);
1400 DenseMap<DebugLocTuple, unsigned>::iterator II
1401 = DebugLocInfo.DebugIdMap.find(Tuple);
1402 if (II != DebugLocInfo.DebugIdMap.end())
1403 return DebugLoc::get(II->second);
1405 // Add a new location entry.
1406 unsigned Id = DebugLocInfo.DebugLocations.size();
1407 DebugLocInfo.DebugLocations.push_back(Tuple);
1408 DebugLocInfo.DebugIdMap[Tuple] = Id;
1410 return DebugLoc::get(Id);