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()), StopPointFn(0), FuncStartFn(0),
610 RegionStartFn(0), RegionEndFn(0),
612 EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
615 Constant *DIFactory::GetTagConstant(unsigned TAG) {
616 assert((TAG & LLVMDebugVersionMask) == 0 &&
617 "Tag too large for debug encoding!");
618 return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
621 //===----------------------------------------------------------------------===//
622 // DIFactory: Primary Constructors
623 //===----------------------------------------------------------------------===//
625 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
626 /// This implicitly uniques the arrays created.
627 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
628 SmallVector<Value*, 16> Elts;
631 Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
633 for (unsigned i = 0; i != NumTys; ++i)
634 Elts.push_back(Tys[i].getNode());
636 return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
639 /// GetOrCreateSubrange - Create a descriptor for a value range. This
640 /// implicitly uniques the values returned.
641 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
643 GetTagConstant(dwarf::DW_TAG_subrange_type),
644 ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
645 ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
648 return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
653 /// CreateCompileUnit - Create a new descriptor for the specified compile
654 /// unit. Note that this does not unique compile units within the module.
655 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
662 unsigned RunTimeVer) {
664 GetTagConstant(dwarf::DW_TAG_compile_unit),
665 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
666 ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
667 MDString::get(VMContext, Filename),
668 MDString::get(VMContext, Directory),
669 MDString::get(VMContext, Producer),
670 ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
671 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
672 MDString::get(VMContext, Flags),
673 ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
676 return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
679 /// CreateEnumerator - Create a single enumerator value.
680 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
682 GetTagConstant(dwarf::DW_TAG_enumerator),
683 MDString::get(VMContext, Name),
684 ConstantInt::get(Type::getInt64Ty(VMContext), Val)
686 return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
690 /// CreateBasicType - Create a basic type like int, float, etc.
691 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
693 DICompileUnit CompileUnit,
696 uint64_t AlignInBits,
697 uint64_t OffsetInBits, unsigned Flags,
700 GetTagConstant(dwarf::DW_TAG_base_type),
702 MDString::get(VMContext, Name),
703 CompileUnit.getNode(),
704 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
705 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
706 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
707 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
708 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
709 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
711 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
715 /// CreateBasicType - Create a basic type like int, float, etc.
716 DIBasicType DIFactory::CreateBasicTypeEx(DIDescriptor Context,
718 DICompileUnit CompileUnit,
720 Constant *SizeInBits,
721 Constant *AlignInBits,
722 Constant *OffsetInBits, unsigned Flags,
725 GetTagConstant(dwarf::DW_TAG_base_type),
727 MDString::get(VMContext, Name),
728 CompileUnit.getNode(),
729 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
733 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
734 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
736 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
740 /// CreateDerivedType - Create a derived type like const qualified type,
741 /// pointer, typedef, etc.
742 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
743 DIDescriptor Context,
745 DICompileUnit CompileUnit,
748 uint64_t AlignInBits,
749 uint64_t OffsetInBits,
751 DIType DerivedFrom) {
755 MDString::get(VMContext, Name),
756 CompileUnit.getNode(),
757 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
758 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
759 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
760 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
761 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
762 DerivedFrom.getNode(),
764 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
768 /// CreateDerivedType - Create a derived type like const qualified type,
769 /// pointer, typedef, etc.
770 DIDerivedType DIFactory::CreateDerivedTypeEx(unsigned Tag,
771 DIDescriptor Context,
773 DICompileUnit CompileUnit,
775 Constant *SizeInBits,
776 Constant *AlignInBits,
777 Constant *OffsetInBits,
779 DIType DerivedFrom) {
783 MDString::get(VMContext, Name),
784 CompileUnit.getNode(),
785 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
789 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
790 DerivedFrom.getNode(),
792 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
796 /// CreateCompositeType - Create a composite type like array, struct, etc.
797 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
798 DIDescriptor Context,
800 DICompileUnit CompileUnit,
803 uint64_t AlignInBits,
804 uint64_t OffsetInBits,
808 unsigned RuntimeLang) {
813 MDString::get(VMContext, Name),
814 CompileUnit.getNode(),
815 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
816 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
817 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
818 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
819 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
820 DerivedFrom.getNode(),
822 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
824 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
828 /// CreateCompositeType - Create a composite type like array, struct, etc.
829 DICompositeType DIFactory::CreateCompositeTypeEx(unsigned Tag,
830 DIDescriptor Context,
832 DICompileUnit CompileUnit,
834 Constant *SizeInBits,
835 Constant *AlignInBits,
836 Constant *OffsetInBits,
840 unsigned RuntimeLang) {
845 MDString::get(VMContext, Name),
846 CompileUnit.getNode(),
847 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
851 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
852 DerivedFrom.getNode(),
854 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
856 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
860 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
861 /// See comments in DISubprogram for descriptions of these fields. This
862 /// method does not unique the generated descriptors.
863 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
865 StringRef DisplayName,
866 StringRef LinkageName,
867 DICompileUnit CompileUnit,
868 unsigned LineNo, DIType Type,
873 GetTagConstant(dwarf::DW_TAG_subprogram),
874 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
876 MDString::get(VMContext, Name),
877 MDString::get(VMContext, DisplayName),
878 MDString::get(VMContext, LinkageName),
879 CompileUnit.getNode(),
880 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
882 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
883 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition)
885 return DISubprogram(MDNode::get(VMContext, &Elts[0], 11));
888 /// CreateGlobalVariable - Create a new descriptor for the specified global.
890 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
891 StringRef DisplayName,
892 StringRef LinkageName,
893 DICompileUnit CompileUnit,
894 unsigned LineNo, DIType Type,bool isLocalToUnit,
895 bool isDefinition, llvm::GlobalVariable *Val) {
897 GetTagConstant(dwarf::DW_TAG_variable),
898 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
900 MDString::get(VMContext, Name),
901 MDString::get(VMContext, DisplayName),
902 MDString::get(VMContext, LinkageName),
903 CompileUnit.getNode(),
904 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
906 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
907 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
911 Value *const *Vs = &Elts[0];
912 MDNode *Node = MDNode::get(VMContext,Vs, 12);
914 // Create a named metadata so that we do not lose this mdnode.
915 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
916 NMD->addElement(Node);
918 return DIGlobalVariable(Node);
922 /// CreateVariable - Create a new descriptor for the specified variable.
923 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
925 DICompileUnit CompileUnit, unsigned LineNo,
930 MDString::get(VMContext, Name),
931 CompileUnit.getNode(),
932 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
935 return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
939 /// CreateComplexVariable - Create a new descriptor for the specified variable
940 /// which has a complex address expression for its address.
941 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
942 const std::string &Name,
943 DICompileUnit CompileUnit,
945 DIType Type, SmallVector<Value *, 9> &addr) {
946 SmallVector<Value *, 9> Elts;
947 Elts.push_back(GetTagConstant(Tag));
948 Elts.push_back(Context.getNode());
949 Elts.push_back(MDString::get(VMContext, Name));
950 Elts.push_back(CompileUnit.getNode());
951 Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
952 Elts.push_back(Type.getNode());
953 Elts.insert(Elts.end(), addr.begin(), addr.end());
955 return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
959 /// CreateBlock - This creates a descriptor for a lexical block with the
960 /// specified parent VMContext.
961 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context) {
963 GetTagConstant(dwarf::DW_TAG_lexical_block),
966 return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 2));
969 /// CreateLocation - Creates a debug info location.
970 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
971 DIScope S, DILocation OrigLoc) {
973 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
974 ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
978 return DILocation(MDNode::get(VMContext, &Elts[0], 4));
982 //===----------------------------------------------------------------------===//
983 // DIFactory: Routines for inserting code into a function
984 //===----------------------------------------------------------------------===//
986 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
987 /// inserting it at the end of the specified basic block.
988 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
989 unsigned ColNo, BasicBlock *BB) {
991 // Lazily construct llvm.dbg.stoppoint function.
993 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
994 llvm::Intrinsic::dbg_stoppoint);
996 // Invoke llvm.dbg.stoppoint
998 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo),
999 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), ColNo),
1002 CallInst::Create(StopPointFn, Args, Args+3, "", BB);
1005 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
1006 /// mark the start of the specified subprogram.
1007 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
1008 // Lazily construct llvm.dbg.func.start.
1010 FuncStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_func_start);
1012 // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
1013 CallInst::Create(FuncStartFn, SP.getNode(), "", BB);
1016 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
1017 /// mark the start of a region for the specified scoping descriptor.
1018 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
1019 // Lazily construct llvm.dbg.region.start function.
1021 RegionStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_start);
1023 // Call llvm.dbg.func.start.
1024 CallInst::Create(RegionStartFn, D.getNode(), "", BB);
1027 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
1028 /// mark the end of a region for the specified scoping descriptor.
1029 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
1030 // Lazily construct llvm.dbg.region.end function.
1032 RegionEndFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_end);
1034 // Call llvm.dbg.region.end.
1035 CallInst::Create(RegionEndFn, D.getNode(), "", BB);
1038 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1039 void DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1040 Instruction *InsertBefore) {
1041 // Cast the storage to a {}* for the call to llvm.dbg.declare.
1042 Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertBefore);
1045 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1047 Value *Args[] = { Storage, D.getNode() };
1048 CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1051 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1052 void DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1053 BasicBlock *InsertAtEnd) {
1054 // Cast the storage to a {}* for the call to llvm.dbg.declare.
1055 Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertAtEnd);
1058 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1060 Value *Args[] = { Storage, D.getNode() };
1061 CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);
1065 //===----------------------------------------------------------------------===//
1066 // DebugInfoFinder implementations.
1067 //===----------------------------------------------------------------------===//
1069 /// processModule - Process entire module and collect debug info.
1070 void DebugInfoFinder::processModule(Module &M) {
1072 #ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
1073 MetadataContext &TheMetadata = M.getContext().getMetadata();
1074 unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
1076 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1077 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1078 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1080 if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(BI))
1081 processStopPoint(SPI);
1082 else if (DbgFuncStartInst *FSI = dyn_cast<DbgFuncStartInst>(BI))
1083 processFuncStart(FSI);
1084 else if (DbgRegionStartInst *DRS = dyn_cast<DbgRegionStartInst>(BI))
1085 processRegionStart(DRS);
1086 else if (DbgRegionEndInst *DRE = dyn_cast<DbgRegionEndInst>(BI))
1087 processRegionEnd(DRE);
1088 else if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1089 processDeclare(DDI);
1090 #ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
1091 else if (MDDbgKind) {
1092 if (MDNode *L = TheMetadata.getMD(MDDbgKind, BI)) {
1094 DIScope S(Loc.getScope().getNode());
1095 if (S.isCompileUnit())
1096 addCompileUnit(DICompileUnit(S.getNode()));
1097 else if (S.isSubprogram())
1098 processSubprogram(DISubprogram(S.getNode()));
1099 else if (S.isLexicalBlock())
1100 processLexicalBlock(DILexicalBlock(S.getNode()));
1106 NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
1110 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1111 DIGlobalVariable DIG(cast<MDNode>(NMD->getElement(i)));
1112 if (addGlobalVariable(DIG)) {
1113 addCompileUnit(DIG.getCompileUnit());
1114 processType(DIG.getType());
1119 /// processType - Process DIType.
1120 void DebugInfoFinder::processType(DIType DT) {
1124 addCompileUnit(DT.getCompileUnit());
1125 if (DT.isCompositeType()) {
1126 DICompositeType DCT(DT.getNode());
1127 processType(DCT.getTypeDerivedFrom());
1128 DIArray DA = DCT.getTypeArray();
1130 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1131 DIDescriptor D = DA.getElement(i);
1132 DIType TypeE = DIType(D.getNode());
1133 if (!TypeE.isNull())
1136 processSubprogram(DISubprogram(D.getNode()));
1138 } else if (DT.isDerivedType()) {
1139 DIDerivedType DDT(DT.getNode());
1141 processType(DDT.getTypeDerivedFrom());
1145 /// processLexicalBlock
1146 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1149 DIScope Context = LB.getContext();
1150 if (Context.isLexicalBlock())
1151 return processLexicalBlock(DILexicalBlock(Context.getNode()));
1153 return processSubprogram(DISubprogram(Context.getNode()));
1156 /// processSubprogram - Process DISubprogram.
1157 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1160 if (!addSubprogram(SP))
1162 addCompileUnit(SP.getCompileUnit());
1163 processType(SP.getType());
1166 /// processStopPoint - Process DbgStopPointInst.
1167 void DebugInfoFinder::processStopPoint(DbgStopPointInst *SPI) {
1168 MDNode *Context = dyn_cast<MDNode>(SPI->getContext());
1169 addCompileUnit(DICompileUnit(Context));
1172 /// processFuncStart - Process DbgFuncStartInst.
1173 void DebugInfoFinder::processFuncStart(DbgFuncStartInst *FSI) {
1174 MDNode *SP = dyn_cast<MDNode>(FSI->getSubprogram());
1175 processSubprogram(DISubprogram(SP));
1178 /// processRegionStart - Process DbgRegionStart.
1179 void DebugInfoFinder::processRegionStart(DbgRegionStartInst *DRS) {
1180 MDNode *SP = dyn_cast<MDNode>(DRS->getContext());
1181 processSubprogram(DISubprogram(SP));
1184 /// processRegionEnd - Process DbgRegionEnd.
1185 void DebugInfoFinder::processRegionEnd(DbgRegionEndInst *DRE) {
1186 MDNode *SP = dyn_cast<MDNode>(DRE->getContext());
1187 processSubprogram(DISubprogram(SP));
1190 /// processDeclare - Process DbgDeclareInst.
1191 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1192 DIVariable DV(cast<MDNode>(DDI->getVariable()));
1196 if (!NodesSeen.insert(DV.getNode()))
1199 addCompileUnit(DV.getCompileUnit());
1200 processType(DV.getType());
1203 /// addType - Add type into Tys.
1204 bool DebugInfoFinder::addType(DIType DT) {
1208 if (!NodesSeen.insert(DT.getNode()))
1211 TYs.push_back(DT.getNode());
1215 /// addCompileUnit - Add compile unit into CUs.
1216 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1220 if (!NodesSeen.insert(CU.getNode()))
1223 CUs.push_back(CU.getNode());
1227 /// addGlobalVariable - Add global variable into GVs.
1228 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1232 if (!NodesSeen.insert(DIG.getNode()))
1235 GVs.push_back(DIG.getNode());
1239 // addSubprogram - Add subprgoram into SPs.
1240 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1244 if (!NodesSeen.insert(SP.getNode()))
1247 SPs.push_back(SP.getNode());
1252 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
1253 /// is the stoppoint that dominates this instruction.
1254 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
1255 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
1258 const BasicBlock *BB = Inst->getParent();
1259 BasicBlock::const_iterator I = Inst, B;
1263 // A BB consisting only of a terminator can't have a stoppoint.
1266 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1270 // This BB didn't have a stoppoint: if there is only one predecessor, look
1271 // for a stoppoint there. We could use getIDom(), but that would require
1273 BB = I->getParent()->getUniquePredecessor();
1275 I = BB->getTerminator();
1281 /// findBBStopPoint - Find the stoppoint corresponding to first real
1282 /// (non-debug intrinsic) instruction in this Basic Block, and return the
1283 /// stoppoint for it.
1284 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
1285 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1286 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1289 // Fallback to looking for stoppoint of unique predecessor. Useful if this
1290 // BB contains no stoppoints, but unique predecessor does.
1291 BB = BB->getUniquePredecessor();
1293 return findStopPoint(BB->getTerminator());
1298 Value *findDbgGlobalDeclare(GlobalVariable *V) {
1299 const Module *M = V->getParent();
1300 NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1304 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1305 DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getElement(i)));
1308 if (DIG.getGlobal() == V)
1309 return DIG.getNode();
1314 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1315 /// It looks through pointer casts too.
1316 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1318 V = V->stripPointerCasts();
1320 // Look for the bitcast.
1321 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1323 if (isa<BitCastInst>(I)) {
1324 const DbgDeclareInst *DDI = findDbgDeclare(*I, false);
1325 if (DDI) return DDI;
1330 // Find llvm.dbg.declare among uses of the instruction.
1331 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1333 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1339 bool getLocationInfo(const Value *V, std::string &DisplayName,
1340 std::string &Type, unsigned &LineNo, std::string &File,
1345 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1346 Value *DIGV = findDbgGlobalDeclare(GV);
1347 if (!DIGV) return false;
1348 DIGlobalVariable Var(cast<MDNode>(DIGV));
1350 if (const char *D = Var.getDisplayName())
1352 LineNo = Var.getLineNumber();
1353 Unit = Var.getCompileUnit();
1354 TypeD = Var.getType();
1356 const DbgDeclareInst *DDI = findDbgDeclare(V);
1357 if (!DDI) return false;
1358 DIVariable Var(cast<MDNode>(DDI->getVariable()));
1360 if (const char *D = Var.getName())
1362 LineNo = Var.getLineNumber();
1363 Unit = Var.getCompileUnit();
1364 TypeD = Var.getType();
1367 if (const char *T = TypeD.getName())
1369 if (const char *F = Unit.getFilename())
1371 if (const char *D = Unit.getDirectory())
1376 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1378 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1379 CodeGenOpt::Level OptLev) {
1380 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1383 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1385 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1386 CodeGenOpt::Level OptLev) {
1387 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1390 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1392 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1393 CodeGenOpt::Level OptLev) {
1394 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1397 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1399 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1400 CodeGenOpt::Level OptLev) {
1401 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1405 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1407 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1408 CodeGenOpt::Level OptLev) {
1409 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1412 /// ExtractDebugLocation - Extract debug location information
1413 /// from llvm.dbg.stoppoint intrinsic.
1414 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1415 DebugLocTracker &DebugLocInfo) {
1417 Value *Context = SPI.getContext();
1419 // If this location is already tracked then use it.
1420 DebugLocTuple Tuple(cast<MDNode>(Context), NULL, SPI.getLine(),
1422 DenseMap<DebugLocTuple, unsigned>::iterator II
1423 = DebugLocInfo.DebugIdMap.find(Tuple);
1424 if (II != DebugLocInfo.DebugIdMap.end())
1425 return DebugLoc::get(II->second);
1427 // Add a new location entry.
1428 unsigned Id = DebugLocInfo.DebugLocations.size();
1429 DebugLocInfo.DebugLocations.push_back(Tuple);
1430 DebugLocInfo.DebugIdMap[Tuple] = Id;
1432 return DebugLoc::get(Id);
1435 /// ExtractDebugLocation - Extract debug location information
1436 /// from DILocation.
1437 DebugLoc ExtractDebugLocation(DILocation &Loc,
1438 DebugLocTracker &DebugLocInfo) {
1440 MDNode *Context = Loc.getScope().getNode();
1441 MDNode *InlinedLoc = NULL;
1442 if (!Loc.getOrigLocation().isNull())
1443 InlinedLoc = Loc.getOrigLocation().getNode();
1444 // If this location is already tracked then use it.
1445 DebugLocTuple Tuple(Context, InlinedLoc, Loc.getLineNumber(),
1446 Loc.getColumnNumber());
1447 DenseMap<DebugLocTuple, unsigned>::iterator II
1448 = DebugLocInfo.DebugIdMap.find(Tuple);
1449 if (II != DebugLocInfo.DebugIdMap.end())
1450 return DebugLoc::get(II->second);
1452 // Add a new location entry.
1453 unsigned Id = DebugLocInfo.DebugLocations.size();
1454 DebugLocInfo.DebugLocations.push_back(Tuple);
1455 DebugLocInfo.DebugIdMap[Tuple] = Id;
1457 return DebugLoc::get(Id);
1460 /// ExtractDebugLocation - Extract debug location information
1461 /// from llvm.dbg.func_start intrinsic.
1462 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1463 DebugLocTracker &DebugLocInfo) {
1465 Value *SP = FSI.getSubprogram();
1467 DISubprogram Subprogram(cast<MDNode>(SP));
1468 unsigned Line = Subprogram.getLineNumber();
1469 DICompileUnit CU(Subprogram.getCompileUnit());
1471 // If this location is already tracked then use it.
1472 DebugLocTuple Tuple(CU.getNode(), NULL, Line, /* Column */ 0);
1473 DenseMap<DebugLocTuple, unsigned>::iterator II
1474 = DebugLocInfo.DebugIdMap.find(Tuple);
1475 if (II != DebugLocInfo.DebugIdMap.end())
1476 return DebugLoc::get(II->second);
1478 // Add a new location entry.
1479 unsigned Id = DebugLocInfo.DebugLocations.size();
1480 DebugLocInfo.DebugLocations.push_back(Tuple);
1481 DebugLocInfo.DebugIdMap[Tuple] = Id;
1483 return DebugLoc::get(Id);
1486 /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1487 bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1488 DISubprogram Subprogram(cast<MDNode>(FSI.getSubprogram()));
1489 if (Subprogram.describes(CurrentFn))
1495 /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1496 bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1497 DISubprogram Subprogram(cast<MDNode>(REI.getContext()));
1498 if (Subprogram.isNull() || Subprogram.describes(CurrentFn))