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 (getContext().isNull())
372 DICompileUnit CU = getCompileUnit();
373 if (!CU.isNull() && !CU.Verify())
376 DIType Ty = getType();
386 /// Verify - Verify that a variable descriptor is well formed.
387 bool DIVariable::Verify() const {
391 if (getContext().isNull())
394 DIType Ty = getType();
401 /// getOriginalTypeSize - If this type is derived from a base type then
402 /// return base type size.
403 uint64_t DIDerivedType::getOriginalTypeSize() const {
404 DIType BT = getTypeDerivedFrom();
405 if (!BT.isNull() && BT.isDerivedType())
406 return DIDerivedType(BT.getNode()).getOriginalTypeSize();
408 return getSizeInBits();
409 return BT.getSizeInBits();
412 /// describes - Return true if this subprogram provides debugging
413 /// information for the function F.
414 bool DISubprogram::describes(const Function *F) {
415 assert (F && "Invalid function");
416 const char *Name = getLinkageName();
419 if (strcmp(F->getName().data(), Name) == 0)
424 const char *DIScope::getFilename() const {
425 if (isLexicalBlock())
426 return DILexicalBlock(DbgNode).getFilename();
427 else if (isSubprogram())
428 return DISubprogram(DbgNode).getFilename();
429 else if (isCompileUnit())
430 return DICompileUnit(DbgNode).getFilename();
432 assert (0 && "Invalid DIScope!");
436 const char *DIScope::getDirectory() const {
437 if (isLexicalBlock())
438 return DILexicalBlock(DbgNode).getDirectory();
439 else if (isSubprogram())
440 return DISubprogram(DbgNode).getDirectory();
441 else if (isCompileUnit())
442 return DICompileUnit(DbgNode).getDirectory();
444 assert (0 && "Invalid DIScope!");
448 //===----------------------------------------------------------------------===//
449 // DIDescriptor: dump routines for all descriptors.
450 //===----------------------------------------------------------------------===//
453 /// dump - Print descriptor.
454 void DIDescriptor::dump() const {
455 errs() << "[" << dwarf::TagString(getTag()) << "] ";
456 errs().write_hex((intptr_t) &*DbgNode) << ']';
459 /// dump - Print compile unit.
460 void DICompileUnit::dump() const {
462 errs() << " [" << dwarf::LanguageString(getLanguage()) << "] ";
464 errs() << " [" << getDirectory() << "/" << getFilename() << " ]";
467 /// dump - Print type.
468 void DIType::dump() const {
469 if (isNull()) return;
471 if (const char *Res = getName())
472 errs() << " [" << Res << "] ";
474 unsigned Tag = getTag();
475 errs() << " [" << dwarf::TagString(Tag) << "] ";
477 // TODO : Print context
478 getCompileUnit().dump();
480 << getLineNumber() << ", "
481 << getSizeInBits() << ", "
482 << getAlignInBits() << ", "
487 errs() << " [private] ";
488 else if (isProtected())
489 errs() << " [protected] ";
495 DIBasicType(DbgNode).dump();
496 else if (isDerivedType())
497 DIDerivedType(DbgNode).dump();
498 else if (isCompositeType())
499 DICompositeType(DbgNode).dump();
501 errs() << "Invalid DIType\n";
508 /// dump - Print basic type.
509 void DIBasicType::dump() const {
510 errs() << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
513 /// dump - Print derived type.
514 void DIDerivedType::dump() const {
515 errs() << "\n\t Derived From: "; getTypeDerivedFrom().dump();
518 /// dump - Print composite type.
519 void DICompositeType::dump() const {
520 DIArray A = getTypeArray();
523 errs() << " [" << A.getNumElements() << " elements]";
526 /// dump - Print global.
527 void DIGlobal::dump() const {
528 if (const char *Res = getName())
529 errs() << " [" << Res << "] ";
531 unsigned Tag = getTag();
532 errs() << " [" << dwarf::TagString(Tag) << "] ";
534 // TODO : Print context
535 getCompileUnit().dump();
536 errs() << " [" << getLineNumber() << "] ";
539 errs() << " [local] ";
544 if (isGlobalVariable())
545 DIGlobalVariable(DbgNode).dump();
550 /// dump - Print subprogram.
551 void DISubprogram::dump() const {
552 if (const char *Res = getName())
553 errs() << " [" << Res << "] ";
555 unsigned Tag = getTag();
556 errs() << " [" << dwarf::TagString(Tag) << "] ";
558 // TODO : Print context
559 getCompileUnit().dump();
560 errs() << " [" << getLineNumber() << "] ";
563 errs() << " [local] ";
571 /// dump - Print global variable.
572 void DIGlobalVariable::dump() const {
578 /// dump - Print variable.
579 void DIVariable::dump() const {
580 if (const char *Res = getName())
581 errs() << " [" << Res << "] ";
583 getCompileUnit().dump();
584 errs() << " [" << getLineNumber() << "] ";
588 // FIXME: Dump complex addresses
591 //===----------------------------------------------------------------------===//
592 // DIFactory: Basic Helpers
593 //===----------------------------------------------------------------------===//
595 DIFactory::DIFactory(Module &m)
596 : M(m), VMContext(M.getContext()), StopPointFn(0), FuncStartFn(0),
597 RegionStartFn(0), RegionEndFn(0),
599 EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
602 Constant *DIFactory::GetTagConstant(unsigned TAG) {
603 assert((TAG & LLVMDebugVersionMask) == 0 &&
604 "Tag too large for debug encoding!");
605 return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
608 //===----------------------------------------------------------------------===//
609 // DIFactory: Primary Constructors
610 //===----------------------------------------------------------------------===//
612 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
613 /// This implicitly uniques the arrays created.
614 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
615 SmallVector<Value*, 16> Elts;
618 Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
620 for (unsigned i = 0; i != NumTys; ++i)
621 Elts.push_back(Tys[i].getNode());
623 return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
626 /// GetOrCreateSubrange - Create a descriptor for a value range. This
627 /// implicitly uniques the values returned.
628 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
630 GetTagConstant(dwarf::DW_TAG_subrange_type),
631 ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
632 ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
635 return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
640 /// CreateCompileUnit - Create a new descriptor for the specified compile
641 /// unit. Note that this does not unique compile units within the module.
642 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
649 unsigned RunTimeVer) {
651 GetTagConstant(dwarf::DW_TAG_compile_unit),
652 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
653 ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
654 MDString::get(VMContext, Filename),
655 MDString::get(VMContext, Directory),
656 MDString::get(VMContext, Producer),
657 ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
658 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
659 MDString::get(VMContext, Flags),
660 ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
663 return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
666 /// CreateEnumerator - Create a single enumerator value.
667 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
669 GetTagConstant(dwarf::DW_TAG_enumerator),
670 MDString::get(VMContext, Name),
671 ConstantInt::get(Type::getInt64Ty(VMContext), Val)
673 return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
677 /// CreateBasicType - Create a basic type like int, float, etc.
678 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
680 DICompileUnit CompileUnit,
683 uint64_t AlignInBits,
684 uint64_t OffsetInBits, unsigned Flags,
687 GetTagConstant(dwarf::DW_TAG_base_type),
689 MDString::get(VMContext, Name),
690 CompileUnit.getNode(),
691 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
692 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
693 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
694 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
695 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
696 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
698 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
702 /// CreateBasicType - Create a basic type like int, float, etc.
703 DIBasicType DIFactory::CreateBasicTypeEx(DIDescriptor Context,
705 DICompileUnit CompileUnit,
707 Constant *SizeInBits,
708 Constant *AlignInBits,
709 Constant *OffsetInBits, unsigned Flags,
712 GetTagConstant(dwarf::DW_TAG_base_type),
714 MDString::get(VMContext, Name),
715 CompileUnit.getNode(),
716 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
720 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
721 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
723 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
727 /// CreateDerivedType - Create a derived type like const qualified type,
728 /// pointer, typedef, etc.
729 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
730 DIDescriptor Context,
732 DICompileUnit CompileUnit,
735 uint64_t AlignInBits,
736 uint64_t OffsetInBits,
738 DIType DerivedFrom) {
742 MDString::get(VMContext, Name),
743 CompileUnit.getNode(),
744 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
745 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
746 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
747 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
748 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
749 DerivedFrom.getNode(),
751 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
755 /// CreateDerivedType - Create a derived type like const qualified type,
756 /// pointer, typedef, etc.
757 DIDerivedType DIFactory::CreateDerivedTypeEx(unsigned Tag,
758 DIDescriptor Context,
760 DICompileUnit CompileUnit,
762 Constant *SizeInBits,
763 Constant *AlignInBits,
764 Constant *OffsetInBits,
766 DIType DerivedFrom) {
770 MDString::get(VMContext, Name),
771 CompileUnit.getNode(),
772 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
776 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
777 DerivedFrom.getNode(),
779 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
783 /// CreateCompositeType - Create a composite type like array, struct, etc.
784 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
785 DIDescriptor Context,
787 DICompileUnit CompileUnit,
790 uint64_t AlignInBits,
791 uint64_t OffsetInBits,
795 unsigned RuntimeLang) {
800 MDString::get(VMContext, Name),
801 CompileUnit.getNode(),
802 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
803 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
804 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
805 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
806 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
807 DerivedFrom.getNode(),
809 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
811 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
815 /// CreateCompositeType - Create a composite type like array, struct, etc.
816 DICompositeType DIFactory::CreateCompositeTypeEx(unsigned Tag,
817 DIDescriptor Context,
819 DICompileUnit CompileUnit,
821 Constant *SizeInBits,
822 Constant *AlignInBits,
823 Constant *OffsetInBits,
827 unsigned RuntimeLang) {
832 MDString::get(VMContext, Name),
833 CompileUnit.getNode(),
834 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
838 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
839 DerivedFrom.getNode(),
841 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
843 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
847 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
848 /// See comments in DISubprogram for descriptions of these fields. This
849 /// method does not unique the generated descriptors.
850 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
852 StringRef DisplayName,
853 StringRef LinkageName,
854 DICompileUnit CompileUnit,
855 unsigned LineNo, DIType Type,
860 GetTagConstant(dwarf::DW_TAG_subprogram),
861 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
863 MDString::get(VMContext, Name),
864 MDString::get(VMContext, DisplayName),
865 MDString::get(VMContext, LinkageName),
866 CompileUnit.getNode(),
867 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
869 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
870 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition)
872 return DISubprogram(MDNode::get(VMContext, &Elts[0], 11));
875 /// CreateGlobalVariable - Create a new descriptor for the specified global.
877 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
878 StringRef DisplayName,
879 StringRef LinkageName,
880 DICompileUnit CompileUnit,
881 unsigned LineNo, DIType Type,bool isLocalToUnit,
882 bool isDefinition, llvm::GlobalVariable *Val) {
884 GetTagConstant(dwarf::DW_TAG_variable),
885 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
887 MDString::get(VMContext, Name),
888 MDString::get(VMContext, DisplayName),
889 MDString::get(VMContext, LinkageName),
890 CompileUnit.getNode(),
891 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
893 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
894 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
898 Value *const *Vs = &Elts[0];
899 MDNode *Node = MDNode::get(VMContext,Vs, 12);
901 // Create a named metadata so that we do not lose this mdnode.
902 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
903 NMD->addElement(Node);
905 return DIGlobalVariable(Node);
909 /// CreateVariable - Create a new descriptor for the specified variable.
910 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
912 DICompileUnit CompileUnit, unsigned LineNo,
917 MDString::get(VMContext, Name),
918 CompileUnit.getNode(),
919 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
922 return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
926 /// CreateComplexVariable - Create a new descriptor for the specified variable
927 /// which has a complex address expression for its address.
928 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
929 const std::string &Name,
930 DICompileUnit CompileUnit,
932 DIType Type, SmallVector<Value *, 9> &addr) {
933 SmallVector<Value *, 9> Elts;
934 Elts.push_back(GetTagConstant(Tag));
935 Elts.push_back(Context.getNode());
936 Elts.push_back(MDString::get(VMContext, Name));
937 Elts.push_back(CompileUnit.getNode());
938 Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
939 Elts.push_back(Type.getNode());
940 Elts.insert(Elts.end(), addr.begin(), addr.end());
942 return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
946 /// CreateBlock - This creates a descriptor for a lexical block with the
947 /// specified parent VMContext.
948 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context) {
950 GetTagConstant(dwarf::DW_TAG_lexical_block),
953 return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 2));
956 /// CreateLocation - Creates a debug info location.
957 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
958 DIScope S, DILocation OrigLoc) {
960 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
961 ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
965 return DILocation(MDNode::get(VMContext, &Elts[0], 4));
969 //===----------------------------------------------------------------------===//
970 // DIFactory: Routines for inserting code into a function
971 //===----------------------------------------------------------------------===//
973 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
974 /// inserting it at the end of the specified basic block.
975 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
976 unsigned ColNo, BasicBlock *BB) {
978 // Lazily construct llvm.dbg.stoppoint function.
980 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
981 llvm::Intrinsic::dbg_stoppoint);
983 // Invoke llvm.dbg.stoppoint
985 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo),
986 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), ColNo),
989 CallInst::Create(StopPointFn, Args, Args+3, "", BB);
992 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
993 /// mark the start of the specified subprogram.
994 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
995 // Lazily construct llvm.dbg.func.start.
997 FuncStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_func_start);
999 // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
1000 CallInst::Create(FuncStartFn, SP.getNode(), "", BB);
1003 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
1004 /// mark the start of a region for the specified scoping descriptor.
1005 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
1006 // Lazily construct llvm.dbg.region.start function.
1008 RegionStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_start);
1010 // Call llvm.dbg.func.start.
1011 CallInst::Create(RegionStartFn, D.getNode(), "", BB);
1014 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
1015 /// mark the end of a region for the specified scoping descriptor.
1016 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
1017 // Lazily construct llvm.dbg.region.end function.
1019 RegionEndFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_end);
1021 // Call llvm.dbg.region.end.
1022 CallInst::Create(RegionEndFn, D.getNode(), "", BB);
1025 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1026 void DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1027 Instruction *InsertBefore) {
1028 // Cast the storage to a {}* for the call to llvm.dbg.declare.
1029 Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertBefore);
1032 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1034 Value *Args[] = { Storage, D.getNode() };
1035 CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1038 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1039 void DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1040 BasicBlock *InsertAtEnd) {
1041 // Cast the storage to a {}* for the call to llvm.dbg.declare.
1042 Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertAtEnd);
1045 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1047 Value *Args[] = { Storage, D.getNode() };
1048 CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);
1052 //===----------------------------------------------------------------------===//
1053 // DebugInfoFinder implementations.
1054 //===----------------------------------------------------------------------===//
1056 /// processModule - Process entire module and collect debug info.
1057 void DebugInfoFinder::processModule(Module &M) {
1059 #ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
1060 MetadataContext &TheMetadata = M.getContext().getMetadata();
1061 unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
1063 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1064 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1065 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1067 if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(BI))
1068 processStopPoint(SPI);
1069 else if (DbgFuncStartInst *FSI = dyn_cast<DbgFuncStartInst>(BI))
1070 processFuncStart(FSI);
1071 else if (DbgRegionStartInst *DRS = dyn_cast<DbgRegionStartInst>(BI))
1072 processRegionStart(DRS);
1073 else if (DbgRegionEndInst *DRE = dyn_cast<DbgRegionEndInst>(BI))
1074 processRegionEnd(DRE);
1075 else if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1076 processDeclare(DDI);
1077 #ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
1078 else if (MDDbgKind) {
1079 if (MDNode *L = TheMetadata.getMD(MDDbgKind, BI)) {
1081 DIScope S(Loc.getScope().getNode());
1082 if (S.isCompileUnit())
1083 addCompileUnit(DICompileUnit(S.getNode()));
1084 else if (S.isSubprogram())
1085 processSubprogram(DISubprogram(S.getNode()));
1086 else if (S.isLexicalBlock())
1087 processLexicalBlock(DILexicalBlock(S.getNode()));
1093 NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
1097 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1098 DIGlobalVariable DIG(cast<MDNode>(NMD->getElement(i)));
1099 if (addGlobalVariable(DIG)) {
1100 addCompileUnit(DIG.getCompileUnit());
1101 processType(DIG.getType());
1106 /// processType - Process DIType.
1107 void DebugInfoFinder::processType(DIType DT) {
1111 addCompileUnit(DT.getCompileUnit());
1112 if (DT.isCompositeType()) {
1113 DICompositeType DCT(DT.getNode());
1114 processType(DCT.getTypeDerivedFrom());
1115 DIArray DA = DCT.getTypeArray();
1117 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1118 DIDescriptor D = DA.getElement(i);
1119 DIType TypeE = DIType(D.getNode());
1120 if (!TypeE.isNull())
1123 processSubprogram(DISubprogram(D.getNode()));
1125 } else if (DT.isDerivedType()) {
1126 DIDerivedType DDT(DT.getNode());
1128 processType(DDT.getTypeDerivedFrom());
1132 /// processLexicalBlock
1133 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1136 DIScope Context = LB.getContext();
1137 if (Context.isLexicalBlock())
1138 return processLexicalBlock(DILexicalBlock(Context.getNode()));
1140 return processSubprogram(DISubprogram(Context.getNode()));
1143 /// processSubprogram - Process DISubprogram.
1144 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1147 if (!addSubprogram(SP))
1149 addCompileUnit(SP.getCompileUnit());
1150 processType(SP.getType());
1153 /// processStopPoint - Process DbgStopPointInst.
1154 void DebugInfoFinder::processStopPoint(DbgStopPointInst *SPI) {
1155 MDNode *Context = dyn_cast<MDNode>(SPI->getContext());
1156 addCompileUnit(DICompileUnit(Context));
1159 /// processFuncStart - Process DbgFuncStartInst.
1160 void DebugInfoFinder::processFuncStart(DbgFuncStartInst *FSI) {
1161 MDNode *SP = dyn_cast<MDNode>(FSI->getSubprogram());
1162 processSubprogram(DISubprogram(SP));
1165 /// processRegionStart - Process DbgRegionStart.
1166 void DebugInfoFinder::processRegionStart(DbgRegionStartInst *DRS) {
1167 MDNode *SP = dyn_cast<MDNode>(DRS->getContext());
1168 processSubprogram(DISubprogram(SP));
1171 /// processRegionEnd - Process DbgRegionEnd.
1172 void DebugInfoFinder::processRegionEnd(DbgRegionEndInst *DRE) {
1173 MDNode *SP = dyn_cast<MDNode>(DRE->getContext());
1174 processSubprogram(DISubprogram(SP));
1177 /// processDeclare - Process DbgDeclareInst.
1178 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1179 DIVariable DV(cast<MDNode>(DDI->getVariable()));
1183 if (!NodesSeen.insert(DV.getNode()))
1186 addCompileUnit(DV.getCompileUnit());
1187 processType(DV.getType());
1190 /// addType - Add type into Tys.
1191 bool DebugInfoFinder::addType(DIType DT) {
1195 if (!NodesSeen.insert(DT.getNode()))
1198 TYs.push_back(DT.getNode());
1202 /// addCompileUnit - Add compile unit into CUs.
1203 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1207 if (!NodesSeen.insert(CU.getNode()))
1210 CUs.push_back(CU.getNode());
1214 /// addGlobalVariable - Add global variable into GVs.
1215 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1219 if (!NodesSeen.insert(DIG.getNode()))
1222 GVs.push_back(DIG.getNode());
1226 // addSubprogram - Add subprgoram into SPs.
1227 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1231 if (!NodesSeen.insert(SP.getNode()))
1234 SPs.push_back(SP.getNode());
1239 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
1240 /// is the stoppoint that dominates this instruction.
1241 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
1242 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
1245 const BasicBlock *BB = Inst->getParent();
1246 BasicBlock::const_iterator I = Inst, B;
1250 // A BB consisting only of a terminator can't have a stoppoint.
1253 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1257 // This BB didn't have a stoppoint: if there is only one predecessor, look
1258 // for a stoppoint there. We could use getIDom(), but that would require
1260 BB = I->getParent()->getUniquePredecessor();
1262 I = BB->getTerminator();
1268 /// findBBStopPoint - Find the stoppoint corresponding to first real
1269 /// (non-debug intrinsic) instruction in this Basic Block, and return the
1270 /// stoppoint for it.
1271 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
1272 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1273 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1276 // Fallback to looking for stoppoint of unique predecessor. Useful if this
1277 // BB contains no stoppoints, but unique predecessor does.
1278 BB = BB->getUniquePredecessor();
1280 return findStopPoint(BB->getTerminator());
1285 Value *findDbgGlobalDeclare(GlobalVariable *V) {
1286 const Module *M = V->getParent();
1287 NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1291 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1292 DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getElement(i)));
1295 if (DIG.getGlobal() == V)
1296 return DIG.getNode();
1301 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1302 /// It looks through pointer casts too.
1303 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1305 V = V->stripPointerCasts();
1307 // Look for the bitcast.
1308 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1310 if (isa<BitCastInst>(I)) {
1311 const DbgDeclareInst *DDI = findDbgDeclare(*I, false);
1312 if (DDI) return DDI;
1317 // Find llvm.dbg.declare among uses of the instruction.
1318 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1320 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1326 bool getLocationInfo(const Value *V, std::string &DisplayName,
1327 std::string &Type, unsigned &LineNo, std::string &File,
1332 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1333 Value *DIGV = findDbgGlobalDeclare(GV);
1334 if (!DIGV) return false;
1335 DIGlobalVariable Var(cast<MDNode>(DIGV));
1337 if (const char *D = Var.getDisplayName())
1339 LineNo = Var.getLineNumber();
1340 Unit = Var.getCompileUnit();
1341 TypeD = Var.getType();
1343 const DbgDeclareInst *DDI = findDbgDeclare(V);
1344 if (!DDI) return false;
1345 DIVariable Var(cast<MDNode>(DDI->getVariable()));
1347 if (const char *D = Var.getName())
1349 LineNo = Var.getLineNumber();
1350 Unit = Var.getCompileUnit();
1351 TypeD = Var.getType();
1354 if (const char *T = TypeD.getName())
1356 if (const char *F = Unit.getFilename())
1358 if (const char *D = Unit.getDirectory())
1363 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1365 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1366 CodeGenOpt::Level OptLev) {
1367 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1370 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1372 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1373 CodeGenOpt::Level OptLev) {
1374 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1377 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1379 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1380 CodeGenOpt::Level OptLev) {
1381 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1384 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1386 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1387 CodeGenOpt::Level OptLev) {
1388 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1392 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1394 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1395 CodeGenOpt::Level OptLev) {
1396 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1399 /// ExtractDebugLocation - Extract debug location information
1400 /// from llvm.dbg.stoppoint intrinsic.
1401 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1402 DebugLocTracker &DebugLocInfo) {
1404 Value *Context = SPI.getContext();
1406 // If this location is already tracked then use it.
1407 DebugLocTuple Tuple(cast<MDNode>(Context), NULL, SPI.getLine(),
1409 DenseMap<DebugLocTuple, unsigned>::iterator II
1410 = DebugLocInfo.DebugIdMap.find(Tuple);
1411 if (II != DebugLocInfo.DebugIdMap.end())
1412 return DebugLoc::get(II->second);
1414 // Add a new location entry.
1415 unsigned Id = DebugLocInfo.DebugLocations.size();
1416 DebugLocInfo.DebugLocations.push_back(Tuple);
1417 DebugLocInfo.DebugIdMap[Tuple] = Id;
1419 return DebugLoc::get(Id);
1422 /// ExtractDebugLocation - Extract debug location information
1423 /// from DILocation.
1424 DebugLoc ExtractDebugLocation(DILocation &Loc,
1425 DebugLocTracker &DebugLocInfo) {
1427 MDNode *Context = Loc.getScope().getNode();
1428 MDNode *InlinedLoc = NULL;
1429 if (!Loc.getOrigLocation().isNull())
1430 InlinedLoc = Loc.getOrigLocation().getNode();
1431 // If this location is already tracked then use it.
1432 DebugLocTuple Tuple(Context, InlinedLoc, Loc.getLineNumber(),
1433 Loc.getColumnNumber());
1434 DenseMap<DebugLocTuple, unsigned>::iterator II
1435 = DebugLocInfo.DebugIdMap.find(Tuple);
1436 if (II != DebugLocInfo.DebugIdMap.end())
1437 return DebugLoc::get(II->second);
1439 // Add a new location entry.
1440 unsigned Id = DebugLocInfo.DebugLocations.size();
1441 DebugLocInfo.DebugLocations.push_back(Tuple);
1442 DebugLocInfo.DebugIdMap[Tuple] = Id;
1444 return DebugLoc::get(Id);
1447 /// ExtractDebugLocation - Extract debug location information
1448 /// from llvm.dbg.func_start intrinsic.
1449 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1450 DebugLocTracker &DebugLocInfo) {
1452 Value *SP = FSI.getSubprogram();
1454 DISubprogram Subprogram(cast<MDNode>(SP));
1455 unsigned Line = Subprogram.getLineNumber();
1456 DICompileUnit CU(Subprogram.getCompileUnit());
1458 // If this location is already tracked then use it.
1459 DebugLocTuple Tuple(CU.getNode(), NULL, Line, /* Column */ 0);
1460 DenseMap<DebugLocTuple, unsigned>::iterator II
1461 = DebugLocInfo.DebugIdMap.find(Tuple);
1462 if (II != DebugLocInfo.DebugIdMap.end())
1463 return DebugLoc::get(II->second);
1465 // Add a new location entry.
1466 unsigned Id = DebugLocInfo.DebugLocations.size();
1467 DebugLocInfo.DebugLocations.push_back(Tuple);
1468 DebugLocInfo.DebugIdMap[Tuple] = Id;
1470 return DebugLoc::get(Id);
1473 /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1474 bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1475 DISubprogram Subprogram(cast<MDNode>(FSI.getSubprogram()));
1476 if (Subprogram.describes(CurrentFn))
1482 /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1483 bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1484 DISubprogram Subprogram(cast<MDNode>(REI.getContext()));
1485 if (Subprogram.isNull() || Subprogram.describes(CurrentFn))