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 return MDS->getString().data();
93 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
97 if (Elt < DbgNode->getNumElements())
98 if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getElement(Elt)))
99 return CI->getZExtValue();
104 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
106 return DIDescriptor();
108 if (Elt < DbgNode->getNumElements() && DbgNode->getElement(Elt))
109 return DIDescriptor(dyn_cast<MDNode>(DbgNode->getElement(Elt)));
111 return DIDescriptor();
114 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
118 if (Elt < DbgNode->getNumElements())
119 return dyn_cast<GlobalVariable>(DbgNode->getElement(Elt));
123 //===----------------------------------------------------------------------===//
125 //===----------------------------------------------------------------------===//
127 /// isBasicType - Return true if the specified tag is legal for
129 bool DIDescriptor::isBasicType() const {
130 assert (!isNull() && "Invalid descriptor!");
131 unsigned Tag = getTag();
133 return Tag == dwarf::DW_TAG_base_type;
136 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
137 bool DIDescriptor::isDerivedType() const {
138 assert (!isNull() && "Invalid descriptor!");
139 unsigned Tag = getTag();
142 case dwarf::DW_TAG_typedef:
143 case dwarf::DW_TAG_pointer_type:
144 case dwarf::DW_TAG_reference_type:
145 case dwarf::DW_TAG_const_type:
146 case dwarf::DW_TAG_volatile_type:
147 case dwarf::DW_TAG_restrict_type:
148 case dwarf::DW_TAG_member:
149 case dwarf::DW_TAG_inheritance:
152 // CompositeTypes are currently modelled as DerivedTypes.
153 return isCompositeType();
157 /// isCompositeType - Return true if the specified tag is legal for
159 bool DIDescriptor::isCompositeType() const {
160 assert (!isNull() && "Invalid descriptor!");
161 unsigned Tag = getTag();
164 case dwarf::DW_TAG_array_type:
165 case dwarf::DW_TAG_structure_type:
166 case dwarf::DW_TAG_union_type:
167 case dwarf::DW_TAG_enumeration_type:
168 case dwarf::DW_TAG_vector_type:
169 case dwarf::DW_TAG_subroutine_type:
170 case dwarf::DW_TAG_class_type:
177 /// isVariable - Return true if the specified tag is legal for DIVariable.
178 bool DIDescriptor::isVariable() const {
179 assert (!isNull() && "Invalid descriptor!");
180 unsigned Tag = getTag();
183 case dwarf::DW_TAG_auto_variable:
184 case dwarf::DW_TAG_arg_variable:
185 case dwarf::DW_TAG_return_variable:
192 /// isSubprogram - Return true if the specified tag is legal for
194 bool DIDescriptor::isSubprogram() const {
195 assert (!isNull() && "Invalid descriptor!");
196 unsigned Tag = getTag();
198 return Tag == dwarf::DW_TAG_subprogram;
201 /// isGlobalVariable - Return true if the specified tag is legal for
202 /// DIGlobalVariable.
203 bool DIDescriptor::isGlobalVariable() const {
204 assert (!isNull() && "Invalid descriptor!");
205 unsigned Tag = getTag();
207 return Tag == dwarf::DW_TAG_variable;
210 /// isScope - Return true if the specified tag is one of the scope
212 bool DIDescriptor::isScope() const {
213 assert (!isNull() && "Invalid descriptor!");
214 unsigned Tag = getTag();
217 case dwarf::DW_TAG_compile_unit:
218 case dwarf::DW_TAG_lexical_block:
219 case dwarf::DW_TAG_subprogram:
227 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
228 bool DIDescriptor::isCompileUnit() const {
229 assert (!isNull() && "Invalid descriptor!");
230 unsigned Tag = getTag();
232 return Tag == dwarf::DW_TAG_compile_unit;
235 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
236 bool DIDescriptor::isLexicalBlock() const {
237 assert (!isNull() && "Invalid descriptor!");
238 unsigned Tag = getTag();
240 return Tag == dwarf::DW_TAG_lexical_block;
243 //===----------------------------------------------------------------------===//
244 // Simple Descriptor Constructors and other Methods
245 //===----------------------------------------------------------------------===//
247 DIType::DIType(MDNode *N) : DIDescriptor(N) {
249 if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
254 unsigned DIArray::getNumElements() const {
255 assert (DbgNode && "Invalid DIArray");
256 return DbgNode->getNumElements();
259 /// replaceAllUsesWith - Replace all uses of debug info referenced by
260 /// this descriptor. After this completes, the current debug info value
262 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
266 assert (!D.isNull() && "Can not replace with null");
268 // Since we use a TrackingVH for the node, its easy for clients to manufacture
269 // legitimate situations where they want to replaceAllUsesWith() on something
270 // which, due to uniquing, has merged with the source. We shield clients from
271 // this detail by allowing a value to be replaced with replaceAllUsesWith()
273 if (getNode() != D.getNode()) {
274 MDNode *Node = DbgNode;
275 Node->replaceAllUsesWith(D.getNode());
280 /// Verify - Verify that a compile unit is well formed.
281 bool DICompileUnit::Verify() const {
284 const char *N = getFilename();
287 // It is possible that directory and produce string is empty.
291 /// Verify - Verify that a type descriptor is well formed.
292 bool DIType::Verify() const {
295 if (getContext().isNull())
298 DICompileUnit CU = getCompileUnit();
299 if (!CU.isNull() && !CU.Verify())
304 /// Verify - Verify that a composite type descriptor is well formed.
305 bool DICompositeType::Verify() const {
308 if (getContext().isNull())
311 DICompileUnit CU = getCompileUnit();
312 if (!CU.isNull() && !CU.Verify())
317 /// Verify - Verify that a subprogram descriptor is well formed.
318 bool DISubprogram::Verify() const {
322 if (getContext().isNull())
325 DICompileUnit CU = getCompileUnit();
329 DICompositeType Ty = getType();
330 if (!Ty.isNull() && !Ty.Verify())
335 /// Verify - Verify that a global variable descriptor is well formed.
336 bool DIGlobalVariable::Verify() const {
340 if (getContext().isNull())
343 DICompileUnit CU = getCompileUnit();
344 if (!CU.isNull() && !CU.Verify())
347 DIType Ty = getType();
357 /// Verify - Verify that a variable descriptor is well formed.
358 bool DIVariable::Verify() const {
362 if (getContext().isNull())
365 DIType Ty = getType();
372 /// getOriginalTypeSize - If this type is derived from a base type then
373 /// return base type size.
374 uint64_t DIDerivedType::getOriginalTypeSize() const {
375 if (getTag() != dwarf::DW_TAG_member)
376 return getSizeInBits();
377 DIType BT = getTypeDerivedFrom();
378 if (BT.getTag() != dwarf::DW_TAG_base_type)
379 return getSizeInBits();
380 return BT.getSizeInBits();
383 /// describes - Return true if this subprogram provides debugging
384 /// information for the function F.
385 bool DISubprogram::describes(const Function *F) {
386 assert (F && "Invalid function");
387 const char *Name = getLinkageName();
390 if (strcmp(F->getName().data(), Name) == 0)
395 //===----------------------------------------------------------------------===//
396 // DIDescriptor: dump routines for all descriptors.
397 //===----------------------------------------------------------------------===//
400 /// dump - Print descriptor.
401 void DIDescriptor::dump() const {
402 errs() << "[" << dwarf::TagString(getTag()) << "] ";
403 errs().write_hex((intptr_t) &*DbgNode) << ']';
406 /// dump - Print compile unit.
407 void DICompileUnit::dump() const {
409 errs() << " [" << dwarf::LanguageString(getLanguage()) << "] ";
411 errs() << " [" << getDirectory() << "/" << getFilename() << " ]";
414 /// dump - Print type.
415 void DIType::dump() const {
416 if (isNull()) return;
418 if (const char *Res = getName())
419 errs() << " [" << Res << "] ";
421 unsigned Tag = getTag();
422 errs() << " [" << dwarf::TagString(Tag) << "] ";
424 // TODO : Print context
425 getCompileUnit().dump();
427 << getLineNumber() << ", "
428 << getSizeInBits() << ", "
429 << getAlignInBits() << ", "
434 errs() << " [private] ";
435 else if (isProtected())
436 errs() << " [protected] ";
442 DIBasicType(DbgNode).dump();
443 else if (isDerivedType())
444 DIDerivedType(DbgNode).dump();
445 else if (isCompositeType())
446 DICompositeType(DbgNode).dump();
448 errs() << "Invalid DIType\n";
455 /// dump - Print basic type.
456 void DIBasicType::dump() const {
457 errs() << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
460 /// dump - Print derived type.
461 void DIDerivedType::dump() const {
462 errs() << "\n\t Derived From: "; getTypeDerivedFrom().dump();
465 /// dump - Print composite type.
466 void DICompositeType::dump() const {
467 DIArray A = getTypeArray();
470 errs() << " [" << A.getNumElements() << " elements]";
473 /// dump - Print global.
474 void DIGlobal::dump() const {
475 if (const char *Res = getName())
476 errs() << " [" << Res << "] ";
478 unsigned Tag = getTag();
479 errs() << " [" << dwarf::TagString(Tag) << "] ";
481 // TODO : Print context
482 getCompileUnit().dump();
483 errs() << " [" << getLineNumber() << "] ";
486 errs() << " [local] ";
491 if (isGlobalVariable())
492 DIGlobalVariable(DbgNode).dump();
497 /// dump - Print subprogram.
498 void DISubprogram::dump() const {
499 if (const char *Res = getName())
500 errs() << " [" << Res << "] ";
502 unsigned Tag = getTag();
503 errs() << " [" << dwarf::TagString(Tag) << "] ";
505 // TODO : Print context
506 getCompileUnit().dump();
507 errs() << " [" << getLineNumber() << "] ";
510 errs() << " [local] ";
518 /// dump - Print global variable.
519 void DIGlobalVariable::dump() const {
525 /// dump - Print variable.
526 void DIVariable::dump() const {
527 if (const char *Res = getName())
528 errs() << " [" << Res << "] ";
530 getCompileUnit().dump();
531 errs() << " [" << getLineNumber() << "] ";
535 // FIXME: Dump complex addresses
538 //===----------------------------------------------------------------------===//
539 // DIFactory: Basic Helpers
540 //===----------------------------------------------------------------------===//
542 DIFactory::DIFactory(Module &m)
543 : M(m), VMContext(M.getContext()), StopPointFn(0), FuncStartFn(0),
544 RegionStartFn(0), RegionEndFn(0),
546 EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
549 Constant *DIFactory::GetTagConstant(unsigned TAG) {
550 assert((TAG & LLVMDebugVersionMask) == 0 &&
551 "Tag too large for debug encoding!");
552 return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
555 //===----------------------------------------------------------------------===//
556 // DIFactory: Primary Constructors
557 //===----------------------------------------------------------------------===//
559 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
560 /// This implicitly uniques the arrays created.
561 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
562 SmallVector<Value*, 16> Elts;
565 Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
567 for (unsigned i = 0; i != NumTys; ++i)
568 Elts.push_back(Tys[i].getNode());
570 return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
573 /// GetOrCreateSubrange - Create a descriptor for a value range. This
574 /// implicitly uniques the values returned.
575 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
577 GetTagConstant(dwarf::DW_TAG_subrange_type),
578 ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
579 ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
582 return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
587 /// CreateCompileUnit - Create a new descriptor for the specified compile
588 /// unit. Note that this does not unique compile units within the module.
589 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
596 unsigned RunTimeVer) {
598 GetTagConstant(dwarf::DW_TAG_compile_unit),
599 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
600 ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
601 MDString::get(VMContext, Filename),
602 MDString::get(VMContext, Directory),
603 MDString::get(VMContext, Producer),
604 ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
605 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
606 MDString::get(VMContext, Flags),
607 ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
610 return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
613 /// CreateEnumerator - Create a single enumerator value.
614 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
616 GetTagConstant(dwarf::DW_TAG_enumerator),
617 MDString::get(VMContext, Name),
618 ConstantInt::get(Type::getInt64Ty(VMContext), Val)
620 return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
624 /// CreateBasicType - Create a basic type like int, float, etc.
625 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
627 DICompileUnit CompileUnit,
630 uint64_t AlignInBits,
631 uint64_t OffsetInBits, unsigned Flags,
634 GetTagConstant(dwarf::DW_TAG_base_type),
636 MDString::get(VMContext, Name),
637 CompileUnit.getNode(),
638 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
639 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
640 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
641 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
642 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
643 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
645 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
648 /// CreateDerivedType - Create a derived type like const qualified type,
649 /// pointer, typedef, etc.
650 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
651 DIDescriptor Context,
653 DICompileUnit CompileUnit,
656 uint64_t AlignInBits,
657 uint64_t OffsetInBits,
659 DIType DerivedFrom) {
663 MDString::get(VMContext, Name),
664 CompileUnit.getNode(),
665 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
666 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
667 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
668 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
669 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
670 DerivedFrom.getNode(),
672 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
675 /// CreateCompositeType - Create a composite type like array, struct, etc.
676 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
677 DIDescriptor Context,
679 DICompileUnit CompileUnit,
682 uint64_t AlignInBits,
683 uint64_t OffsetInBits,
687 unsigned RuntimeLang) {
692 MDString::get(VMContext, Name),
693 CompileUnit.getNode(),
694 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
695 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
696 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
697 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
698 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
699 DerivedFrom.getNode(),
701 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
703 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
707 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
708 /// See comments in DISubprogram for descriptions of these fields. This
709 /// method does not unique the generated descriptors.
710 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
712 StringRef DisplayName,
713 StringRef LinkageName,
714 DICompileUnit CompileUnit,
715 unsigned LineNo, DIType Type,
720 GetTagConstant(dwarf::DW_TAG_subprogram),
721 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
723 MDString::get(VMContext, Name),
724 MDString::get(VMContext, DisplayName),
725 MDString::get(VMContext, LinkageName),
726 CompileUnit.getNode(),
727 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
729 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
730 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition)
732 return DISubprogram(MDNode::get(VMContext, &Elts[0], 11));
735 /// CreateGlobalVariable - Create a new descriptor for the specified global.
737 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
738 StringRef DisplayName,
739 StringRef LinkageName,
740 DICompileUnit CompileUnit,
741 unsigned LineNo, DIType Type,bool isLocalToUnit,
742 bool isDefinition, llvm::GlobalVariable *Val) {
744 GetTagConstant(dwarf::DW_TAG_variable),
745 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
747 MDString::get(VMContext, Name),
748 MDString::get(VMContext, DisplayName),
749 MDString::get(VMContext, LinkageName),
750 CompileUnit.getNode(),
751 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
753 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
754 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
758 Value *const *Vs = &Elts[0];
759 MDNode *Node = MDNode::get(VMContext,Vs, 12);
761 // Create a named metadata so that we do not lose this mdnode.
762 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
763 NMD->addElement(Node);
765 return DIGlobalVariable(Node);
769 /// CreateVariable - Create a new descriptor for the specified variable.
770 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
772 DICompileUnit CompileUnit, unsigned LineNo,
777 MDString::get(VMContext, Name),
778 CompileUnit.getNode(),
779 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
782 return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
786 /// CreateComplexVariable - Create a new descriptor for the specified variable
787 /// which has a complex address expression for its address.
788 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
789 const std::string &Name,
790 DICompileUnit CompileUnit,
792 DIType Type, SmallVector<Value *, 9> &addr) {
793 SmallVector<Value *, 9> Elts;
794 Elts.push_back(GetTagConstant(Tag));
795 Elts.push_back(Context.getNode());
796 Elts.push_back(MDString::get(VMContext, Name));
797 Elts.push_back(CompileUnit.getNode());
798 Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
799 Elts.push_back(Type.getNode());
800 Elts.insert(Elts.end(), addr.begin(), addr.end());
802 return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
806 /// CreateBlock - This creates a descriptor for a lexical block with the
807 /// specified parent VMContext.
808 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context) {
810 GetTagConstant(dwarf::DW_TAG_lexical_block),
813 return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 2));
816 /// CreateLocation - Creates a debug info location.
817 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
818 DIScope S, DILocation OrigLoc) {
820 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
821 ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
825 return DILocation(MDNode::get(VMContext, &Elts[0], 4));
829 //===----------------------------------------------------------------------===//
830 // DIFactory: Routines for inserting code into a function
831 //===----------------------------------------------------------------------===//
833 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
834 /// inserting it at the end of the specified basic block.
835 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
836 unsigned ColNo, BasicBlock *BB) {
838 // Lazily construct llvm.dbg.stoppoint function.
840 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
841 llvm::Intrinsic::dbg_stoppoint);
843 // Invoke llvm.dbg.stoppoint
845 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo),
846 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), ColNo),
849 CallInst::Create(StopPointFn, Args, Args+3, "", BB);
852 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
853 /// mark the start of the specified subprogram.
854 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
855 // Lazily construct llvm.dbg.func.start.
857 FuncStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_func_start);
859 // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
860 CallInst::Create(FuncStartFn, SP.getNode(), "", BB);
863 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
864 /// mark the start of a region for the specified scoping descriptor.
865 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
866 // Lazily construct llvm.dbg.region.start function.
868 RegionStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_start);
870 // Call llvm.dbg.func.start.
871 CallInst::Create(RegionStartFn, D.getNode(), "", BB);
874 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
875 /// mark the end of a region for the specified scoping descriptor.
876 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
877 // Lazily construct llvm.dbg.region.end function.
879 RegionEndFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_end);
881 // Call llvm.dbg.region.end.
882 CallInst::Create(RegionEndFn, D.getNode(), "", BB);
885 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
886 void DIFactory::InsertDeclare(Value *Storage, DIVariable D, BasicBlock *BB) {
887 // Cast the storage to a {}* for the call to llvm.dbg.declare.
888 Storage = new BitCastInst(Storage, EmptyStructPtr, "", BB);
891 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
893 Value *Args[] = { Storage, D.getNode() };
894 CallInst::Create(DeclareFn, Args, Args+2, "", BB);
898 //===----------------------------------------------------------------------===//
899 // DebugInfoFinder implementations.
900 //===----------------------------------------------------------------------===//
902 /// processModule - Process entire module and collect debug info.
903 void DebugInfoFinder::processModule(Module &M) {
906 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
907 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
908 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
910 if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(BI))
911 processStopPoint(SPI);
912 else if (DbgFuncStartInst *FSI = dyn_cast<DbgFuncStartInst>(BI))
913 processFuncStart(FSI);
914 else if (DbgRegionStartInst *DRS = dyn_cast<DbgRegionStartInst>(BI))
915 processRegionStart(DRS);
916 else if (DbgRegionEndInst *DRE = dyn_cast<DbgRegionEndInst>(BI))
917 processRegionEnd(DRE);
918 else if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
922 NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
926 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
927 DIGlobalVariable DIG(cast<MDNode>(NMD->getElement(i)));
928 if (addGlobalVariable(DIG)) {
929 addCompileUnit(DIG.getCompileUnit());
930 processType(DIG.getType());
935 /// processType - Process DIType.
936 void DebugInfoFinder::processType(DIType DT) {
940 addCompileUnit(DT.getCompileUnit());
941 if (DT.isCompositeType()) {
942 DICompositeType DCT(DT.getNode());
943 processType(DCT.getTypeDerivedFrom());
944 DIArray DA = DCT.getTypeArray();
946 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
947 DIDescriptor D = DA.getElement(i);
948 DIType TypeE = DIType(D.getNode());
952 processSubprogram(DISubprogram(D.getNode()));
954 } else if (DT.isDerivedType()) {
955 DIDerivedType DDT(DT.getNode());
957 processType(DDT.getTypeDerivedFrom());
961 /// processSubprogram - Process DISubprogram.
962 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
965 if (!addSubprogram(SP))
967 addCompileUnit(SP.getCompileUnit());
968 processType(SP.getType());
971 /// processStopPoint - Process DbgStopPointInst.
972 void DebugInfoFinder::processStopPoint(DbgStopPointInst *SPI) {
973 MDNode *Context = dyn_cast<MDNode>(SPI->getContext());
974 addCompileUnit(DICompileUnit(Context));
977 /// processFuncStart - Process DbgFuncStartInst.
978 void DebugInfoFinder::processFuncStart(DbgFuncStartInst *FSI) {
979 MDNode *SP = dyn_cast<MDNode>(FSI->getSubprogram());
980 processSubprogram(DISubprogram(SP));
983 /// processRegionStart - Process DbgRegionStart.
984 void DebugInfoFinder::processRegionStart(DbgRegionStartInst *DRS) {
985 MDNode *SP = dyn_cast<MDNode>(DRS->getContext());
986 processSubprogram(DISubprogram(SP));
989 /// processRegionEnd - Process DbgRegionEnd.
990 void DebugInfoFinder::processRegionEnd(DbgRegionEndInst *DRE) {
991 MDNode *SP = dyn_cast<MDNode>(DRE->getContext());
992 processSubprogram(DISubprogram(SP));
995 /// processDeclare - Process DbgDeclareInst.
996 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
997 DIVariable DV(cast<MDNode>(DDI->getVariable()));
1001 if (!NodesSeen.insert(DV.getNode()))
1004 addCompileUnit(DV.getCompileUnit());
1005 processType(DV.getType());
1008 /// addType - Add type into Tys.
1009 bool DebugInfoFinder::addType(DIType DT) {
1013 if (!NodesSeen.insert(DT.getNode()))
1016 TYs.push_back(DT.getNode());
1020 /// addCompileUnit - Add compile unit into CUs.
1021 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1025 if (!NodesSeen.insert(CU.getNode()))
1028 CUs.push_back(CU.getNode());
1032 /// addGlobalVariable - Add global variable into GVs.
1033 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1037 if (!NodesSeen.insert(DIG.getNode()))
1040 GVs.push_back(DIG.getNode());
1044 // addSubprogram - Add subprgoram into SPs.
1045 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1049 if (!NodesSeen.insert(SP.getNode()))
1052 SPs.push_back(SP.getNode());
1057 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
1058 /// is the stoppoint that dominates this instruction.
1059 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
1060 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
1063 const BasicBlock *BB = Inst->getParent();
1064 BasicBlock::const_iterator I = Inst, B;
1068 // A BB consisting only of a terminator can't have a stoppoint.
1071 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1075 // This BB didn't have a stoppoint: if there is only one predecessor, look
1076 // for a stoppoint there. We could use getIDom(), but that would require
1078 BB = I->getParent()->getUniquePredecessor();
1080 I = BB->getTerminator();
1086 /// findBBStopPoint - Find the stoppoint corresponding to first real
1087 /// (non-debug intrinsic) instruction in this Basic Block, and return the
1088 /// stoppoint for it.
1089 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
1090 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1091 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1094 // Fallback to looking for stoppoint of unique predecessor. Useful if this
1095 // BB contains no stoppoints, but unique predecessor does.
1096 BB = BB->getUniquePredecessor();
1098 return findStopPoint(BB->getTerminator());
1103 Value *findDbgGlobalDeclare(GlobalVariable *V) {
1104 const Module *M = V->getParent();
1105 NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1109 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1110 DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getElement(i)));
1113 if (DIG.getGlobal() == V)
1114 return DIG.getNode();
1119 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1120 /// It looks through pointer casts too.
1121 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1123 V = V->stripPointerCasts();
1125 // Look for the bitcast.
1126 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1128 if (isa<BitCastInst>(I))
1129 return findDbgDeclare(*I, false);
1134 // Find llvm.dbg.declare among uses of the instruction.
1135 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1137 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1143 bool getLocationInfo(const Value *V, std::string &DisplayName,
1144 std::string &Type, unsigned &LineNo, std::string &File,
1149 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1150 Value *DIGV = findDbgGlobalDeclare(GV);
1151 if (!DIGV) return false;
1152 DIGlobalVariable Var(cast<MDNode>(DIGV));
1154 if (const char *D = Var.getDisplayName())
1156 LineNo = Var.getLineNumber();
1157 Unit = Var.getCompileUnit();
1158 TypeD = Var.getType();
1160 const DbgDeclareInst *DDI = findDbgDeclare(V);
1161 if (!DDI) return false;
1162 DIVariable Var(cast<MDNode>(DDI->getVariable()));
1164 if (const char *D = Var.getName())
1166 LineNo = Var.getLineNumber();
1167 Unit = Var.getCompileUnit();
1168 TypeD = Var.getType();
1171 if (const char *T = TypeD.getName())
1173 if (const char *F = Unit.getFilename())
1175 if (const char *D = Unit.getDirectory())
1180 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1182 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1183 CodeGenOpt::Level OptLev) {
1184 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1187 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1189 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1190 CodeGenOpt::Level OptLev) {
1191 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1194 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1196 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1197 CodeGenOpt::Level OptLev) {
1198 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1201 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1203 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1204 CodeGenOpt::Level OptLev) {
1205 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1209 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1211 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1212 CodeGenOpt::Level OptLev) {
1213 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1216 /// ExtractDebugLocation - Extract debug location information
1217 /// from llvm.dbg.stoppoint intrinsic.
1218 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1219 DebugLocTracker &DebugLocInfo) {
1221 Value *Context = SPI.getContext();
1223 // If this location is already tracked then use it.
1224 DebugLocTuple Tuple(cast<MDNode>(Context), SPI.getLine(),
1226 DenseMap<DebugLocTuple, unsigned>::iterator II
1227 = DebugLocInfo.DebugIdMap.find(Tuple);
1228 if (II != DebugLocInfo.DebugIdMap.end())
1229 return DebugLoc::get(II->second);
1231 // Add a new location entry.
1232 unsigned Id = DebugLocInfo.DebugLocations.size();
1233 DebugLocInfo.DebugLocations.push_back(Tuple);
1234 DebugLocInfo.DebugIdMap[Tuple] = Id;
1236 return DebugLoc::get(Id);
1239 /// ExtractDebugLocation - Extract debug location information
1240 /// from DILocation.
1241 DebugLoc ExtractDebugLocation(DILocation &Loc,
1242 DebugLocTracker &DebugLocInfo) {
1244 MDNode *Context = Loc.getScope().getNode();
1246 // If this location is already tracked then use it.
1247 DebugLocTuple Tuple(Context, Loc.getLineNumber(),
1248 Loc.getColumnNumber());
1249 DenseMap<DebugLocTuple, unsigned>::iterator II
1250 = DebugLocInfo.DebugIdMap.find(Tuple);
1251 if (II != DebugLocInfo.DebugIdMap.end())
1252 return DebugLoc::get(II->second);
1254 // Add a new location entry.
1255 unsigned Id = DebugLocInfo.DebugLocations.size();
1256 DebugLocInfo.DebugLocations.push_back(Tuple);
1257 DebugLocInfo.DebugIdMap[Tuple] = Id;
1259 return DebugLoc::get(Id);
1262 /// ExtractDebugLocation - Extract debug location information
1263 /// from llvm.dbg.func_start intrinsic.
1264 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1265 DebugLocTracker &DebugLocInfo) {
1267 Value *SP = FSI.getSubprogram();
1269 DISubprogram Subprogram(cast<MDNode>(SP));
1270 unsigned Line = Subprogram.getLineNumber();
1271 DICompileUnit CU(Subprogram.getCompileUnit());
1273 // If this location is already tracked then use it.
1274 DebugLocTuple Tuple(CU.getNode(), Line, /* Column */ 0);
1275 DenseMap<DebugLocTuple, unsigned>::iterator II
1276 = DebugLocInfo.DebugIdMap.find(Tuple);
1277 if (II != DebugLocInfo.DebugIdMap.end())
1278 return DebugLoc::get(II->second);
1280 // Add a new location entry.
1281 unsigned Id = DebugLocInfo.DebugLocations.size();
1282 DebugLocInfo.DebugLocations.push_back(Tuple);
1283 DebugLocInfo.DebugIdMap[Tuple] = Id;
1285 return DebugLoc::get(Id);
1288 /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1289 bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1290 DISubprogram Subprogram(cast<MDNode>(FSI.getSubprogram()));
1291 if (Subprogram.describes(CurrentFn))
1297 /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1298 bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1299 DISubprogram Subprogram(cast<MDNode>(REI.getContext()));
1300 if (Subprogram.isNull() || Subprogram.describes(CurrentFn))