1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
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 contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "DwarfDebug.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCSection.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/Target/Mangler.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetFrameInfo.h"
28 #include "llvm/Target/TargetLoweringObjectFile.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Analysis/DebugInfo.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/StringExtras.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/ValueHandle.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/Timer.h"
42 #include "llvm/System/Path.h"
45 static cl::opt<bool> PrintDbgScope("print-dbgscope", cl::Hidden,
46 cl::desc("Print DbgScope information for each machine instruction"));
48 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
50 cl::desc("Disable debug info printing"));
52 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
53 cl::desc("Make an absense of debug location information explicit."),
57 STATISTIC(BlocksWithoutLineNo, "Number of blocks without any line number");
61 const char *DWARFGroupName = "DWARF Emission";
62 const char *DbgTimerName = "DWARF Debug Writer";
63 } // end anonymous namespace
65 //===----------------------------------------------------------------------===//
67 /// Configuration values for initial hash set sizes (log2).
69 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
73 //===----------------------------------------------------------------------===//
74 /// CompileUnit - This dwarf writer support class manages information associate
75 /// with a source file.
77 /// ID - File identifier for source.
81 /// Die - Compile unit debug information entry.
83 const OwningPtr<DIE> CUDie;
85 /// IndexTyDie - An anonymous type for index type. Owned by CUDie.
88 /// MDNodeToDieMap - Tracks the mapping of unit level debug informaton
89 /// variables to debug information entries.
90 DenseMap<const MDNode *, DIE *> MDNodeToDieMap;
92 /// MDNodeToDIEEntryMap - Tracks the mapping of unit level debug informaton
93 /// descriptors to debug information entries using a DIEEntry proxy.
94 DenseMap<const MDNode *, DIEEntry *> MDNodeToDIEEntryMap;
96 /// Globals - A map of globally visible named entities for this unit.
98 StringMap<DIE*> Globals;
100 /// GlobalTypes - A map of globally visible types for this unit.
102 StringMap<DIE*> GlobalTypes;
105 CompileUnit(unsigned I, DIE *D)
106 : ID(I), CUDie(D), IndexTyDie(0) {}
109 unsigned getID() const { return ID; }
110 DIE* getCUDie() const { return CUDie.get(); }
111 const StringMap<DIE*> &getGlobals() const { return Globals; }
112 const StringMap<DIE*> &getGlobalTypes() const { return GlobalTypes; }
114 /// hasContent - Return true if this compile unit has something to write out.
116 bool hasContent() const { return !CUDie->getChildren().empty(); }
118 /// addGlobal - Add a new global entity to the compile unit.
120 void addGlobal(StringRef Name, DIE *Die) { Globals[Name] = Die; }
122 /// addGlobalType - Add a new global type to the compile unit.
124 void addGlobalType(StringRef Name, DIE *Die) {
125 GlobalTypes[Name] = Die;
128 /// getDIE - Returns the debug information entry map slot for the
129 /// specified debug variable.
130 DIE *getDIE(const MDNode *N) { return MDNodeToDieMap.lookup(N); }
132 /// insertDIE - Insert DIE into the map.
133 void insertDIE(const MDNode *N, DIE *D) {
134 MDNodeToDieMap.insert(std::make_pair(N, D));
137 /// getDIEEntry - Returns the debug information entry for the speciefied
139 DIEEntry *getDIEEntry(const MDNode *N) {
140 DenseMap<const MDNode *, DIEEntry *>::iterator I =
141 MDNodeToDIEEntryMap.find(N);
142 if (I == MDNodeToDIEEntryMap.end())
147 /// insertDIEEntry - Insert debug information entry into the map.
148 void insertDIEEntry(const MDNode *N, DIEEntry *E) {
149 MDNodeToDIEEntryMap.insert(std::make_pair(N, E));
152 /// addDie - Adds or interns the DIE to the compile unit.
154 void addDie(DIE *Buffer) {
155 this->CUDie->addChild(Buffer);
158 // getIndexTyDie - Get an anonymous type for index type.
159 DIE *getIndexTyDie() {
163 // setIndexTyDie - Set D as anonymous type for index which can be reused
165 void setIndexTyDie(DIE *D) {
171 //===----------------------------------------------------------------------===//
172 /// DbgVariable - This class is used to track local variable information.
175 DIVariable Var; // Variable Descriptor.
176 DIE *TheDIE; // Variable DIE.
177 unsigned DotDebugLocOffset; // Offset in DotDebugLocEntries.
179 // AbsVar may be NULL.
180 DbgVariable(DIVariable V) : Var(V), TheDIE(0), DotDebugLocOffset(~0U) {}
183 DIVariable getVariable() const { return Var; }
184 void setDIE(DIE *D) { TheDIE = D; }
185 DIE *getDIE() const { return TheDIE; }
186 void setDotDebugLocOffset(unsigned O) { DotDebugLocOffset = O; }
187 unsigned getDotDebugLocOffset() const { return DotDebugLocOffset; }
188 StringRef getName() const { return Var.getName(); }
189 unsigned getTag() const { return Var.getTag(); }
190 bool variableHasComplexAddress() const {
191 assert(Var.Verify() && "Invalid complex DbgVariable!");
192 return Var.hasComplexAddress();
194 bool isBlockByrefVariable() const {
195 assert(Var.Verify() && "Invalid complex DbgVariable!");
196 return Var.isBlockByrefVariable();
198 unsigned getNumAddrElements() const {
199 assert(Var.Verify() && "Invalid complex DbgVariable!");
200 return Var.getNumAddrElements();
202 uint64_t getAddrElement(unsigned i) const {
203 return Var.getAddrElement(i);
205 DIType getType() const {
206 DIType Ty = Var.getType();
207 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
208 // addresses instead.
209 if (Var.isBlockByrefVariable()) {
210 /* Byref variables, in Blocks, are declared by the programmer as
211 "SomeType VarName;", but the compiler creates a
212 __Block_byref_x_VarName struct, and gives the variable VarName
213 either the struct, or a pointer to the struct, as its type. This
214 is necessary for various behind-the-scenes things the compiler
215 needs to do with by-reference variables in blocks.
217 However, as far as the original *programmer* is concerned, the
218 variable should still have type 'SomeType', as originally declared.
220 The following function dives into the __Block_byref_x_VarName
221 struct to find the original type of the variable. This will be
222 passed back to the code generating the type for the Debug
223 Information Entry for the variable 'VarName'. 'VarName' will then
224 have the original type 'SomeType' in its debug information.
226 The original type 'SomeType' will be the type of the field named
227 'VarName' inside the __Block_byref_x_VarName struct.
229 NOTE: In order for this to not completely fail on the debugger
230 side, the Debug Information Entry for the variable VarName needs to
231 have a DW_AT_location that tells the debugger how to unwind through
232 the pointers and __Block_byref_x_VarName struct to find the actual
233 value of the variable. The function addBlockByrefType does this. */
235 unsigned tag = Ty.getTag();
237 if (tag == dwarf::DW_TAG_pointer_type) {
238 DIDerivedType DTy = DIDerivedType(Ty);
239 subType = DTy.getTypeDerivedFrom();
242 DICompositeType blockStruct = DICompositeType(subType);
243 DIArray Elements = blockStruct.getTypeArray();
245 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
246 DIDescriptor Element = Elements.getElement(i);
247 DIDerivedType DT = DIDerivedType(Element);
248 if (getName() == DT.getName())
249 return (DT.getTypeDerivedFrom());
257 //===----------------------------------------------------------------------===//
258 /// DbgRange - This is used to track range of instructions with identical
259 /// debug info scope.
261 typedef std::pair<const MachineInstr *, const MachineInstr *> DbgRange;
263 //===----------------------------------------------------------------------===//
264 /// DbgScope - This class is used to track scope information.
267 DbgScope *Parent; // Parent to this scope.
268 DIDescriptor Desc; // Debug info descriptor for scope.
269 // Location at which this scope is inlined.
270 AssertingVH<const MDNode> InlinedAtLocation;
271 bool AbstractScope; // Abstract Scope
272 const MachineInstr *LastInsn; // Last instruction of this scope.
273 const MachineInstr *FirstInsn; // First instruction of this scope.
274 unsigned DFSIn, DFSOut;
275 // Scopes defined in scope. Contents not owned.
276 SmallVector<DbgScope *, 4> Scopes;
277 // Variables declared in scope. Contents owned.
278 SmallVector<DbgVariable *, 8> Variables;
279 SmallVector<DbgRange, 4> Ranges;
280 // Private state for dump()
281 mutable unsigned IndentLevel;
283 DbgScope(DbgScope *P, DIDescriptor D, const MDNode *I = 0)
284 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
285 LastInsn(0), FirstInsn(0),
286 DFSIn(0), DFSOut(0), IndentLevel(0) {}
290 DbgScope *getParent() const { return Parent; }
291 void setParent(DbgScope *P) { Parent = P; }
292 DIDescriptor getDesc() const { return Desc; }
293 const MDNode *getInlinedAt() const { return InlinedAtLocation; }
294 const MDNode *getScopeNode() const { return Desc; }
295 const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
296 const SmallVector<DbgVariable *, 8> &getDbgVariables() { return Variables; }
297 const SmallVector<DbgRange, 4> &getRanges() { return Ranges; }
299 /// openInsnRange - This scope covers instruction range starting from MI.
300 void openInsnRange(const MachineInstr *MI) {
305 Parent->openInsnRange(MI);
308 /// extendInsnRange - Extend the current instruction range covered by
310 void extendInsnRange(const MachineInstr *MI) {
311 assert (FirstInsn && "MI Range is not open!");
314 Parent->extendInsnRange(MI);
317 /// closeInsnRange - Create a range based on FirstInsn and LastInsn collected
318 /// until now. This is used when a new scope is encountered while walking
319 /// machine instructions.
320 void closeInsnRange(DbgScope *NewScope = NULL) {
321 assert (LastInsn && "Last insn missing!");
322 Ranges.push_back(DbgRange(FirstInsn, LastInsn));
325 // If Parent dominates NewScope then do not close Parent's instruction
327 if (Parent && (!NewScope || !Parent->dominates(NewScope)))
328 Parent->closeInsnRange(NewScope);
331 void setAbstractScope() { AbstractScope = true; }
332 bool isAbstractScope() const { return AbstractScope; }
334 // Depth First Search support to walk and mainpluate DbgScope hierarchy.
335 unsigned getDFSOut() const { return DFSOut; }
336 void setDFSOut(unsigned O) { DFSOut = O; }
337 unsigned getDFSIn() const { return DFSIn; }
338 void setDFSIn(unsigned I) { DFSIn = I; }
339 bool dominates(const DbgScope *S) {
342 if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
347 /// addScope - Add a scope to the scope.
349 void addScope(DbgScope *S) { Scopes.push_back(S); }
351 /// addVariable - Add a variable to the scope.
353 void addVariable(DbgVariable *V) { Variables.push_back(V); }
360 } // end llvm namespace
363 void DbgScope::dump() const {
364 raw_ostream &err = dbgs();
365 err.indent(IndentLevel);
366 const MDNode *N = Desc;
369 err << "Abstract Scope\n";
373 err << "Children ...\n";
374 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
375 if (Scopes[i] != this)
382 DbgScope::~DbgScope() {
383 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
387 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
388 : Asm(A), MMI(Asm->MMI), FirstCU(0),
389 AbbreviationsSet(InitAbbreviationsSetSize),
390 CurrentFnDbgScope(0), PrevLabel(NULL) {
391 NextStringPoolNumber = 0;
393 DwarfFrameSectionSym = DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
394 DwarfStrSectionSym = TextSectionSym = 0;
395 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
396 FunctionBeginSym = FunctionEndSym = 0;
397 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
399 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
403 DwarfDebug::~DwarfDebug() {
404 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
405 DIEBlocks[j]->~DIEBlock();
408 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
409 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
410 if (Entry.first) return Entry.first;
412 Entry.second = NextStringPoolNumber++;
413 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
417 /// assignAbbrevNumber - Define a unique number for the abbreviation.
419 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
420 // Profile the node so that we can make it unique.
424 // Check the set for priors.
425 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
427 // If it's newly added.
428 if (InSet == &Abbrev) {
429 // Add to abbreviation list.
430 Abbreviations.push_back(&Abbrev);
432 // Assign the vector position + 1 as its number.
433 Abbrev.setNumber(Abbreviations.size());
435 // Assign existing abbreviation number.
436 Abbrev.setNumber(InSet->getNumber());
440 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
441 /// information entry.
442 DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
443 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
447 /// addUInt - Add an unsigned integer attribute data and value.
449 void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
450 unsigned Form, uint64_t Integer) {
451 if (!Form) Form = DIEInteger::BestForm(false, Integer);
452 DIEValue *Value = Integer == 1 ?
453 DIEIntegerOne : new (DIEValueAllocator) DIEInteger(Integer);
454 Die->addValue(Attribute, Form, Value);
457 /// addSInt - Add an signed integer attribute data and value.
459 void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
460 unsigned Form, int64_t Integer) {
461 if (!Form) Form = DIEInteger::BestForm(true, Integer);
462 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
463 Die->addValue(Attribute, Form, Value);
466 /// addString - Add a string attribute data and value. DIEString only
467 /// keeps string reference.
468 void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
470 DIEValue *Value = new (DIEValueAllocator) DIEString(String);
471 Die->addValue(Attribute, Form, Value);
474 /// addLabel - Add a Dwarf label attribute data and value.
476 void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
477 const MCSymbol *Label) {
478 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
479 Die->addValue(Attribute, Form, Value);
482 /// addDelta - Add a label delta attribute data and value.
484 void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
485 const MCSymbol *Hi, const MCSymbol *Lo) {
486 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
487 Die->addValue(Attribute, Form, Value);
490 /// addDIEEntry - Add a DIE attribute data and value.
492 void DwarfDebug::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
494 Die->addValue(Attribute, Form, createDIEEntry(Entry));
498 /// addBlock - Add block data.
500 void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
502 Block->ComputeSize(Asm);
503 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
504 Die->addValue(Attribute, Block->BestForm(), Block);
507 /// addSourceLine - Add location information to specified debug information
509 void DwarfDebug::addSourceLine(DIE *Die, DIVariable V) {
514 unsigned Line = V.getLineNumber();
517 unsigned FileID = GetOrCreateSourceID(V.getContext().getFilename());
518 assert(FileID && "Invalid file id");
519 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
520 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
523 /// addSourceLine - Add location information to specified debug information
525 void DwarfDebug::addSourceLine(DIE *Die, DIGlobalVariable G) {
526 // Verify global variable.
530 unsigned Line = G.getLineNumber();
533 unsigned FileID = GetOrCreateSourceID(G.getContext().getFilename());
534 assert(FileID && "Invalid file id");
535 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
536 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
539 /// addSourceLine - Add location information to specified debug information
541 void DwarfDebug::addSourceLine(DIE *Die, DISubprogram SP) {
542 // Verify subprogram.
545 // If the line number is 0, don't add it.
546 if (SP.getLineNumber() == 0)
549 unsigned Line = SP.getLineNumber();
550 if (!SP.getContext().Verify())
552 unsigned FileID = GetOrCreateSourceID(SP.getFilename());
553 assert(FileID && "Invalid file id");
554 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
555 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
558 /// addSourceLine - Add location information to specified debug information
560 void DwarfDebug::addSourceLine(DIE *Die, DIType Ty) {
565 unsigned Line = Ty.getLineNumber();
566 if (Line == 0 || !Ty.getContext().Verify())
568 unsigned FileID = GetOrCreateSourceID(Ty.getFilename());
569 assert(FileID && "Invalid file id");
570 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
571 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
574 /// addSourceLine - Add location information to specified debug information
576 void DwarfDebug::addSourceLine(DIE *Die, DINameSpace NS) {
581 unsigned Line = NS.getLineNumber();
584 StringRef FN = NS.getFilename();
586 unsigned FileID = GetOrCreateSourceID(FN);
587 assert(FileID && "Invalid file id");
588 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
589 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
592 /// addVariableAddress - Add DW_AT_location attribute for a DbgVariable based
593 /// on provided frame index.
594 void DwarfDebug::addVariableAddress(DbgVariable *&DV, DIE *Die, int64_t FI) {
595 MachineLocation Location;
597 const TargetFrameInfo *TFI = Asm->TM.getFrameInfo();
598 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
599 Location.set(FrameReg, Offset);
601 if (DV->variableHasComplexAddress())
602 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
603 else if (DV->isBlockByrefVariable())
604 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
606 addAddress(Die, dwarf::DW_AT_location, Location);
609 /// addComplexAddress - Start with the address based on the location provided,
610 /// and generate the DWARF information necessary to find the actual variable
611 /// given the extra address information encoded in the DIVariable, starting from
612 /// the starting location. Add the DWARF information to the die.
614 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
616 const MachineLocation &Location) {
617 DIType Ty = DV->getType();
619 // Decode the original location, and use that as the start of the byref
620 // variable's location.
621 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
622 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
623 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
625 if (Location.isReg()) {
627 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
629 Reg = Reg - dwarf::DW_OP_reg0;
630 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
631 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
635 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
637 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
638 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
641 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
644 for (unsigned i = 0, N = DV->getNumAddrElements(); i < N; ++i) {
645 uint64_t Element = DV->getAddrElement(i);
647 if (Element == DIFactory::OpPlus) {
648 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
649 addUInt(Block, 0, dwarf::DW_FORM_udata, DV->getAddrElement(++i));
650 } else if (Element == DIFactory::OpDeref) {
651 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
652 } else llvm_unreachable("unknown DIFactory Opcode");
655 // Now attach the location information to the DIE.
656 addBlock(Die, Attribute, 0, Block);
659 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
660 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
661 gives the variable VarName either the struct, or a pointer to the struct, as
662 its type. This is necessary for various behind-the-scenes things the
663 compiler needs to do with by-reference variables in Blocks.
665 However, as far as the original *programmer* is concerned, the variable
666 should still have type 'SomeType', as originally declared.
668 The function getBlockByrefType dives into the __Block_byref_x_VarName
669 struct to find the original type of the variable, which is then assigned to
670 the variable's Debug Information Entry as its real type. So far, so good.
671 However now the debugger will expect the variable VarName to have the type
672 SomeType. So we need the location attribute for the variable to be an
673 expression that explains to the debugger how to navigate through the
674 pointers and struct to find the actual variable of type SomeType.
676 The following function does just that. We start by getting
677 the "normal" location for the variable. This will be the location
678 of either the struct __Block_byref_x_VarName or the pointer to the
679 struct __Block_byref_x_VarName.
681 The struct will look something like:
683 struct __Block_byref_x_VarName {
685 struct __Block_byref_x_VarName *forwarding;
686 ... <various other fields>
688 ... <maybe more fields>
691 If we are given the struct directly (as our starting point) we
692 need to tell the debugger to:
694 1). Add the offset of the forwarding field.
696 2). Follow that pointer to get the real __Block_byref_x_VarName
697 struct to use (the real one may have been copied onto the heap).
699 3). Add the offset for the field VarName, to find the actual variable.
701 If we started with a pointer to the struct, then we need to
702 dereference that pointer first, before the other steps.
703 Translating this into DWARF ops, we will need to append the following
704 to the current location description for the variable:
706 DW_OP_deref -- optional, if we start with a pointer
707 DW_OP_plus_uconst <forward_fld_offset>
709 DW_OP_plus_uconst <varName_fld_offset>
711 That is what this function does. */
713 /// addBlockByrefAddress - Start with the address based on the location
714 /// provided, and generate the DWARF information necessary to find the
715 /// actual Block variable (navigating the Block struct) based on the
716 /// starting location. Add the DWARF information to the die. For
717 /// more information, read large comment just above here.
719 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
721 const MachineLocation &Location) {
722 DIType Ty = DV->getType();
724 unsigned Tag = Ty.getTag();
725 bool isPointer = false;
727 StringRef varName = DV->getName();
729 if (Tag == dwarf::DW_TAG_pointer_type) {
730 DIDerivedType DTy = DIDerivedType(Ty);
731 TmpTy = DTy.getTypeDerivedFrom();
735 DICompositeType blockStruct = DICompositeType(TmpTy);
737 // Find the __forwarding field and the variable field in the __Block_byref
739 DIArray Fields = blockStruct.getTypeArray();
740 DIDescriptor varField = DIDescriptor();
741 DIDescriptor forwardingField = DIDescriptor();
743 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
744 DIDescriptor Element = Fields.getElement(i);
745 DIDerivedType DT = DIDerivedType(Element);
746 StringRef fieldName = DT.getName();
747 if (fieldName == "__forwarding")
748 forwardingField = Element;
749 else if (fieldName == varName)
753 // Get the offsets for the forwarding field and the variable field.
754 unsigned forwardingFieldOffset =
755 DIDerivedType(forwardingField).getOffsetInBits() >> 3;
756 unsigned varFieldOffset =
757 DIDerivedType(varField).getOffsetInBits() >> 3;
759 // Decode the original location, and use that as the start of the byref
760 // variable's location.
761 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
762 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
763 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
765 if (Location.isReg()) {
767 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
769 Reg = Reg - dwarf::DW_OP_reg0;
770 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
771 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
775 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
777 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
778 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
781 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
784 // If we started with a pointer to the __Block_byref... struct, then
785 // the first thing we need to do is dereference the pointer (DW_OP_deref).
787 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
789 // Next add the offset for the '__forwarding' field:
790 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
791 // adding the offset if it's 0.
792 if (forwardingFieldOffset > 0) {
793 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
794 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
797 // Now dereference the __forwarding field to get to the real __Block_byref
798 // struct: DW_OP_deref.
799 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
801 // Now that we've got the real __Block_byref... struct, add the offset
802 // for the variable's field to get to the location of the actual variable:
803 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
804 if (varFieldOffset > 0) {
805 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
806 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
809 // Now attach the location information to the DIE.
810 addBlock(Die, Attribute, 0, Block);
813 /// addAddress - Add an address attribute to a die based on the location
815 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
816 const MachineLocation &Location) {
817 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
818 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
819 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
821 if (RI->getFrameRegister(*Asm->MF) == Location.getReg()
822 && Location.getOffset()) {
823 // If variable offset is based in frame register then use fbreg.
824 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
825 addSInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
826 addBlock(Die, Attribute, 0, Block);
830 if (Location.isReg()) {
832 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
834 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
835 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
839 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
841 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
842 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
845 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
848 addBlock(Die, Attribute, 0, Block);
851 /// addRegisterAddress - Add register location entry in variable DIE.
852 bool DwarfDebug::addRegisterAddress(DIE *Die, const MachineOperand &MO) {
853 assert (MO.isReg() && "Invalid machine operand!");
856 MachineLocation Location;
857 Location.set(MO.getReg());
858 addAddress(Die, dwarf::DW_AT_location, Location);
862 /// addConstantValue - Add constant value entry in variable DIE.
863 bool DwarfDebug::addConstantValue(DIE *Die, const MachineOperand &MO) {
864 assert (MO.isImm() && "Invalid machine operand!");
865 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
866 unsigned Imm = MO.getImm();
867 addUInt(Block, 0, dwarf::DW_FORM_udata, Imm);
868 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
872 /// addConstantFPValue - Add constant value entry in variable DIE.
873 bool DwarfDebug::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
874 assert (MO.isFPImm() && "Invalid machine operand!");
875 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
876 APFloat FPImm = MO.getFPImm()->getValueAPF();
878 // Get the raw data form of the floating point.
879 const APInt FltVal = FPImm.bitcastToAPInt();
880 const char *FltPtr = (const char*)FltVal.getRawData();
882 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
883 bool LittleEndian = Asm->getTargetData().isLittleEndian();
884 int Incr = (LittleEndian ? 1 : -1);
885 int Start = (LittleEndian ? 0 : NumBytes - 1);
886 int Stop = (LittleEndian ? NumBytes : -1);
888 // Output the constant to DWARF one byte at a time.
889 for (; Start != Stop; Start += Incr)
890 addUInt(Block, 0, dwarf::DW_FORM_data1,
891 (unsigned char)0xFF & FltPtr[Start]);
893 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
898 /// addToContextOwner - Add Die into the list of its context owner's children.
899 void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
900 if (Context.isType()) {
901 DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context));
902 ContextDIE->addChild(Die);
903 } else if (Context.isNameSpace()) {
904 DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context));
905 ContextDIE->addChild(Die);
906 } else if (Context.isSubprogram()) {
907 DIE *ContextDIE = createSubprogramDIE(DISubprogram(Context));
908 ContextDIE->addChild(Die);
909 } else if (DIE *ContextDIE = getCompileUnit(Context)->getDIE(Context))
910 ContextDIE->addChild(Die);
912 getCompileUnit(Context)->addDie(Die);
915 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
917 DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
918 CompileUnit *TypeCU = getCompileUnit(Ty);
919 DIE *TyDIE = TypeCU->getDIE(Ty);
924 TyDIE = new DIE(dwarf::DW_TAG_base_type);
925 TypeCU->insertDIE(Ty, TyDIE);
926 if (Ty.isBasicType())
927 constructTypeDIE(*TyDIE, DIBasicType(Ty));
928 else if (Ty.isCompositeType())
929 constructTypeDIE(*TyDIE, DICompositeType(Ty));
931 assert(Ty.isDerivedType() && "Unknown kind of DIType");
932 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
935 addToContextOwner(TyDIE, Ty.getContext());
939 /// addType - Add a new type attribute to the specified entity.
940 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
944 // Check for pre-existence.
945 CompileUnit *TypeCU = getCompileUnit(Ty);
946 DIEEntry *Entry = TypeCU->getDIEEntry(Ty);
947 // If it exists then use the existing value.
949 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
954 DIE *Buffer = getOrCreateTypeDIE(Ty);
957 Entry = createDIEEntry(Buffer);
958 TypeCU->insertDIEEntry(Ty, Entry);
960 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
963 /// constructTypeDIE - Construct basic type die from DIBasicType.
964 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
965 // Get core information.
966 StringRef Name = BTy.getName();
967 Buffer.setTag(dwarf::DW_TAG_base_type);
968 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
971 // Add name if not anonymous or intermediate type.
973 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
974 uint64_t Size = BTy.getSizeInBits() >> 3;
975 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
978 /// constructTypeDIE - Construct derived type die from DIDerivedType.
979 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
980 // Get core information.
981 StringRef Name = DTy.getName();
982 uint64_t Size = DTy.getSizeInBits() >> 3;
983 unsigned Tag = DTy.getTag();
985 // FIXME - Workaround for templates.
986 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
990 // Map to main type, void will not have a type.
991 DIType FromTy = DTy.getTypeDerivedFrom();
992 addType(&Buffer, FromTy);
994 // Add name if not anonymous or intermediate type.
996 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
998 // Add size if non-zero (derived types might be zero-sized.)
1000 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1002 // Add source line info if available and TyDesc is not a forward declaration.
1003 if (!DTy.isForwardDecl())
1004 addSourceLine(&Buffer, DTy);
1007 /// constructTypeDIE - Construct type DIE from DICompositeType.
1008 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1009 // Get core information.
1010 StringRef Name = CTy.getName();
1012 uint64_t Size = CTy.getSizeInBits() >> 3;
1013 unsigned Tag = CTy.getTag();
1017 case dwarf::DW_TAG_vector_type:
1018 case dwarf::DW_TAG_array_type:
1019 constructArrayTypeDIE(Buffer, &CTy);
1021 case dwarf::DW_TAG_enumeration_type: {
1022 DIArray Elements = CTy.getTypeArray();
1024 // Add enumerators to enumeration type.
1025 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1026 DIE *ElemDie = NULL;
1027 DIDescriptor Enum(Elements.getElement(i));
1028 if (Enum.isEnumerator()) {
1029 ElemDie = constructEnumTypeDIE(DIEnumerator(Enum));
1030 Buffer.addChild(ElemDie);
1035 case dwarf::DW_TAG_subroutine_type: {
1037 DIArray Elements = CTy.getTypeArray();
1038 DIDescriptor RTy = Elements.getElement(0);
1039 addType(&Buffer, DIType(RTy));
1041 bool isPrototyped = true;
1043 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1044 DIDescriptor Ty = Elements.getElement(i);
1045 if (Ty.isUnspecifiedParameter()) {
1046 DIE *Arg = new DIE(dwarf::DW_TAG_unspecified_parameters);
1047 Buffer.addChild(Arg);
1048 isPrototyped = false;
1050 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1051 addType(Arg, DIType(Ty));
1052 Buffer.addChild(Arg);
1055 // Add prototype flag.
1057 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1060 case dwarf::DW_TAG_structure_type:
1061 case dwarf::DW_TAG_union_type:
1062 case dwarf::DW_TAG_class_type: {
1063 // Add elements to structure type.
1064 DIArray Elements = CTy.getTypeArray();
1066 // A forward struct declared type may not have elements available.
1067 unsigned N = Elements.getNumElements();
1071 // Add elements to structure type.
1072 for (unsigned i = 0; i < N; ++i) {
1073 DIDescriptor Element = Elements.getElement(i);
1074 DIE *ElemDie = NULL;
1075 if (Element.isSubprogram()) {
1076 DISubprogram SP(Element);
1077 ElemDie = createSubprogramDIE(DISubprogram(Element));
1078 if (SP.isProtected())
1079 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1080 dwarf::DW_ACCESS_protected);
1081 else if (SP.isPrivate())
1082 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1083 dwarf::DW_ACCESS_private);
1085 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1086 dwarf::DW_ACCESS_public);
1087 if (SP.isExplicit())
1088 addUInt(ElemDie, dwarf::DW_AT_explicit, dwarf::DW_FORM_flag, 1);
1090 else if (Element.isVariable()) {
1091 DIVariable DV(Element);
1092 ElemDie = new DIE(dwarf::DW_TAG_variable);
1093 addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1095 addType(ElemDie, DV.getType());
1096 addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1097 addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1098 addSourceLine(ElemDie, DV);
1099 } else if (Element.isDerivedType())
1100 ElemDie = createMemberDIE(DIDerivedType(Element));
1103 Buffer.addChild(ElemDie);
1106 if (CTy.isAppleBlockExtension())
1107 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1109 unsigned RLang = CTy.getRunTimeLang();
1111 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1112 dwarf::DW_FORM_data1, RLang);
1114 DICompositeType ContainingType = CTy.getContainingType();
1115 if (DIDescriptor(ContainingType).isCompositeType())
1116 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1117 getOrCreateTypeDIE(DIType(ContainingType)));
1119 DIDescriptor Context = CTy.getContext();
1120 addToContextOwner(&Buffer, Context);
1128 // Add name if not anonymous or intermediate type.
1130 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1132 if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type
1133 || Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1135 // Add size if non-zero (derived types might be zero-sized.)
1137 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1139 // Add zero size if it is not a forward declaration.
1140 if (CTy.isForwardDecl())
1141 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1143 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1146 // Add source line info if available.
1147 if (!CTy.isForwardDecl())
1148 addSourceLine(&Buffer, CTy);
1152 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1153 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1154 int64_t L = SR.getLo();
1155 int64_t H = SR.getHi();
1156 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1158 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1160 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1161 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1163 Buffer.addChild(DW_Subrange);
1166 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1167 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1168 DICompositeType *CTy) {
1169 Buffer.setTag(dwarf::DW_TAG_array_type);
1170 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1171 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1173 // Emit derived type.
1174 addType(&Buffer, CTy->getTypeDerivedFrom());
1175 DIArray Elements = CTy->getTypeArray();
1177 // Get an anonymous type for index type.
1178 CompileUnit *TheCU = getCompileUnit(*CTy);
1179 DIE *IdxTy = TheCU->getIndexTyDie();
1181 // Construct an anonymous type for index type.
1182 IdxTy = new DIE(dwarf::DW_TAG_base_type);
1183 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1184 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1185 dwarf::DW_ATE_signed);
1186 TheCU->addDie(IdxTy);
1187 TheCU->setIndexTyDie(IdxTy);
1190 // Add subranges to array type.
1191 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1192 DIDescriptor Element = Elements.getElement(i);
1193 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1194 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1198 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1199 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1200 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1201 StringRef Name = ETy.getName();
1202 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1203 int64_t Value = ETy.getEnumValue();
1204 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1208 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1209 /// printer to not emit usual symbol prefix before the symbol name is used then
1210 /// return linkage name after skipping this special LLVM prefix.
1211 static StringRef getRealLinkageName(StringRef LinkageName) {
1213 if (LinkageName.startswith(StringRef(&One, 1)))
1214 return LinkageName.substr(1);
1218 /// createMemberDIE - Create new member DIE.
1219 DIE *DwarfDebug::createMemberDIE(DIDerivedType DT) {
1220 DIE *MemberDie = new DIE(DT.getTag());
1221 StringRef Name = DT.getName();
1223 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1225 addType(MemberDie, DT.getTypeDerivedFrom());
1227 addSourceLine(MemberDie, DT);
1229 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1230 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1232 uint64_t Size = DT.getSizeInBits();
1233 uint64_t FieldSize = DT.getOriginalTypeSize();
1235 if (Size != FieldSize) {
1237 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1238 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1240 uint64_t Offset = DT.getOffsetInBits();
1241 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1242 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1243 uint64_t FieldOffset = (HiMark - FieldSize);
1244 Offset -= FieldOffset;
1246 // Maybe we need to work from the other end.
1247 if (Asm->getTargetData().isLittleEndian())
1248 Offset = FieldSize - (Offset + Size);
1249 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1251 // Here WD_AT_data_member_location points to the anonymous
1252 // field that includes this bit field.
1253 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1256 // This is not a bitfield.
1257 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1259 if (DT.getTag() == dwarf::DW_TAG_inheritance
1260 && DT.isVirtual()) {
1262 // For C++, virtual base classes are not at fixed offset. Use following
1263 // expression to extract appropriate offset from vtable.
1264 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1266 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1267 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1268 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1269 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1270 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1271 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1272 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1273 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1275 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1278 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1280 if (DT.isProtected())
1281 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1282 dwarf::DW_ACCESS_protected);
1283 else if (DT.isPrivate())
1284 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1285 dwarf::DW_ACCESS_private);
1286 // Otherwise C++ member and base classes are considered public.
1287 else if (DT.getCompileUnit().getLanguage() == dwarf::DW_LANG_C_plus_plus)
1288 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1289 dwarf::DW_ACCESS_public);
1291 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1292 dwarf::DW_VIRTUALITY_virtual);
1296 /// createSubprogramDIE - Create new DIE using SP.
1297 DIE *DwarfDebug::createSubprogramDIE(DISubprogram SP) {
1298 CompileUnit *SPCU = getCompileUnit(SP);
1299 DIE *SPDie = SPCU->getDIE(SP);
1303 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1304 // Constructors and operators for anonymous aggregates do not have names.
1305 if (!SP.getName().empty())
1306 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1308 StringRef LinkageName = SP.getLinkageName();
1309 if (!LinkageName.empty())
1310 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1311 getRealLinkageName(LinkageName));
1313 addSourceLine(SPDie, SP);
1315 if (SP.isPrototyped())
1316 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1319 DICompositeType SPTy = SP.getType();
1320 DIArray Args = SPTy.getTypeArray();
1321 unsigned SPTag = SPTy.getTag();
1323 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1324 addType(SPDie, SPTy);
1326 addType(SPDie, DIType(Args.getElement(0)));
1328 unsigned VK = SP.getVirtuality();
1330 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1331 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1332 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1333 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1334 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1335 ContainingTypeMap.insert(std::make_pair(SPDie,
1336 SP.getContainingType()));
1339 if (!SP.isDefinition()) {
1340 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1342 // Add arguments. Do not add arguments for subprogram definition. They will
1343 // be handled while processing variables.
1344 DICompositeType SPTy = SP.getType();
1345 DIArray Args = SPTy.getTypeArray();
1346 unsigned SPTag = SPTy.getTag();
1348 if (SPTag == dwarf::DW_TAG_subroutine_type)
1349 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1350 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1351 DIType ATy = DIType(DIType(Args.getElement(i)));
1353 if (ATy.isArtificial())
1354 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1355 SPDie->addChild(Arg);
1359 if (SP.isArtificial())
1360 addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1362 if (!SP.isLocalToUnit())
1363 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1365 if (SP.isOptimized())
1366 addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1368 if (unsigned isa = Asm->getISAEncoding()) {
1369 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1372 // DW_TAG_inlined_subroutine may refer to this DIE.
1373 SPCU->insertDIE(SP, SPDie);
1375 // Add to context owner.
1376 addToContextOwner(SPDie, SP.getContext());
1381 DbgScope *DwarfDebug::getOrCreateAbstractScope(const MDNode *N) {
1382 assert(N && "Invalid Scope encoding!");
1384 DbgScope *AScope = AbstractScopes.lookup(N);
1388 DbgScope *Parent = NULL;
1390 DIDescriptor Scope(N);
1391 if (Scope.isLexicalBlock()) {
1392 DILexicalBlock DB(N);
1393 DIDescriptor ParentDesc = DB.getContext();
1394 Parent = getOrCreateAbstractScope(ParentDesc);
1397 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1400 Parent->addScope(AScope);
1401 AScope->setAbstractScope();
1402 AbstractScopes[N] = AScope;
1403 if (DIDescriptor(N).isSubprogram())
1404 AbstractScopesList.push_back(AScope);
1408 /// isSubprogramContext - Return true if Context is either a subprogram
1409 /// or another context nested inside a subprogram.
1410 static bool isSubprogramContext(const MDNode *Context) {
1413 DIDescriptor D(Context);
1414 if (D.isSubprogram())
1417 return isSubprogramContext(DIType(Context).getContext());
1421 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1422 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1423 /// If there are global variables in this scope then create and insert
1424 /// DIEs for these variables.
1425 DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
1426 CompileUnit *SPCU = getCompileUnit(SPNode);
1427 DIE *SPDie = SPCU->getDIE(SPNode);
1429 assert(SPDie && "Unable to find subprogram DIE!");
1430 DISubprogram SP(SPNode);
1432 // There is not any need to generate specification DIE for a function
1433 // defined at compile unit level. If a function is defined inside another
1434 // function then gdb prefers the definition at top level and but does not
1435 // expect specification DIE in parent function. So avoid creating
1436 // specification DIE for a function defined inside a function.
1437 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
1438 !SP.getContext().isFile() &&
1439 !isSubprogramContext(SP.getContext())) {
1440 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1443 DICompositeType SPTy = SP.getType();
1444 DIArray Args = SPTy.getTypeArray();
1445 unsigned SPTag = SPTy.getTag();
1446 if (SPTag == dwarf::DW_TAG_subroutine_type)
1447 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1448 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1449 DIType ATy = DIType(DIType(Args.getElement(i)));
1451 if (ATy.isArtificial())
1452 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1453 SPDie->addChild(Arg);
1455 DIE *SPDeclDie = SPDie;
1456 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1457 addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1459 SPCU->addDie(SPDie);
1462 // Pick up abstract subprogram DIE.
1463 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
1464 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1465 addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
1466 dwarf::DW_FORM_ref4, AbsSPDIE);
1467 SPCU->addDie(SPDie);
1470 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1471 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
1472 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1473 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
1474 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1475 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
1476 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1481 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1482 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1483 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1485 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1486 if (Scope->isAbstractScope())
1489 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1493 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1494 if (Ranges.size() > 1) {
1495 // .debug_range section has not been laid out yet. Emit offset in
1496 // .debug_range as a uint, size 4, for now. emitDIE will handle
1497 // DW_AT_ranges appropriately.
1498 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
1499 DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
1500 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1501 RE = Ranges.end(); RI != RE; ++RI) {
1502 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
1503 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
1505 DebugRangeSymbols.push_back(NULL);
1506 DebugRangeSymbols.push_back(NULL);
1510 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
1511 const MCSymbol *End = getLabelAfterInsn(RI->second);
1513 if (End == 0) return 0;
1515 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1516 assert(End->isDefined() && "Invalid end label for an inlined scope!");
1518 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
1519 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
1524 /// constructInlinedScopeDIE - This scope represents inlined body of
1525 /// a function. Construct DIE to represent this concrete inlined copy
1526 /// of the function.
1527 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1529 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1530 assert (Ranges.empty() == false
1531 && "DbgScope does not have instruction markers!");
1533 // FIXME : .debug_inlined section specification does not clearly state how
1534 // to emit inlined scope that is split into multiple instruction ranges.
1535 // For now, use first instruction range and emit low_pc/high_pc pair and
1536 // corresponding .debug_inlined section entry for this pair.
1537 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1538 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
1539 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
1541 if (StartLabel == 0 || EndLabel == 0) {
1542 assert (0 && "Unexpected Start and End labels for a inlined scope!");
1545 assert(StartLabel->isDefined() &&
1546 "Invalid starting label for an inlined scope!");
1547 assert(EndLabel->isDefined() &&
1548 "Invalid end label for an inlined scope!");
1550 if (!Scope->getScopeNode())
1552 DIScope DS(Scope->getScopeNode());
1553 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1555 DISubprogram InlinedSP = getDISubprogram(DS);
1556 CompileUnit *TheCU = getCompileUnit(InlinedSP);
1557 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
1558 assert(OriginDIE && "Unable to find Origin DIE!");
1559 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1560 dwarf::DW_FORM_ref4, OriginDIE);
1562 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1563 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1565 InlinedSubprogramDIEs.insert(OriginDIE);
1567 // Track the start label for this inlined function.
1568 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1569 I = InlineInfo.find(InlinedSP);
1571 if (I == InlineInfo.end()) {
1572 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
1574 InlinedSPNodes.push_back(InlinedSP);
1576 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1578 DILocation DL(Scope->getInlinedAt());
1579 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
1580 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1586 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1587 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1588 StringRef Name = DV->getName();
1592 // Translate tag to proper Dwarf tag. The result variable is dropped for
1595 switch (DV->getTag()) {
1596 case dwarf::DW_TAG_return_variable:
1598 case dwarf::DW_TAG_arg_variable:
1599 Tag = dwarf::DW_TAG_formal_parameter;
1601 case dwarf::DW_TAG_auto_variable: // fall thru
1603 Tag = dwarf::DW_TAG_variable;
1607 // Define variable debug information entry.
1608 DIE *VariableDie = new DIE(Tag);
1611 DenseMap<const DbgVariable *, const DbgVariable *>::iterator
1612 V2AVI = VarToAbstractVarMap.find(DV);
1613 if (V2AVI != VarToAbstractVarMap.end())
1614 AbsDIE = V2AVI->second->getDIE();
1617 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1618 dwarf::DW_FORM_ref4, AbsDIE);
1620 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1621 addSourceLine(VariableDie, DV->getVariable());
1623 // Add variable type.
1624 addType(VariableDie, DV->getType());
1627 if (Tag == dwarf::DW_TAG_formal_parameter && DV->getType().isArtificial())
1628 addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1629 else if (DIVariable(DV->getVariable()).isArtificial())
1630 addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1632 if (Scope->isAbstractScope()) {
1633 DV->setDIE(VariableDie);
1637 // Add variable address.
1639 unsigned Offset = DV->getDotDebugLocOffset();
1640 if (Offset != ~0U) {
1641 addLabel(VariableDie, dwarf::DW_AT_location, dwarf::DW_FORM_data4,
1642 Asm->GetTempSymbol("debug_loc", Offset));
1643 DV->setDIE(VariableDie);
1644 UseDotDebugLocEntry.insert(VariableDie);
1648 // Check if variable is described by a DBG_VALUE instruction.
1649 DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
1650 DbgVariableToDbgInstMap.find(DV);
1651 if (DVI != DbgVariableToDbgInstMap.end()) {
1652 const MachineInstr *DVInsn = DVI->second;
1653 bool updated = false;
1654 // FIXME : Handle getNumOperands != 3
1655 if (DVInsn->getNumOperands() == 3) {
1656 if (DVInsn->getOperand(0).isReg()) {
1657 const MachineOperand RegOp = DVInsn->getOperand(0);
1658 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1659 if (DVInsn->getOperand(1).isImm() &&
1660 TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
1661 addVariableAddress(DV, VariableDie, DVInsn->getOperand(1).getImm());
1664 updated = addRegisterAddress(VariableDie, RegOp);
1666 else if (DVInsn->getOperand(0).isImm())
1667 updated = addConstantValue(VariableDie, DVInsn->getOperand(0));
1668 else if (DVInsn->getOperand(0).isFPImm())
1670 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1672 MachineLocation Location = Asm->getDebugValueLocation(DVInsn);
1673 if (Location.getReg()) {
1674 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1679 // If variableDie is not updated then DBG_VALUE instruction does not
1680 // have valid variable info.
1684 DV->setDIE(VariableDie);
1688 // .. else use frame index, if available.
1690 if (findVariableFrameIndex(DV, &FI))
1691 addVariableAddress(DV, VariableDie, FI);
1693 DV->setDIE(VariableDie);
1698 void DwarfDebug::addPubTypes(DISubprogram SP) {
1699 DICompositeType SPTy = SP.getType();
1700 unsigned SPTag = SPTy.getTag();
1701 if (SPTag != dwarf::DW_TAG_subroutine_type)
1704 DIArray Args = SPTy.getTypeArray();
1705 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1706 DIType ATy(Args.getElement(i));
1709 DICompositeType CATy = getDICompositeType(ATy);
1710 if (DIDescriptor(CATy).Verify() && !CATy.getName().empty()
1711 && !CATy.isForwardDecl()) {
1712 CompileUnit *TheCU = getCompileUnit(CATy);
1713 if (DIEEntry *Entry = TheCU->getDIEEntry(CATy))
1714 TheCU->addGlobalType(CATy.getName(), Entry->getEntry());
1719 /// constructScopeDIE - Construct a DIE for this scope.
1720 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1721 if (!Scope || !Scope->getScopeNode())
1724 DIScope DS(Scope->getScopeNode());
1725 DIE *ScopeDIE = NULL;
1726 if (Scope->getInlinedAt())
1727 ScopeDIE = constructInlinedScopeDIE(Scope);
1728 else if (DS.isSubprogram()) {
1729 ProcessedSPNodes.insert(DS);
1730 if (Scope->isAbstractScope()) {
1731 ScopeDIE = getCompileUnit(DS)->getDIE(DS);
1732 // Note down abstract DIE.
1734 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
1737 ScopeDIE = updateSubprogramScopeDIE(DS);
1740 ScopeDIE = constructLexicalScopeDIE(Scope);
1741 if (!ScopeDIE) return NULL;
1743 // Add variables to scope.
1744 const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
1745 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1746 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1748 ScopeDIE->addChild(VariableDIE);
1751 // Add nested scopes.
1752 const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1753 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1754 // Define the Scope debug information entry.
1755 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1757 ScopeDIE->addChild(NestedDIE);
1760 if (DS.isSubprogram())
1761 addPubTypes(DISubprogram(DS));
1766 /// GetOrCreateSourceID - Look up the source id with the given directory and
1767 /// source file names. If none currently exists, create a new id and insert it
1768 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1771 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName){
1772 // If FE did not provide a file name, then assume stdin.
1773 if (FileName.empty())
1774 return GetOrCreateSourceID("<stdin>");
1776 StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
1777 if (Entry.getValue())
1778 return Entry.getValue();
1780 unsigned SrcId = SourceIdMap.size();
1781 Entry.setValue(SrcId);
1783 // Print out a .file directive to specify files for .loc directives.
1784 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, FileName);
1789 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1790 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1791 CompileUnit *TheCU = getCompileUnit(NS);
1792 DIE *NDie = TheCU->getDIE(NS);
1795 NDie = new DIE(dwarf::DW_TAG_namespace);
1796 TheCU->insertDIE(NS, NDie);
1797 if (!NS.getName().empty())
1798 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1799 addSourceLine(NDie, NS);
1800 addToContextOwner(NDie, NS.getContext());
1804 /// constructCompileUnit - Create new CompileUnit for the given
1805 /// metadata node with tag DW_TAG_compile_unit.
1806 void DwarfDebug::constructCompileUnit(const MDNode *N) {
1807 DICompileUnit DIUnit(N);
1808 StringRef FN = DIUnit.getFilename();
1809 StringRef Dir = DIUnit.getDirectory();
1810 unsigned ID = GetOrCreateSourceID(FN);
1812 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1813 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1814 DIUnit.getProducer());
1815 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1816 DIUnit.getLanguage());
1817 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1818 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
1819 // simplifies debug range entries.
1820 addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
1821 // DW_AT_stmt_list is a offset of line number information for this
1822 // compile unit in debug_line section.
1823 if (Asm->MAI->doesDwarfUsesAbsoluteLabelForStmtList())
1824 addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_addr,
1825 Asm->GetTempSymbol("section_line"));
1827 addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
1830 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1831 if (DIUnit.isOptimized())
1832 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1834 StringRef Flags = DIUnit.getFlags();
1836 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1838 unsigned RVer = DIUnit.getRunTimeVersion();
1840 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1841 dwarf::DW_FORM_data1, RVer);
1843 CompileUnit *NewCU = new CompileUnit(ID, Die);
1846 CUMap.insert(std::make_pair(N, NewCU));
1849 /// getCompielUnit - Get CompileUnit DIE.
1850 CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
1851 assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
1853 const MDNode *CUNode = NULL;
1854 if (D.isCompileUnit())
1856 else if (D.isSubprogram())
1857 CUNode = DISubprogram(N).getCompileUnit();
1858 else if (D.isType())
1859 CUNode = DIType(N).getCompileUnit();
1860 else if (D.isGlobalVariable())
1861 CUNode = DIGlobalVariable(N).getCompileUnit();
1862 else if (D.isVariable())
1863 CUNode = DIVariable(N).getCompileUnit();
1864 else if (D.isNameSpace())
1865 CUNode = DINameSpace(N).getCompileUnit();
1866 else if (D.isFile())
1867 CUNode = DIFile(N).getCompileUnit();
1871 DenseMap<const MDNode *, CompileUnit *>::const_iterator I
1872 = CUMap.find(CUNode);
1873 if (I == CUMap.end())
1878 /// isUnsignedDIType - Return true if type encoding is unsigned.
1879 static bool isUnsignedDIType(DIType Ty) {
1880 DIDerivedType DTy(Ty);
1882 return isUnsignedDIType(DTy.getTypeDerivedFrom());
1884 DIBasicType BTy(Ty);
1886 unsigned Encoding = BTy.getEncoding();
1887 if (Encoding == dwarf::DW_ATE_unsigned ||
1888 Encoding == dwarf::DW_ATE_unsigned_char)
1894 /// constructGlobalVariableDIE - Construct global variable DIE.
1895 void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
1896 DIGlobalVariable GV(N);
1898 // If debug information is malformed then ignore it.
1899 if (GV.Verify() == false)
1902 // Check for pre-existence.
1903 CompileUnit *TheCU = getCompileUnit(N);
1904 if (TheCU->getDIE(GV))
1907 DIType GTy = GV.getType();
1908 DIE *VariableDIE = new DIE(GV.getTag());
1910 bool isGlobalVariable = GV.getGlobal() != NULL;
1913 addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1914 GV.getDisplayName());
1915 StringRef LinkageName = GV.getLinkageName();
1916 if (!LinkageName.empty() && isGlobalVariable)
1917 addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1918 getRealLinkageName(LinkageName));
1920 addType(VariableDIE, GTy);
1921 if (GTy.isCompositeType() && !GTy.getName().empty()
1922 && !GTy.isForwardDecl()) {
1923 DIEEntry *Entry = TheCU->getDIEEntry(GTy);
1924 assert(Entry && "Missing global type!");
1925 TheCU->addGlobalType(GTy.getName(), Entry->getEntry());
1927 // Add scoping info.
1928 if (!GV.isLocalToUnit()) {
1929 addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1930 // Expose as global.
1931 TheCU->addGlobal(GV.getName(), VariableDIE);
1933 // Add line number info.
1934 addSourceLine(VariableDIE, GV);
1936 TheCU->insertDIE(N, VariableDIE);
1937 // Add to context owner.
1938 DIDescriptor GVContext = GV.getContext();
1939 addToContextOwner(VariableDIE, GVContext);
1941 if (isGlobalVariable) {
1942 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1943 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1944 addLabel(Block, 0, dwarf::DW_FORM_udata,
1945 Asm->Mang->getSymbol(GV.getGlobal()));
1946 // Do not create specification DIE if context is either compile unit
1948 if (GV.isDefinition() && !GVContext.isCompileUnit() &&
1949 !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1950 // Create specification DIE.
1951 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1952 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1953 dwarf::DW_FORM_ref4, VariableDIE);
1954 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1955 addUInt(VariableDIE, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1956 TheCU->addDie(VariableSpecDIE);
1958 addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1960 } else if (Constant *C = GV.getConstant()) {
1961 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1962 if (isUnsignedDIType(GTy))
1963 addUInt(VariableDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
1964 CI->getZExtValue());
1966 addSInt(VariableDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1967 CI->getSExtValue());
1973 /// construct SubprogramDIE - Construct subprogram DIE.
1974 void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
1977 // Check for pre-existence.
1978 CompileUnit *TheCU = getCompileUnit(N);
1979 if (TheCU->getDIE(N))
1982 if (!SP.isDefinition())
1983 // This is a method declaration which will be handled while constructing
1987 DIE *SubprogramDie = createSubprogramDIE(SP);
1990 TheCU->insertDIE(N, SubprogramDie);
1992 // Add to context owner.
1993 addToContextOwner(SubprogramDie, SP.getContext());
1995 // Expose as global.
1996 TheCU->addGlobal(SP.getName(), SubprogramDie);
2001 /// beginModule - Emit all Dwarf sections that should come prior to the
2002 /// content. Create global DIEs and emit initial debug info sections.
2003 /// This is inovked by the target AsmPrinter.
2004 void DwarfDebug::beginModule(Module *M) {
2005 if (DisableDebugInfoPrinting)
2008 DebugInfoFinder DbgFinder;
2009 DbgFinder.processModule(*M);
2011 bool HasDebugInfo = false;
2013 // Scan all the compile-units to see if there are any marked as the main unit.
2014 // if not, we do not generate debug info.
2015 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
2016 E = DbgFinder.compile_unit_end(); I != E; ++I) {
2017 if (DICompileUnit(*I).isMain()) {
2018 HasDebugInfo = true;
2023 if (!HasDebugInfo) return;
2025 // Tell MMI that we have debug info.
2026 MMI->setDebugInfoAvailability(true);
2028 // Emit initial sections.
2029 EmitSectionLabels();
2031 // Create all the compile unit DIEs.
2032 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
2033 E = DbgFinder.compile_unit_end(); I != E; ++I)
2034 constructCompileUnit(*I);
2036 // Create DIEs for each subprogram.
2037 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
2038 E = DbgFinder.subprogram_end(); I != E; ++I)
2039 constructSubprogramDIE(*I);
2041 // Create DIEs for each global variable.
2042 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
2043 E = DbgFinder.global_variable_end(); I != E; ++I)
2044 constructGlobalVariableDIE(*I);
2046 //getOrCreateTypeDIE
2047 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
2048 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
2049 getOrCreateTypeDIE(DIType(NMD->getOperand(i)));
2051 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
2052 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
2053 getOrCreateTypeDIE(DIType(NMD->getOperand(i)));
2055 // Prime section data.
2056 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
2059 /// endModule - Emit all Dwarf sections that should come after the content.
2061 void DwarfDebug::endModule() {
2062 if (!FirstCU) return;
2063 const Module *M = MMI->getModule();
2064 DenseMap<const MDNode *, DbgScope *> DeadFnScopeMap;
2065 if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
2066 for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
2067 if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
2068 DISubprogram SP(AllSPs->getOperand(SI));
2069 if (!SP.Verify()) continue;
2071 // Collect info for variables that were optimized out.
2072 if (!SP.isDefinition()) continue;
2073 StringRef FName = SP.getLinkageName();
2075 FName = SP.getName();
2076 NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
2078 unsigned E = NMD->getNumOperands();
2080 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(SP), NULL);
2081 DeadFnScopeMap[SP] = Scope;
2082 for (unsigned I = 0; I != E; ++I) {
2083 DIVariable DV(NMD->getOperand(I));
2084 if (!DV.Verify()) continue;
2085 Scope->addVariable(new DbgVariable(DV));
2088 // Construct subprogram DIE and add variables DIEs.
2089 constructSubprogramDIE(SP);
2090 DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
2091 const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
2092 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2093 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
2095 ScopeDIE->addChild(VariableDIE);
2100 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
2101 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
2102 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
2104 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
2107 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
2108 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
2109 DIE *SPDie = CI->first;
2110 const MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
2112 DIE *NDie = getCompileUnit(N)->getDIE(N);
2113 if (!NDie) continue;
2114 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
2117 // Standard sections final addresses.
2118 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
2119 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
2120 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
2121 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
2123 // End text sections.
2124 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2125 Asm->OutStreamer.SwitchSection(SectionMap[i]);
2126 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
2129 // Emit common frame information.
2130 emitCommonDebugFrame();
2132 // Emit function debug frame information
2133 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2134 E = DebugFrames.end(); I != E; ++I)
2135 emitFunctionDebugFrame(*I);
2137 // Compute DIE offsets and sizes.
2138 computeSizeAndOffsets();
2140 // Emit all the DIEs into a debug info section
2143 // Corresponding abbreviations into a abbrev section.
2144 emitAbbreviations();
2146 // Emit info into a debug pubnames section.
2147 emitDebugPubNames();
2149 // Emit info into a debug pubtypes section.
2150 emitDebugPubTypes();
2152 // Emit info into a debug loc section.
2155 // Emit info into a debug aranges section.
2158 // Emit info into a debug ranges section.
2161 // Emit info into a debug macinfo section.
2164 // Emit inline info.
2165 emitDebugInlineInfo();
2167 // Emit info into a debug str section.
2171 DeleteContainerSeconds(DeadFnScopeMap);
2172 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2173 E = CUMap.end(); I != E; ++I)
2175 FirstCU = NULL; // Reset for the next Module, if any.
2178 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2179 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2180 DebugLoc ScopeLoc) {
2182 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
2184 return AbsDbgVariable;
2186 LLVMContext &Ctx = Var->getContext();
2187 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2191 AbsDbgVariable = new DbgVariable(Var);
2192 Scope->addVariable(AbsDbgVariable);
2193 AbstractVariables[Var] = AbsDbgVariable;
2194 return AbsDbgVariable;
2197 /// collectVariableInfoFromMMITable - Collect variable information from
2198 /// side table maintained by MMI.
2200 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction * MF,
2201 SmallPtrSet<const MDNode *, 16> &Processed) {
2202 const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2203 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
2204 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
2205 VE = VMap.end(); VI != VE; ++VI) {
2206 const MDNode *Var = VI->first;
2208 Processed.insert(Var);
2210 const std::pair<unsigned, DebugLoc> &VP = VI->second;
2212 DbgScope *Scope = 0;
2213 if (const MDNode *IA = VP.second.getInlinedAt(Ctx))
2214 Scope = ConcreteScopes.lookup(IA);
2216 Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
2218 // If variable scope is not found then skip this variable.
2222 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
2223 DbgVariable *RegVar = new DbgVariable(DV);
2224 recordVariableFrameIndex(RegVar, VP.first);
2225 Scope->addVariable(RegVar);
2226 if (AbsDbgVariable) {
2227 recordVariableFrameIndex(AbsDbgVariable, VP.first);
2228 VarToAbstractVarMap[RegVar] = AbsDbgVariable;
2233 /// isDbgValueInUndefinedReg - Return true if debug value, encoded by
2234 /// DBG_VALUE instruction, is in undefined reg.
2235 static bool isDbgValueInUndefinedReg(const MachineInstr *MI) {
2236 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
2237 if (MI->getOperand(0).isReg() && !MI->getOperand(0).getReg())
2242 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
2243 /// DBG_VALUE instruction, is in a defined reg.
2244 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
2245 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
2246 if (MI->getOperand(0).isReg() && MI->getOperand(0).getReg())
2251 /// collectVariableInfo - Populate DbgScope entries with variables' info.
2253 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
2254 SmallPtrSet<const MDNode *, 16> &Processed) {
2256 /// collection info from MMI table.
2257 collectVariableInfoFromMMITable(MF, Processed);
2259 SmallVector<const MachineInstr *, 8> DbgValues;
2260 // Collect variable information from DBG_VALUE machine instructions;
2261 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2263 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2265 const MachineInstr *MInsn = II;
2266 if (!MInsn->isDebugValue() || isDbgValueInUndefinedReg(MInsn))
2268 DbgValues.push_back(MInsn);
2271 // This is a collection of DBV_VALUE instructions describing same variable.
2272 SmallVector<const MachineInstr *, 4> MultipleValues;
2273 for(SmallVector<const MachineInstr *, 8>::iterator I = DbgValues.begin(),
2274 E = DbgValues.end(); I != E; ++I) {
2275 const MachineInstr *MInsn = *I;
2276 MultipleValues.clear();
2277 if (isDbgValueInDefinedReg(MInsn))
2278 MultipleValues.push_back(MInsn);
2279 DIVariable DV(MInsn->getOperand(MInsn->getNumOperands() - 1).getMetadata());
2280 if (Processed.count(DV) != 0)
2283 const MachineInstr *PrevMI = MInsn;
2284 for (SmallVector<const MachineInstr *, 8>::iterator MI = I+1,
2285 ME = DbgValues.end(); MI != ME; ++MI) {
2287 (*MI)->getOperand((*MI)->getNumOperands()-1).getMetadata();
2288 if (Var == DV && isDbgValueInDefinedReg(*MI) &&
2289 !PrevMI->isIdenticalTo(*MI))
2290 MultipleValues.push_back(*MI);
2294 DbgScope *Scope = findDbgScope(MInsn);
2295 bool CurFnArg = false;
2296 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
2297 DISubprogram(DV.getContext()).describes(MF->getFunction()))
2299 if (!Scope && CurFnArg)
2300 Scope = CurrentFnDbgScope;
2301 // If variable scope is not found then skip this variable.
2305 Processed.insert(DV);
2306 DbgVariable *RegVar = new DbgVariable(DV);
2307 Scope->addVariable(RegVar);
2308 if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) {
2309 DbgVariableToDbgInstMap[AbsVar] = MInsn;
2310 VarToAbstractVarMap[RegVar] = AbsVar;
2312 if (MultipleValues.size() <= 1) {
2313 DbgVariableToDbgInstMap[RegVar] = MInsn;
2317 // handle multiple DBG_VALUE instructions describing one variable.
2318 if (DotDebugLocEntries.empty())
2319 RegVar->setDotDebugLocOffset(0);
2321 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
2322 const MachineInstr *Begin = NULL;
2323 const MachineInstr *End = NULL;
2324 for (SmallVector<const MachineInstr *, 4>::iterator
2325 MVI = MultipleValues.begin(), MVE = MultipleValues.end();
2326 MVI != MVE; ++MVI) {
2332 MachineLocation MLoc;
2333 if (Begin->getNumOperands() == 3) {
2334 if (Begin->getOperand(0).isReg() && Begin->getOperand(1).isImm())
2335 MLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
2337 MLoc = Asm->getDebugValueLocation(Begin);
2339 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
2340 const MCSymbol *SLabel = getLabelBeforeInsn(End);
2342 DotDebugLocEntries.push_back(DotDebugLocEntry(FLabel, SLabel, MLoc));
2345 if (MVI + 1 == MVE) {
2346 // If End is the last instruction then its value is valid
2347 // until the end of the funtion.
2348 MachineLocation EMLoc;
2349 if (End->getNumOperands() == 3) {
2350 if (End->getOperand(0).isReg() && Begin->getOperand(1).isImm())
2351 EMLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
2353 EMLoc = Asm->getDebugValueLocation(End);
2356 push_back(DotDebugLocEntry(SLabel, FunctionEndSym, EMLoc));
2359 DotDebugLocEntries.push_back(DotDebugLocEntry());
2362 // Collect info for variables that were optimized out.
2363 const Function *F = MF->getFunction();
2364 if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
2365 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2366 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2367 if (!DV || !Processed.insert(DV))
2369 DbgScope *Scope = DbgScopeMap.lookup(DV.getContext());
2371 Scope->addVariable(new DbgVariable(DV));
2376 /// getLabelBeforeInsn - Return Label preceding the instruction.
2377 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
2378 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
2379 LabelsBeforeInsn.find(MI);
2380 if (I == LabelsBeforeInsn.end())
2381 // FunctionBeginSym always preceeds all the instruction in current function.
2382 return FunctionBeginSym;
2386 /// getLabelAfterInsn - Return Label immediately following the instruction.
2387 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
2388 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
2389 LabelsAfterInsn.find(MI);
2390 if (I == LabelsAfterInsn.end())
2395 /// beginInstruction - Process beginning of an instruction.
2396 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
2397 if (InsnNeedsLabel.count(MI) == 0) {
2398 LabelsBeforeInsn[MI] = PrevLabel;
2403 DebugLoc DL = MI->getDebugLoc();
2404 if (!DL.isUnknown()) {
2405 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
2406 PrevLabel = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2408 LabelsBeforeInsn[MI] = PrevLabel;
2412 // If location is unknown then use temp label for this DBG_VALUE
2414 if (MI->isDebugValue()) {
2415 PrevLabel = MMI->getContext().CreateTempSymbol();
2416 Asm->OutStreamer.EmitLabel(PrevLabel);
2417 LabelsBeforeInsn[MI] = PrevLabel;
2421 if (UnknownLocations) {
2422 PrevLabel = recordSourceLine(0, 0, 0);
2423 LabelsBeforeInsn[MI] = PrevLabel;
2427 assert (0 && "Instruction is not processed!");
2430 /// endInstruction - Process end of an instruction.
2431 void DwarfDebug::endInstruction(const MachineInstr *MI) {
2432 if (InsnsEndScopeSet.count(MI) != 0) {
2433 // Emit a label if this instruction ends a scope.
2434 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2435 Asm->OutStreamer.EmitLabel(Label);
2436 LabelsAfterInsn[MI] = Label;
2440 /// getOrCreateDbgScope - Create DbgScope for the scope.
2441 DbgScope *DwarfDebug::getOrCreateDbgScope(const MDNode *Scope,
2442 const MDNode *InlinedAt) {
2444 DbgScope *WScope = DbgScopeMap.lookup(Scope);
2447 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2448 DbgScopeMap.insert(std::make_pair(Scope, WScope));
2449 if (DIDescriptor(Scope).isLexicalBlock()) {
2451 getOrCreateDbgScope(DILexicalBlock(Scope).getContext(), NULL);
2452 WScope->setParent(Parent);
2453 Parent->addScope(WScope);
2456 if (!WScope->getParent()) {
2457 StringRef SPName = DISubprogram(Scope).getLinkageName();
2458 // We used to check only for a linkage name, but that fails
2459 // since we began omitting the linkage name for private
2460 // functions. The new way is to check for the name in metadata,
2461 // but that's not supported in old .ll test cases. Ergo, we
2463 if (SPName == Asm->MF->getFunction()->getName() ||
2464 DISubprogram(Scope).getFunction() == Asm->MF->getFunction())
2465 CurrentFnDbgScope = WScope;
2471 getOrCreateAbstractScope(Scope);
2472 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2476 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2477 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2478 DILocation DL(InlinedAt);
2480 getOrCreateDbgScope(DL.getScope(), DL.getOrigLocation());
2481 WScope->setParent(Parent);
2482 Parent->addScope(WScope);
2484 ConcreteScopes[InlinedAt] = WScope;
2489 /// hasValidLocation - Return true if debug location entry attached with
2490 /// machine instruction encodes valid location info.
2491 static bool hasValidLocation(LLVMContext &Ctx,
2492 const MachineInstr *MInsn,
2493 const MDNode *&Scope, const MDNode *&InlinedAt) {
2494 DebugLoc DL = MInsn->getDebugLoc();
2495 if (DL.isUnknown()) return false;
2497 const MDNode *S = DL.getScope(Ctx);
2499 // There is no need to create another DIE for compile unit. For all
2500 // other scopes, create one DbgScope now. This will be translated
2501 // into a scope DIE at the end.
2502 if (DIScope(S).isCompileUnit()) return false;
2505 InlinedAt = DL.getInlinedAt(Ctx);
2509 /// calculateDominanceGraph - Calculate dominance graph for DbgScope
2511 static void calculateDominanceGraph(DbgScope *Scope) {
2512 assert (Scope && "Unable to calculate scop edominance graph!");
2513 SmallVector<DbgScope *, 4> WorkStack;
2514 WorkStack.push_back(Scope);
2515 unsigned Counter = 0;
2516 while (!WorkStack.empty()) {
2517 DbgScope *WS = WorkStack.back();
2518 const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
2519 bool visitedChildren = false;
2520 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2521 SE = Children.end(); SI != SE; ++SI) {
2522 DbgScope *ChildScope = *SI;
2523 if (!ChildScope->getDFSOut()) {
2524 WorkStack.push_back(ChildScope);
2525 visitedChildren = true;
2526 ChildScope->setDFSIn(++Counter);
2530 if (!visitedChildren) {
2531 WorkStack.pop_back();
2532 WS->setDFSOut(++Counter);
2537 /// printDbgScopeInfo - Print DbgScope info for each machine instruction.
2539 void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
2540 DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
2543 unsigned PrevDFSIn = 0;
2544 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2546 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2548 const MachineInstr *MInsn = II;
2549 const MDNode *Scope = NULL;
2550 const MDNode *InlinedAt = NULL;
2552 // Check if instruction has valid location information.
2553 if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2557 DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
2558 MI2ScopeMap.find(MInsn);
2559 if (DI != MI2ScopeMap.end()) {
2560 DbgScope *S = DI->second;
2561 dbgs() << S->getDFSIn();
2562 PrevDFSIn = S->getDFSIn();
2564 dbgs() << PrevDFSIn;
2566 dbgs() << " [ x" << PrevDFSIn;
2574 /// extractScopeInformation - Scan machine instructions in this function
2575 /// and collect DbgScopes. Return true, if at least one scope was found.
2576 bool DwarfDebug::extractScopeInformation() {
2577 // If scope information was extracted using .dbg intrinsics then there is not
2578 // any need to extract these information by scanning each instruction.
2579 if (!DbgScopeMap.empty())
2582 // Scan each instruction and create scopes. First build working set of scopes.
2583 LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2584 SmallVector<DbgRange, 4> MIRanges;
2585 DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
2586 const MDNode *PrevScope = NULL;
2587 const MDNode *PrevInlinedAt = NULL;
2588 const MachineInstr *RangeBeginMI = NULL;
2589 const MachineInstr *PrevMI = NULL;
2590 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2592 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2594 const MachineInstr *MInsn = II;
2595 const MDNode *Scope = NULL;
2596 const MDNode *InlinedAt = NULL;
2598 // Check if instruction has valid location information.
2599 if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2604 // If scope has not changed then skip this instruction.
2605 if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
2611 // If we have alread seen a beginning of a instruction range and
2612 // current instruction scope does not match scope of first instruction
2613 // in this range then create a new instruction range.
2614 DbgRange R(RangeBeginMI, PrevMI);
2615 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope,
2617 MIRanges.push_back(R);
2620 // This is a beginning of a new instruction range.
2621 RangeBeginMI = MInsn;
2623 // Reset previous markers.
2626 PrevInlinedAt = InlinedAt;
2630 // Create last instruction range.
2631 if (RangeBeginMI && PrevMI && PrevScope) {
2632 DbgRange R(RangeBeginMI, PrevMI);
2633 MIRanges.push_back(R);
2634 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2637 if (!CurrentFnDbgScope)
2640 calculateDominanceGraph(CurrentFnDbgScope);
2642 printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
2644 // Find ranges of instructions covered by each DbgScope;
2645 DbgScope *PrevDbgScope = NULL;
2646 for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
2647 RE = MIRanges.end(); RI != RE; ++RI) {
2648 const DbgRange &R = *RI;
2649 DbgScope *S = MI2ScopeMap.lookup(R.first);
2650 assert (S && "Lost DbgScope for a machine instruction!");
2651 if (PrevDbgScope && !PrevDbgScope->dominates(S))
2652 PrevDbgScope->closeInsnRange(S);
2653 S->openInsnRange(R.first);
2654 S->extendInsnRange(R.second);
2659 PrevDbgScope->closeInsnRange();
2661 identifyScopeMarkers();
2663 return !DbgScopeMap.empty();
2666 /// identifyScopeMarkers() -
2667 /// Each DbgScope has first instruction and last instruction to mark beginning
2668 /// and end of a scope respectively. Create an inverse map that list scopes
2669 /// starts (and ends) with an instruction. One instruction may start (or end)
2670 /// multiple scopes. Ignore scopes that are not reachable.
2671 void DwarfDebug::identifyScopeMarkers() {
2672 SmallVector<DbgScope *, 4> WorkList;
2673 WorkList.push_back(CurrentFnDbgScope);
2674 while (!WorkList.empty()) {
2675 DbgScope *S = WorkList.pop_back_val();
2677 const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2678 if (!Children.empty())
2679 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2680 SE = Children.end(); SI != SE; ++SI)
2681 WorkList.push_back(*SI);
2683 if (S->isAbstractScope())
2686 const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
2689 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
2690 RE = Ranges.end(); RI != RE; ++RI) {
2691 assert(RI->first && "DbgRange does not have first instruction!");
2692 assert(RI->second && "DbgRange does not have second instruction!");
2693 InsnsEndScopeSet.insert(RI->second);
2698 /// FindFirstDebugLoc - Find the first debug location in the function. This
2699 /// is intended to be an approximation for the source position of the
2700 /// beginning of the function.
2701 static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
2702 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2704 for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
2705 MBBI != MBBE; ++MBBI) {
2706 DebugLoc DL = MBBI->getDebugLoc();
2707 if (!DL.isUnknown())
2714 /// CheckLineNumbers - Count basicblocks whose instructions do not have any
2715 /// line number information.
2716 static void CheckLineNumbers(const MachineFunction *MF) {
2717 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2719 bool FoundLineNo = false;
2720 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2722 const MachineInstr *MI = II;
2723 if (!MI->getDebugLoc().isUnknown()) {
2728 if (!FoundLineNo && I->size())
2729 ++BlocksWithoutLineNo;
2734 /// beginFunction - Gather pre-function debug information. Assumes being
2735 /// emitted immediately after the function entry point.
2736 void DwarfDebug::beginFunction(const MachineFunction *MF) {
2737 if (!MMI->hasDebugInfo()) return;
2738 if (!extractScopeInformation()) return;
2741 CheckLineNumbers(MF);
2744 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
2745 Asm->getFunctionNumber());
2746 // Assumes in correct section after the entry point.
2747 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
2749 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2751 DebugLoc FDL = FindFirstDebugLoc(MF);
2752 if (FDL.isUnknown()) return;
2754 const MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
2755 const MDNode *TheScope = 0;
2757 DISubprogram SP = getDISubprogram(Scope);
2760 Line = SP.getLineNumber();
2764 Line = FDL.getLine();
2769 recordSourceLine(Line, Col, TheScope);
2771 /// ProcessedArgs - Collection of arguments already processed.
2772 SmallPtrSet<const MDNode *, 8> ProcessedArgs;
2775 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2777 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2779 const MachineInstr *MI = II;
2780 DebugLoc DL = MI->getDebugLoc();
2781 if (MI->isDebugValue()) {
2782 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
2783 DIVariable DV(MI->getOperand(MI->getNumOperands() - 1).getMetadata());
2784 if (!DV.Verify()) continue;
2785 // If DBG_VALUE is for a local variable then it needs a label.
2786 if (DV.getTag() != dwarf::DW_TAG_arg_variable
2787 && isDbgValueInUndefinedReg(MI) == false)
2788 InsnNeedsLabel.insert(MI);
2789 // DBG_VALUE for inlined functions argument needs a label.
2790 else if (!DISubprogram(getDISubprogram(DV.getContext())).
2791 describes(MF->getFunction()))
2792 InsnNeedsLabel.insert(MI);
2793 // DBG_VALUE indicating argument location change needs a label.
2794 else if (isDbgValueInUndefinedReg(MI) == false
2795 && !ProcessedArgs.insert(DV))
2796 InsnNeedsLabel.insert(MI);
2798 // If location is unknown then instruction needs a location only if
2799 // UnknownLocations flag is set.
2800 if (DL.isUnknown()) {
2801 if (UnknownLocations && !PrevLoc.isUnknown())
2802 InsnNeedsLabel.insert(MI);
2803 } else if (DL != PrevLoc)
2804 // Otherwise, instruction needs a location only if it is new location.
2805 InsnNeedsLabel.insert(MI);
2808 if (!DL.isUnknown() || UnknownLocations)
2812 PrevLabel = FunctionBeginSym;
2815 /// endFunction - Gather and emit post-function debug information.
2817 void DwarfDebug::endFunction(const MachineFunction *MF) {
2818 if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2820 if (CurrentFnDbgScope) {
2822 // Define end label for subprogram.
2823 FunctionEndSym = Asm->GetTempSymbol("func_end",
2824 Asm->getFunctionNumber());
2825 // Assumes in correct section after the entry point.
2826 Asm->OutStreamer.EmitLabel(FunctionEndSym);
2828 SmallPtrSet<const MDNode *, 16> ProcessedVars;
2829 collectVariableInfo(MF, ProcessedVars);
2831 // Construct abstract scopes.
2832 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2833 AE = AbstractScopesList.end(); AI != AE; ++AI) {
2834 DISubprogram SP((*AI)->getScopeNode());
2836 // Collect info for variables that were optimized out.
2837 StringRef FName = SP.getLinkageName();
2839 FName = SP.getName();
2840 if (NamedMDNode *NMD =
2841 getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
2842 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2843 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2844 if (!DV || !ProcessedVars.insert(DV))
2846 DbgScope *Scope = AbstractScopes.lookup(DV.getContext());
2848 Scope->addVariable(new DbgVariable(DV));
2852 if (ProcessedSPNodes.count((*AI)->getScopeNode()) == 0)
2853 constructScopeDIE(*AI);
2856 DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope);
2858 if (!DisableFramePointerElim(*MF))
2859 addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
2860 dwarf::DW_FORM_flag, 1);
2863 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2864 MMI->getFrameMoves()));
2868 CurrentFnDbgScope = NULL;
2869 InsnNeedsLabel.clear();
2870 DbgVariableToFrameIndexMap.clear();
2871 VarToAbstractVarMap.clear();
2872 DbgVariableToDbgInstMap.clear();
2873 DeleteContainerSeconds(DbgScopeMap);
2874 InsnsEndScopeSet.clear();
2875 ConcreteScopes.clear();
2876 DeleteContainerSeconds(AbstractScopes);
2877 AbstractScopesList.clear();
2878 AbstractVariables.clear();
2879 LabelsBeforeInsn.clear();
2880 LabelsAfterInsn.clear();
2884 /// recordVariableFrameIndex - Record a variable's index.
2885 void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
2886 assert (V && "Invalid DbgVariable!");
2887 DbgVariableToFrameIndexMap[V] = Index;
2890 /// findVariableFrameIndex - Return true if frame index for the variable
2891 /// is found. Update FI to hold value of the index.
2892 bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
2893 assert (V && "Invalid DbgVariable!");
2894 DenseMap<const DbgVariable *, int>::iterator I =
2895 DbgVariableToFrameIndexMap.find(V);
2896 if (I == DbgVariableToFrameIndexMap.end())
2902 /// findDbgScope - Find DbgScope for the debug loc attached with an
2904 DbgScope *DwarfDebug::findDbgScope(const MachineInstr *MInsn) {
2905 DbgScope *Scope = NULL;
2907 MInsn->getParent()->getParent()->getFunction()->getContext();
2908 DebugLoc DL = MInsn->getDebugLoc();
2913 if (const MDNode *IA = DL.getInlinedAt(Ctx))
2914 Scope = ConcreteScopes.lookup(IA);
2916 Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2922 /// recordSourceLine - Register a source line with debug info. Returns the
2923 /// unique label that was emitted and which provides correspondence to
2924 /// the source line list.
2925 MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col,
2931 DIDescriptor Scope(S);
2933 if (Scope.isCompileUnit()) {
2934 DICompileUnit CU(S);
2935 Fn = CU.getFilename();
2936 } else if (Scope.isFile()) {
2938 Fn = F.getFilename();
2939 } else if (Scope.isSubprogram()) {
2941 Fn = SP.getFilename();
2942 } else if (Scope.isLexicalBlock()) {
2943 DILexicalBlock DB(S);
2944 Fn = DB.getFilename();
2946 assert(0 && "Unexpected scope info");
2948 Src = GetOrCreateSourceID(Fn);
2951 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, DWARF2_FLAG_IS_STMT,
2954 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2955 Asm->OutStreamer.EmitLabel(Label);
2959 //===----------------------------------------------------------------------===//
2961 //===----------------------------------------------------------------------===//
2963 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2966 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2967 // Get the children.
2968 const std::vector<DIE *> &Children = Die->getChildren();
2970 // If not last sibling and has children then add sibling offset attribute.
2971 if (!Last && !Children.empty())
2972 Die->addSiblingOffset(DIEValueAllocator);
2974 // Record the abbreviation.
2975 assignAbbrevNumber(Die->getAbbrev());
2977 // Get the abbreviation for this DIE.
2978 unsigned AbbrevNumber = Die->getAbbrevNumber();
2979 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2982 Die->setOffset(Offset);
2984 // Start the size with the size of abbreviation code.
2985 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2987 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2988 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2990 // Size the DIE attribute values.
2991 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2992 // Size attribute value.
2993 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
2995 // Size the DIE children if any.
2996 if (!Children.empty()) {
2997 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2998 "Children flag not set");
3000 for (unsigned j = 0, M = Children.size(); j < M; ++j)
3001 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
3003 // End of children marker.
3004 Offset += sizeof(int8_t);
3007 Die->setSize(Offset - Die->getOffset());
3011 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
3013 void DwarfDebug::computeSizeAndOffsets() {
3014 unsigned PrevOffset = 0;
3015 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3016 E = CUMap.end(); I != E; ++I) {
3017 // Compute size of compile unit header.
3018 static unsigned Offset = PrevOffset +
3019 sizeof(int32_t) + // Length of Compilation Unit Info
3020 sizeof(int16_t) + // DWARF version number
3021 sizeof(int32_t) + // Offset Into Abbrev. Section
3022 sizeof(int8_t); // Pointer Size (in bytes)
3023 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
3024 PrevOffset = Offset;
3028 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
3029 /// temporary label to it if SymbolStem is specified.
3030 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
3031 const char *SymbolStem = 0) {
3032 Asm->OutStreamer.SwitchSection(Section);
3033 if (!SymbolStem) return 0;
3035 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
3036 Asm->OutStreamer.EmitLabel(TmpSym);
3040 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
3041 /// the start of each one.
3042 void DwarfDebug::EmitSectionLabels() {
3043 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
3045 // Dwarf sections base addresses.
3046 if (Asm->MAI->doesDwarfRequireFrameSection()) {
3047 DwarfFrameSectionSym =
3048 EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
3051 DwarfInfoSectionSym =
3052 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
3053 DwarfAbbrevSectionSym =
3054 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
3055 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
3057 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
3058 EmitSectionSym(Asm, MacroInfo);
3060 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
3061 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
3062 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
3063 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
3064 DwarfStrSectionSym =
3065 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
3066 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
3069 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
3070 "section_debug_loc");
3072 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
3073 EmitSectionSym(Asm, TLOF.getDataSection());
3076 /// emitDIE - Recusively Emits a debug information entry.
3078 void DwarfDebug::emitDIE(DIE *Die) {
3079 // Get the abbreviation for this DIE.
3080 unsigned AbbrevNumber = Die->getAbbrevNumber();
3081 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
3083 // Emit the code (index) for the abbreviation.
3084 if (Asm->isVerbose())
3085 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
3086 Twine::utohexstr(Die->getOffset()) + ":0x" +
3087 Twine::utohexstr(Die->getSize()) + " " +
3088 dwarf::TagString(Abbrev->getTag()));
3089 Asm->EmitULEB128(AbbrevNumber);
3091 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
3092 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
3094 // Emit the DIE attribute values.
3095 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3096 unsigned Attr = AbbrevData[i].getAttribute();
3097 unsigned Form = AbbrevData[i].getForm();
3098 assert(Form && "Too many attributes for DIE (check abbreviation)");
3100 if (Asm->isVerbose())
3101 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
3104 case dwarf::DW_AT_sibling:
3105 Asm->EmitInt32(Die->getSiblingOffset());
3107 case dwarf::DW_AT_abstract_origin: {
3108 DIEEntry *E = cast<DIEEntry>(Values[i]);
3109 DIE *Origin = E->getEntry();
3110 unsigned Addr = Origin->getOffset();
3111 Asm->EmitInt32(Addr);
3114 case dwarf::DW_AT_ranges: {
3115 // DW_AT_range Value encodes offset in debug_range section.
3116 DIEInteger *V = cast<DIEInteger>(Values[i]);
3118 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
3119 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
3123 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
3125 DwarfDebugRangeSectionSym,
3130 case dwarf::DW_AT_location: {
3131 if (UseDotDebugLocEntry.count(Die) != 0) {
3132 DIELabel *L = cast<DIELabel>(Values[i]);
3133 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
3135 Values[i]->EmitValue(Asm, Form);
3138 case dwarf::DW_AT_accessibility: {
3139 if (Asm->isVerbose()) {
3140 DIEInteger *V = cast<DIEInteger>(Values[i]);
3141 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
3143 Values[i]->EmitValue(Asm, Form);
3147 // Emit an attribute using the defined form.
3148 Values[i]->EmitValue(Asm, Form);
3153 // Emit the DIE children if any.
3154 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
3155 const std::vector<DIE *> &Children = Die->getChildren();
3157 for (unsigned j = 0, M = Children.size(); j < M; ++j)
3158 emitDIE(Children[j]);
3160 if (Asm->isVerbose())
3161 Asm->OutStreamer.AddComment("End Of Children Mark");
3166 /// emitDebugInfo - Emit the debug info section.
3168 void DwarfDebug::emitDebugInfo() {
3169 // Start debug info section.
3170 Asm->OutStreamer.SwitchSection(
3171 Asm->getObjFileLowering().getDwarfInfoSection());
3172 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3173 E = CUMap.end(); I != E; ++I) {
3174 CompileUnit *TheCU = I->second;
3175 DIE *Die = TheCU->getCUDie();
3177 // Emit the compile units header.
3178 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
3181 // Emit size of content not including length itself
3182 unsigned ContentSize = Die->getSize() +
3183 sizeof(int16_t) + // DWARF version number
3184 sizeof(int32_t) + // Offset Into Abbrev. Section
3185 sizeof(int8_t) + // Pointer Size (in bytes)
3186 sizeof(int32_t); // FIXME - extra pad for gdb bug.
3188 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
3189 Asm->EmitInt32(ContentSize);
3190 Asm->OutStreamer.AddComment("DWARF version number");
3191 Asm->EmitInt16(dwarf::DWARF_VERSION);
3192 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
3193 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
3194 DwarfAbbrevSectionSym);
3195 Asm->OutStreamer.AddComment("Address Size (in bytes)");
3196 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3199 // FIXME - extra padding for gdb bug.
3200 Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
3205 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
3209 /// emitAbbreviations - Emit the abbreviation section.
3211 void DwarfDebug::emitAbbreviations() const {
3212 // Check to see if it is worth the effort.
3213 if (!Abbreviations.empty()) {
3214 // Start the debug abbrev section.
3215 Asm->OutStreamer.SwitchSection(
3216 Asm->getObjFileLowering().getDwarfAbbrevSection());
3218 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
3220 // For each abbrevation.
3221 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
3222 // Get abbreviation data
3223 const DIEAbbrev *Abbrev = Abbreviations[i];
3225 // Emit the abbrevations code (base 1 index.)
3226 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
3228 // Emit the abbreviations data.
3232 // Mark end of abbreviations.
3233 Asm->EmitULEB128(0, "EOM(3)");
3235 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
3239 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
3240 /// the line matrix.
3242 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
3243 // Define last address of section.
3244 Asm->OutStreamer.AddComment("Extended Op");
3247 Asm->OutStreamer.AddComment("Op size");
3248 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
3249 Asm->OutStreamer.AddComment("DW_LNE_set_address");
3250 Asm->EmitInt8(dwarf::DW_LNE_set_address);
3252 Asm->OutStreamer.AddComment("Section end label");
3254 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
3255 Asm->getTargetData().getPointerSize(),
3258 // Mark end of matrix.
3259 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
3265 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
3267 void DwarfDebug::emitCommonDebugFrame() {
3268 if (!Asm->MAI->doesDwarfRequireFrameSection())
3271 int stackGrowth = Asm->getTargetData().getPointerSize();
3272 if (Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3273 TargetFrameInfo::StackGrowsDown)
3276 // Start the dwarf frame section.
3277 Asm->OutStreamer.SwitchSection(
3278 Asm->getObjFileLowering().getDwarfFrameSection());
3280 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
3281 Asm->OutStreamer.AddComment("Length of Common Information Entry");
3282 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
3283 Asm->GetTempSymbol("debug_frame_common_begin"), 4);
3285 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
3286 Asm->OutStreamer.AddComment("CIE Identifier Tag");
3287 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
3288 Asm->OutStreamer.AddComment("CIE Version");
3289 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
3290 Asm->OutStreamer.AddComment("CIE Augmentation");
3291 Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
3292 Asm->EmitULEB128(1, "CIE Code Alignment Factor");
3293 Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
3294 Asm->OutStreamer.AddComment("CIE RA Column");
3295 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3296 const TargetFrameInfo *TFI = Asm->TM.getFrameInfo();
3297 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3299 std::vector<MachineMove> Moves;
3300 TFI->getInitialFrameState(Moves);
3302 Asm->EmitFrameMoves(Moves, 0, false);
3304 Asm->EmitAlignment(2);
3305 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
3308 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
3311 emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3312 if (!Asm->MAI->doesDwarfRequireFrameSection())
3315 // Start the dwarf frame section.
3316 Asm->OutStreamer.SwitchSection(
3317 Asm->getObjFileLowering().getDwarfFrameSection());
3319 Asm->OutStreamer.AddComment("Length of Frame Information Entry");
3320 MCSymbol *DebugFrameBegin =
3321 Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
3322 MCSymbol *DebugFrameEnd =
3323 Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
3324 Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
3326 Asm->OutStreamer.EmitLabel(DebugFrameBegin);
3328 Asm->OutStreamer.AddComment("FDE CIE offset");
3329 Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
3330 DwarfFrameSectionSym);
3332 Asm->OutStreamer.AddComment("FDE initial location");
3333 MCSymbol *FuncBeginSym =
3334 Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
3335 Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
3336 Asm->getTargetData().getPointerSize(),
3340 Asm->OutStreamer.AddComment("FDE address range");
3341 Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
3342 FuncBeginSym, Asm->getTargetData().getPointerSize());
3344 Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
3346 Asm->EmitAlignment(2);
3347 Asm->OutStreamer.EmitLabel(DebugFrameEnd);
3350 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
3352 void DwarfDebug::emitDebugPubNames() {
3353 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3354 E = CUMap.end(); I != E; ++I) {
3355 CompileUnit *TheCU = I->second;
3356 // Start the dwarf pubnames section.
3357 Asm->OutStreamer.SwitchSection(
3358 Asm->getObjFileLowering().getDwarfPubNamesSection());
3360 Asm->OutStreamer.AddComment("Length of Public Names Info");
3361 Asm->EmitLabelDifference(
3362 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
3363 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
3365 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
3368 Asm->OutStreamer.AddComment("DWARF Version");
3369 Asm->EmitInt16(dwarf::DWARF_VERSION);
3371 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3372 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
3373 DwarfInfoSectionSym);
3375 Asm->OutStreamer.AddComment("Compilation Unit Length");
3376 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
3377 Asm->GetTempSymbol("info_begin", TheCU->getID()),
3380 const StringMap<DIE*> &Globals = TheCU->getGlobals();
3381 for (StringMap<DIE*>::const_iterator
3382 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3383 const char *Name = GI->getKeyData();
3384 DIE *Entity = GI->second;
3386 Asm->OutStreamer.AddComment("DIE offset");
3387 Asm->EmitInt32(Entity->getOffset());
3389 if (Asm->isVerbose())
3390 Asm->OutStreamer.AddComment("External Name");
3391 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
3394 Asm->OutStreamer.AddComment("End Mark");
3396 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
3401 void DwarfDebug::emitDebugPubTypes() {
3402 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3403 E = CUMap.end(); I != E; ++I) {
3404 CompileUnit *TheCU = I->second;
3405 // Start the dwarf pubnames section.
3406 Asm->OutStreamer.SwitchSection(
3407 Asm->getObjFileLowering().getDwarfPubTypesSection());
3408 Asm->OutStreamer.AddComment("Length of Public Types Info");
3409 Asm->EmitLabelDifference(
3410 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
3411 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
3413 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
3416 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
3417 Asm->EmitInt16(dwarf::DWARF_VERSION);
3419 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3420 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
3421 DwarfInfoSectionSym);
3423 Asm->OutStreamer.AddComment("Compilation Unit Length");
3424 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
3425 Asm->GetTempSymbol("info_begin", TheCU->getID()),
3428 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
3429 for (StringMap<DIE*>::const_iterator
3430 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3431 const char *Name = GI->getKeyData();
3432 DIE * Entity = GI->second;
3434 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3435 Asm->EmitInt32(Entity->getOffset());
3437 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
3438 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
3441 Asm->OutStreamer.AddComment("End Mark");
3443 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
3448 /// emitDebugStr - Emit visible names into a debug str section.
3450 void DwarfDebug::emitDebugStr() {
3451 // Check to see if it is worth the effort.
3452 if (StringPool.empty()) return;
3454 // Start the dwarf str section.
3455 Asm->OutStreamer.SwitchSection(
3456 Asm->getObjFileLowering().getDwarfStrSection());
3458 // Get all of the string pool entries and put them in an array by their ID so
3459 // we can sort them.
3460 SmallVector<std::pair<unsigned,
3461 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
3463 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
3464 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
3465 Entries.push_back(std::make_pair(I->second.second, &*I));
3467 array_pod_sort(Entries.begin(), Entries.end());
3469 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
3470 // Emit a label for reference from debug information entries.
3471 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
3473 // Emit the string itself.
3474 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
3478 /// emitDebugLoc - Emit visible names into a debug loc section.
3480 void DwarfDebug::emitDebugLoc() {
3481 if (DotDebugLocEntries.empty())
3484 // Start the dwarf loc section.
3485 Asm->OutStreamer.SwitchSection(
3486 Asm->getObjFileLowering().getDwarfLocSection());
3487 unsigned char Size = Asm->getTargetData().getPointerSize();
3488 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
3490 for (SmallVector<DotDebugLocEntry, 4>::iterator
3491 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
3492 I != E; ++I, ++index) {
3493 DotDebugLocEntry Entry = *I;
3494 if (Entry.isEmpty()) {
3495 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3496 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3497 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
3499 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
3500 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
3501 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3502 unsigned Reg = RI->getDwarfRegNum(Entry.Loc.getReg(), false);
3503 if (int Offset = Entry.Loc.getOffset()) {
3504 // If the value is at a certain offset from frame register then
3506 unsigned OffsetSize = Offset ? MCAsmInfo::getSLEB128Size(Offset) : 1;
3507 Asm->OutStreamer.AddComment("Loc expr size");
3508 Asm->EmitInt16(1 + OffsetSize);
3509 Asm->OutStreamer.AddComment(
3510 dwarf::OperationEncodingString(dwarf::DW_OP_fbreg));
3511 Asm->EmitInt8(dwarf::DW_OP_fbreg);
3512 Asm->OutStreamer.AddComment("Offset");
3513 Asm->EmitSLEB128(Offset);
3516 Asm->OutStreamer.AddComment("Loc expr size");
3518 Asm->OutStreamer.AddComment(
3519 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
3520 Asm->EmitInt8(dwarf::DW_OP_reg0 + Reg);
3522 Asm->OutStreamer.AddComment("Loc expr size");
3523 Asm->EmitInt16(1 + MCAsmInfo::getULEB128Size(Reg));
3524 Asm->EmitInt8(dwarf::DW_OP_regx);
3525 Asm->EmitULEB128(Reg);
3532 /// EmitDebugARanges - Emit visible names into a debug aranges section.
3534 void DwarfDebug::EmitDebugARanges() {
3535 // Start the dwarf aranges section.
3536 Asm->OutStreamer.SwitchSection(
3537 Asm->getObjFileLowering().getDwarfARangesSection());
3540 /// emitDebugRanges - Emit visible names into a debug ranges section.
3542 void DwarfDebug::emitDebugRanges() {
3543 // Start the dwarf ranges section.
3544 Asm->OutStreamer.SwitchSection(
3545 Asm->getObjFileLowering().getDwarfRangesSection());
3546 unsigned char Size = Asm->getTargetData().getPointerSize();
3547 for (SmallVector<const MCSymbol *, 8>::iterator
3548 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
3551 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
3553 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3557 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
3559 void DwarfDebug::emitDebugMacInfo() {
3560 if (const MCSection *LineInfo =
3561 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
3562 // Start the dwarf macinfo section.
3563 Asm->OutStreamer.SwitchSection(LineInfo);
3567 /// emitDebugInlineInfo - Emit inline info using following format.
3569 /// 1. length of section
3570 /// 2. Dwarf version number
3571 /// 3. address size.
3573 /// Entries (one "entry" for each function that was inlined):
3575 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
3576 /// otherwise offset into __debug_str for regular function name.
3577 /// 2. offset into __debug_str section for regular function name.
3578 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
3579 /// instances for the function.
3581 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
3582 /// inlined instance; the die_offset points to the inlined_subroutine die in the
3583 /// __debug_info section, and the low_pc is the starting address for the
3584 /// inlining instance.
3585 void DwarfDebug::emitDebugInlineInfo() {
3586 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
3592 Asm->OutStreamer.SwitchSection(
3593 Asm->getObjFileLowering().getDwarfDebugInlineSection());
3595 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
3596 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
3597 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
3599 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
3601 Asm->OutStreamer.AddComment("Dwarf Version");
3602 Asm->EmitInt16(dwarf::DWARF_VERSION);
3603 Asm->OutStreamer.AddComment("Address Size (in bytes)");
3604 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3606 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3607 E = InlinedSPNodes.end(); I != E; ++I) {
3609 const MDNode *Node = *I;
3610 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3611 = InlineInfo.find(Node);
3612 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3613 DISubprogram SP(Node);
3614 StringRef LName = SP.getLinkageName();
3615 StringRef Name = SP.getName();
3617 Asm->OutStreamer.AddComment("MIPS linkage name");
3618 if (LName.empty()) {
3619 Asm->OutStreamer.EmitBytes(Name, 0);
3620 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
3622 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
3623 DwarfStrSectionSym);
3625 Asm->OutStreamer.AddComment("Function name");
3626 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
3627 Asm->EmitULEB128(Labels.size(), "Inline count");
3629 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3630 LE = Labels.end(); LI != LE; ++LI) {
3631 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3632 Asm->EmitInt32(LI->second->getOffset());
3634 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
3635 Asm->OutStreamer.EmitSymbolValue(LI->first,
3636 Asm->getTargetData().getPointerSize(),0);
3640 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));