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().getDirectory(),
518 V.getContext().getFilename());
519 assert(FileID && "Invalid file id");
520 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
521 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
524 /// addSourceLine - Add location information to specified debug information
526 void DwarfDebug::addSourceLine(DIE *Die, DIGlobalVariable G) {
527 // Verify global variable.
531 unsigned Line = G.getLineNumber();
534 unsigned FileID = GetOrCreateSourceID(G.getContext().getDirectory(),
535 G.getContext().getFilename());
536 assert(FileID && "Invalid file id");
537 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
538 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
541 /// addSourceLine - Add location information to specified debug information
543 void DwarfDebug::addSourceLine(DIE *Die, DISubprogram SP) {
544 // Verify subprogram.
547 // If the line number is 0, don't add it.
548 if (SP.getLineNumber() == 0)
551 unsigned Line = SP.getLineNumber();
552 if (!SP.getContext().Verify())
554 unsigned FileID = GetOrCreateSourceID(SP.getDirectory(),
556 assert(FileID && "Invalid file id");
557 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
558 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
561 /// addSourceLine - Add location information to specified debug information
563 void DwarfDebug::addSourceLine(DIE *Die, DIType Ty) {
568 unsigned Line = Ty.getLineNumber();
569 if (Line == 0 || !Ty.getContext().Verify())
571 unsigned FileID = GetOrCreateSourceID(Ty.getDirectory(),
573 assert(FileID && "Invalid file id");
574 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
575 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
578 /// addSourceLine - Add location information to specified debug information
580 void DwarfDebug::addSourceLine(DIE *Die, DINameSpace NS) {
585 unsigned Line = NS.getLineNumber();
588 StringRef FN = NS.getFilename();
589 StringRef Dir = NS.getDirectory();
591 unsigned FileID = GetOrCreateSourceID(Dir, FN);
592 assert(FileID && "Invalid file id");
593 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
594 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
597 /// addVariableAddress - Add DW_AT_location attribute for a DbgVariable based
598 /// on provided frame index.
599 void DwarfDebug::addVariableAddress(DbgVariable *&DV, DIE *Die, int64_t FI) {
600 MachineLocation Location;
602 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
603 int Offset = RI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
604 Location.set(FrameReg, Offset);
606 if (DV->variableHasComplexAddress())
607 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
608 else if (DV->isBlockByrefVariable())
609 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
611 addAddress(Die, dwarf::DW_AT_location, Location);
614 /// addComplexAddress - Start with the address based on the location provided,
615 /// and generate the DWARF information necessary to find the actual variable
616 /// given the extra address information encoded in the DIVariable, starting from
617 /// the starting location. Add the DWARF information to the die.
619 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
621 const MachineLocation &Location) {
622 DIType Ty = DV->getType();
624 // Decode the original location, and use that as the start of the byref
625 // variable's location.
626 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
627 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
628 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
630 if (Location.isReg()) {
632 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
634 Reg = Reg - dwarf::DW_OP_reg0;
635 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
636 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
640 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
642 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
643 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
646 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
649 for (unsigned i = 0, N = DV->getNumAddrElements(); i < N; ++i) {
650 uint64_t Element = DV->getAddrElement(i);
652 if (Element == DIFactory::OpPlus) {
653 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
654 addUInt(Block, 0, dwarf::DW_FORM_udata, DV->getAddrElement(++i));
655 } else if (Element == DIFactory::OpDeref) {
656 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
657 } else llvm_unreachable("unknown DIFactory Opcode");
660 // Now attach the location information to the DIE.
661 addBlock(Die, Attribute, 0, Block);
664 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
665 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
666 gives the variable VarName either the struct, or a pointer to the struct, as
667 its type. This is necessary for various behind-the-scenes things the
668 compiler needs to do with by-reference variables in Blocks.
670 However, as far as the original *programmer* is concerned, the variable
671 should still have type 'SomeType', as originally declared.
673 The function getBlockByrefType dives into the __Block_byref_x_VarName
674 struct to find the original type of the variable, which is then assigned to
675 the variable's Debug Information Entry as its real type. So far, so good.
676 However now the debugger will expect the variable VarName to have the type
677 SomeType. So we need the location attribute for the variable to be an
678 expression that explains to the debugger how to navigate through the
679 pointers and struct to find the actual variable of type SomeType.
681 The following function does just that. We start by getting
682 the "normal" location for the variable. This will be the location
683 of either the struct __Block_byref_x_VarName or the pointer to the
684 struct __Block_byref_x_VarName.
686 The struct will look something like:
688 struct __Block_byref_x_VarName {
690 struct __Block_byref_x_VarName *forwarding;
691 ... <various other fields>
693 ... <maybe more fields>
696 If we are given the struct directly (as our starting point) we
697 need to tell the debugger to:
699 1). Add the offset of the forwarding field.
701 2). Follow that pointer to get the real __Block_byref_x_VarName
702 struct to use (the real one may have been copied onto the heap).
704 3). Add the offset for the field VarName, to find the actual variable.
706 If we started with a pointer to the struct, then we need to
707 dereference that pointer first, before the other steps.
708 Translating this into DWARF ops, we will need to append the following
709 to the current location description for the variable:
711 DW_OP_deref -- optional, if we start with a pointer
712 DW_OP_plus_uconst <forward_fld_offset>
714 DW_OP_plus_uconst <varName_fld_offset>
716 That is what this function does. */
718 /// addBlockByrefAddress - Start with the address based on the location
719 /// provided, and generate the DWARF information necessary to find the
720 /// actual Block variable (navigating the Block struct) based on the
721 /// starting location. Add the DWARF information to the die. For
722 /// more information, read large comment just above here.
724 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
726 const MachineLocation &Location) {
727 DIType Ty = DV->getType();
729 unsigned Tag = Ty.getTag();
730 bool isPointer = false;
732 StringRef varName = DV->getName();
734 if (Tag == dwarf::DW_TAG_pointer_type) {
735 DIDerivedType DTy = DIDerivedType(Ty);
736 TmpTy = DTy.getTypeDerivedFrom();
740 DICompositeType blockStruct = DICompositeType(TmpTy);
742 // Find the __forwarding field and the variable field in the __Block_byref
744 DIArray Fields = blockStruct.getTypeArray();
745 DIDescriptor varField = DIDescriptor();
746 DIDescriptor forwardingField = DIDescriptor();
748 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
749 DIDescriptor Element = Fields.getElement(i);
750 DIDerivedType DT = DIDerivedType(Element);
751 StringRef fieldName = DT.getName();
752 if (fieldName == "__forwarding")
753 forwardingField = Element;
754 else if (fieldName == varName)
758 // Get the offsets for the forwarding field and the variable field.
759 unsigned forwardingFieldOffset =
760 DIDerivedType(forwardingField).getOffsetInBits() >> 3;
761 unsigned varFieldOffset =
762 DIDerivedType(varField).getOffsetInBits() >> 3;
764 // Decode the original location, and use that as the start of the byref
765 // variable's location.
766 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
767 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
768 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
770 if (Location.isReg()) {
772 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
774 Reg = Reg - dwarf::DW_OP_reg0;
775 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
776 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
780 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
782 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
783 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
786 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
789 // If we started with a pointer to the __Block_byref... struct, then
790 // the first thing we need to do is dereference the pointer (DW_OP_deref).
792 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
794 // Next add the offset for the '__forwarding' field:
795 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
796 // adding the offset if it's 0.
797 if (forwardingFieldOffset > 0) {
798 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
799 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
802 // Now dereference the __forwarding field to get to the real __Block_byref
803 // struct: DW_OP_deref.
804 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
806 // Now that we've got the real __Block_byref... struct, add the offset
807 // for the variable's field to get to the location of the actual variable:
808 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
809 if (varFieldOffset > 0) {
810 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
811 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
814 // Now attach the location information to the DIE.
815 addBlock(Die, Attribute, 0, Block);
818 /// addAddress - Add an address attribute to a die based on the location
820 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
821 const MachineLocation &Location) {
822 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
823 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
824 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
826 if (RI->getFrameRegister(*Asm->MF) == Location.getReg()
827 && Location.getOffset()) {
828 // If variable offset is based in frame register then use fbreg.
829 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
830 addSInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
831 addBlock(Die, Attribute, 0, Block);
835 if (Location.isReg()) {
837 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
839 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
840 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
844 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
846 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
847 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
850 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
853 addBlock(Die, Attribute, 0, Block);
856 /// addRegisterAddress - Add register location entry in variable DIE.
857 bool DwarfDebug::addRegisterAddress(DIE *Die, const MCSymbol *VS,
858 const MachineOperand &MO) {
859 assert (MO.isReg() && "Invalid machine operand!");
862 MachineLocation Location;
863 Location.set(MO.getReg());
864 addAddress(Die, dwarf::DW_AT_location, Location);
866 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
870 /// addConstantValue - Add constant value entry in variable DIE.
871 bool DwarfDebug::addConstantValue(DIE *Die, const MCSymbol *VS,
872 const MachineOperand &MO) {
873 assert (MO.isImm() && "Invalid machine operand!");
874 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
875 unsigned Imm = MO.getImm();
876 addUInt(Block, 0, dwarf::DW_FORM_udata, Imm);
877 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
879 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
883 /// addConstantFPValue - Add constant value entry in variable DIE.
884 bool DwarfDebug::addConstantFPValue(DIE *Die, const MCSymbol *VS,
885 const MachineOperand &MO) {
886 assert (MO.isFPImm() && "Invalid machine operand!");
887 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
888 APFloat FPImm = MO.getFPImm()->getValueAPF();
890 // Get the raw data form of the floating point.
891 const APInt FltVal = FPImm.bitcastToAPInt();
892 const char *FltPtr = (const char*)FltVal.getRawData();
894 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
895 bool LittleEndian = Asm->getTargetData().isLittleEndian();
896 int Incr = (LittleEndian ? 1 : -1);
897 int Start = (LittleEndian ? 0 : NumBytes - 1);
898 int Stop = (LittleEndian ? NumBytes : -1);
900 // Output the constant to DWARF one byte at a time.
901 for (; Start != Stop; Start += Incr)
902 addUInt(Block, 0, dwarf::DW_FORM_data1,
903 (unsigned char)0xFF & FltPtr[Start]);
905 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
907 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
912 /// addToContextOwner - Add Die into the list of its context owner's children.
913 void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
914 if (Context.isType()) {
915 DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context));
916 ContextDIE->addChild(Die);
917 } else if (Context.isNameSpace()) {
918 DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context));
919 ContextDIE->addChild(Die);
920 } else if (Context.isSubprogram()) {
921 DIE *ContextDIE = createSubprogramDIE(DISubprogram(Context));
922 ContextDIE->addChild(Die);
923 } else if (DIE *ContextDIE = getCompileUnit(Context)->getDIE(Context))
924 ContextDIE->addChild(Die);
926 getCompileUnit(Context)->addDie(Die);
929 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
931 DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
932 CompileUnit *TypeCU = getCompileUnit(Ty);
933 DIE *TyDIE = TypeCU->getDIE(Ty);
938 TyDIE = new DIE(dwarf::DW_TAG_base_type);
939 TypeCU->insertDIE(Ty, TyDIE);
940 if (Ty.isBasicType())
941 constructTypeDIE(*TyDIE, DIBasicType(Ty));
942 else if (Ty.isCompositeType())
943 constructTypeDIE(*TyDIE, DICompositeType(Ty));
945 assert(Ty.isDerivedType() && "Unknown kind of DIType");
946 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
949 addToContextOwner(TyDIE, Ty.getContext());
953 /// addType - Add a new type attribute to the specified entity.
954 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
958 // Check for pre-existence.
959 CompileUnit *TypeCU = getCompileUnit(Ty);
960 DIEEntry *Entry = TypeCU->getDIEEntry(Ty);
961 // If it exists then use the existing value.
963 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
968 DIE *Buffer = getOrCreateTypeDIE(Ty);
971 Entry = createDIEEntry(Buffer);
972 TypeCU->insertDIEEntry(Ty, Entry);
974 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
977 /// constructTypeDIE - Construct basic type die from DIBasicType.
978 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
979 // Get core information.
980 StringRef Name = BTy.getName();
981 Buffer.setTag(dwarf::DW_TAG_base_type);
982 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
985 // Add name if not anonymous or intermediate type.
987 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
988 uint64_t Size = BTy.getSizeInBits() >> 3;
989 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
992 /// constructTypeDIE - Construct derived type die from DIDerivedType.
993 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
994 // Get core information.
995 StringRef Name = DTy.getName();
996 uint64_t Size = DTy.getSizeInBits() >> 3;
997 unsigned Tag = DTy.getTag();
999 // FIXME - Workaround for templates.
1000 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
1004 // Map to main type, void will not have a type.
1005 DIType FromTy = DTy.getTypeDerivedFrom();
1006 addType(&Buffer, FromTy);
1008 // Add name if not anonymous or intermediate type.
1010 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1012 // Add size if non-zero (derived types might be zero-sized.)
1014 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1016 // Add source line info if available and TyDesc is not a forward declaration.
1017 if (!DTy.isForwardDecl())
1018 addSourceLine(&Buffer, DTy);
1021 /// constructTypeDIE - Construct type DIE from DICompositeType.
1022 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1023 // Get core information.
1024 StringRef Name = CTy.getName();
1026 uint64_t Size = CTy.getSizeInBits() >> 3;
1027 unsigned Tag = CTy.getTag();
1031 case dwarf::DW_TAG_vector_type:
1032 case dwarf::DW_TAG_array_type:
1033 constructArrayTypeDIE(Buffer, &CTy);
1035 case dwarf::DW_TAG_enumeration_type: {
1036 DIArray Elements = CTy.getTypeArray();
1038 // Add enumerators to enumeration type.
1039 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1040 DIE *ElemDie = NULL;
1041 DIDescriptor Enum(Elements.getElement(i));
1042 if (Enum.isEnumerator()) {
1043 ElemDie = constructEnumTypeDIE(DIEnumerator(Enum));
1044 Buffer.addChild(ElemDie);
1049 case dwarf::DW_TAG_subroutine_type: {
1051 DIArray Elements = CTy.getTypeArray();
1052 DIDescriptor RTy = Elements.getElement(0);
1053 addType(&Buffer, DIType(RTy));
1055 bool isPrototyped = true;
1057 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1058 DIDescriptor Ty = Elements.getElement(i);
1059 if (Ty.isUnspecifiedParameter()) {
1060 DIE *Arg = new DIE(dwarf::DW_TAG_unspecified_parameters);
1061 Buffer.addChild(Arg);
1062 isPrototyped = false;
1064 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1065 addType(Arg, DIType(Ty));
1066 Buffer.addChild(Arg);
1069 // Add prototype flag.
1071 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1074 case dwarf::DW_TAG_structure_type:
1075 case dwarf::DW_TAG_union_type:
1076 case dwarf::DW_TAG_class_type: {
1077 // Add elements to structure type.
1078 DIArray Elements = CTy.getTypeArray();
1080 // A forward struct declared type may not have elements available.
1081 unsigned N = Elements.getNumElements();
1085 // Add elements to structure type.
1086 for (unsigned i = 0; i < N; ++i) {
1087 DIDescriptor Element = Elements.getElement(i);
1088 DIE *ElemDie = NULL;
1089 if (Element.isSubprogram()) {
1090 DISubprogram SP(Element);
1091 ElemDie = createSubprogramDIE(DISubprogram(Element));
1092 if (SP.isProtected())
1093 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1094 dwarf::DW_ACCESS_protected);
1095 else if (SP.isPrivate())
1096 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1097 dwarf::DW_ACCESS_private);
1099 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1100 dwarf::DW_ACCESS_public);
1101 if (SP.isExplicit())
1102 addUInt(ElemDie, dwarf::DW_AT_explicit, dwarf::DW_FORM_flag, 1);
1104 else if (Element.isVariable()) {
1105 DIVariable DV(Element);
1106 ElemDie = new DIE(dwarf::DW_TAG_variable);
1107 addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1109 addType(ElemDie, DV.getType());
1110 addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1111 addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1112 addSourceLine(ElemDie, DV);
1113 } else if (Element.isDerivedType())
1114 ElemDie = createMemberDIE(DIDerivedType(Element));
1117 Buffer.addChild(ElemDie);
1120 if (CTy.isAppleBlockExtension())
1121 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1123 unsigned RLang = CTy.getRunTimeLang();
1125 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1126 dwarf::DW_FORM_data1, RLang);
1128 DICompositeType ContainingType = CTy.getContainingType();
1129 if (DIDescriptor(ContainingType).isCompositeType())
1130 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1131 getOrCreateTypeDIE(DIType(ContainingType)));
1133 DIDescriptor Context = CTy.getContext();
1134 addToContextOwner(&Buffer, Context);
1142 // Add name if not anonymous or intermediate type.
1144 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1146 if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type
1147 || Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1149 // Add size if non-zero (derived types might be zero-sized.)
1151 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1153 // Add zero size if it is not a forward declaration.
1154 if (CTy.isForwardDecl())
1155 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1157 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1160 // Add source line info if available.
1161 if (!CTy.isForwardDecl())
1162 addSourceLine(&Buffer, CTy);
1166 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1167 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1168 int64_t L = SR.getLo();
1169 int64_t H = SR.getHi();
1170 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1172 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1174 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1175 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1177 Buffer.addChild(DW_Subrange);
1180 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1181 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1182 DICompositeType *CTy) {
1183 Buffer.setTag(dwarf::DW_TAG_array_type);
1184 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1185 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1187 // Emit derived type.
1188 addType(&Buffer, CTy->getTypeDerivedFrom());
1189 DIArray Elements = CTy->getTypeArray();
1191 // Get an anonymous type for index type.
1192 CompileUnit *TheCU = getCompileUnit(*CTy);
1193 DIE *IdxTy = TheCU->getIndexTyDie();
1195 // Construct an anonymous type for index type.
1196 IdxTy = new DIE(dwarf::DW_TAG_base_type);
1197 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1198 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1199 dwarf::DW_ATE_signed);
1200 TheCU->addDie(IdxTy);
1201 TheCU->setIndexTyDie(IdxTy);
1204 // Add subranges to array type.
1205 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1206 DIDescriptor Element = Elements.getElement(i);
1207 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1208 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1212 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1213 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1214 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1215 StringRef Name = ETy.getName();
1216 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1217 int64_t Value = ETy.getEnumValue();
1218 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1222 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1223 /// printer to not emit usual symbol prefix before the symbol name is used then
1224 /// return linkage name after skipping this special LLVM prefix.
1225 static StringRef getRealLinkageName(StringRef LinkageName) {
1227 if (LinkageName.startswith(StringRef(&One, 1)))
1228 return LinkageName.substr(1);
1232 /// createMemberDIE - Create new member DIE.
1233 DIE *DwarfDebug::createMemberDIE(DIDerivedType DT) {
1234 DIE *MemberDie = new DIE(DT.getTag());
1235 StringRef Name = DT.getName();
1237 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1239 addType(MemberDie, DT.getTypeDerivedFrom());
1241 addSourceLine(MemberDie, DT);
1243 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1244 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1246 uint64_t Size = DT.getSizeInBits();
1247 uint64_t FieldSize = DT.getOriginalTypeSize();
1249 if (Size != FieldSize) {
1251 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1252 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1254 uint64_t Offset = DT.getOffsetInBits();
1255 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1256 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1257 uint64_t FieldOffset = (HiMark - FieldSize);
1258 Offset -= FieldOffset;
1260 // Maybe we need to work from the other end.
1261 if (Asm->getTargetData().isLittleEndian())
1262 Offset = FieldSize - (Offset + Size);
1263 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1265 // Here WD_AT_data_member_location points to the anonymous
1266 // field that includes this bit field.
1267 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1270 // This is not a bitfield.
1271 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1273 if (DT.getTag() == dwarf::DW_TAG_inheritance
1274 && DT.isVirtual()) {
1276 // For C++, virtual base classes are not at fixed offset. Use following
1277 // expression to extract appropriate offset from vtable.
1278 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1280 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1281 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1282 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1283 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1284 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1285 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1286 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1287 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1289 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1292 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1294 if (DT.isProtected())
1295 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1296 dwarf::DW_ACCESS_protected);
1297 else if (DT.isPrivate())
1298 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1299 dwarf::DW_ACCESS_private);
1300 // Otherwise C++ member and base classes are considered public.
1301 else if (DT.getCompileUnit().getLanguage() == dwarf::DW_LANG_C_plus_plus)
1302 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1303 dwarf::DW_ACCESS_public);
1305 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1306 dwarf::DW_VIRTUALITY_virtual);
1310 /// createSubprogramDIE - Create new DIE using SP.
1311 DIE *DwarfDebug::createSubprogramDIE(DISubprogram SP) {
1312 CompileUnit *SPCU = getCompileUnit(SP);
1313 DIE *SPDie = SPCU->getDIE(SP);
1317 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1318 // Constructors and operators for anonymous aggregates do not have names.
1319 if (!SP.getName().empty())
1320 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1322 StringRef LinkageName = SP.getLinkageName();
1323 if (!LinkageName.empty())
1324 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1325 getRealLinkageName(LinkageName));
1327 addSourceLine(SPDie, SP);
1329 if (SP.isPrototyped())
1330 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1333 DICompositeType SPTy = SP.getType();
1334 DIArray Args = SPTy.getTypeArray();
1335 unsigned SPTag = SPTy.getTag();
1337 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1338 addType(SPDie, SPTy);
1340 addType(SPDie, DIType(Args.getElement(0)));
1342 unsigned VK = SP.getVirtuality();
1344 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1345 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1346 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1347 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1348 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1349 ContainingTypeMap.insert(std::make_pair(SPDie,
1350 SP.getContainingType()));
1353 if (!SP.isDefinition()) {
1354 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1356 // Add arguments. Do not add arguments for subprogram definition. They will
1357 // be handled while processing variables.
1358 DICompositeType SPTy = SP.getType();
1359 DIArray Args = SPTy.getTypeArray();
1360 unsigned SPTag = SPTy.getTag();
1362 if (SPTag == dwarf::DW_TAG_subroutine_type)
1363 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1364 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1365 DIType ATy = DIType(DIType(Args.getElement(i)));
1367 if (ATy.isArtificial())
1368 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1369 SPDie->addChild(Arg);
1373 if (SP.isArtificial())
1374 addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1376 if (!SP.isLocalToUnit())
1377 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1379 if (SP.isOptimized())
1380 addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1382 if (unsigned isa = Asm->getISAEncoding()) {
1383 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1386 // DW_TAG_inlined_subroutine may refer to this DIE.
1387 SPCU->insertDIE(SP, SPDie);
1389 // Add to context owner.
1390 addToContextOwner(SPDie, SP.getContext());
1395 DbgScope *DwarfDebug::getOrCreateAbstractScope(const MDNode *N) {
1396 assert(N && "Invalid Scope encoding!");
1398 DbgScope *AScope = AbstractScopes.lookup(N);
1402 DbgScope *Parent = NULL;
1404 DIDescriptor Scope(N);
1405 if (Scope.isLexicalBlock()) {
1406 DILexicalBlock DB(N);
1407 DIDescriptor ParentDesc = DB.getContext();
1408 Parent = getOrCreateAbstractScope(ParentDesc);
1411 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1414 Parent->addScope(AScope);
1415 AScope->setAbstractScope();
1416 AbstractScopes[N] = AScope;
1417 if (DIDescriptor(N).isSubprogram())
1418 AbstractScopesList.push_back(AScope);
1422 /// isSubprogramContext - Return true if Context is either a subprogram
1423 /// or another context nested inside a subprogram.
1424 static bool isSubprogramContext(const MDNode *Context) {
1427 DIDescriptor D(Context);
1428 if (D.isSubprogram())
1431 return isSubprogramContext(DIType(Context).getContext());
1435 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1436 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1437 /// If there are global variables in this scope then create and insert
1438 /// DIEs for these variables.
1439 DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
1440 CompileUnit *SPCU = getCompileUnit(SPNode);
1441 DIE *SPDie = SPCU->getDIE(SPNode);
1443 assert(SPDie && "Unable to find subprogram DIE!");
1444 DISubprogram SP(SPNode);
1446 // There is not any need to generate specification DIE for a function
1447 // defined at compile unit level. If a function is defined inside another
1448 // function then gdb prefers the definition at top level and but does not
1449 // expect specification DIE in parent function. So avoid creating
1450 // specification DIE for a function defined inside a function.
1451 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
1452 !SP.getContext().isFile() &&
1453 !isSubprogramContext(SP.getContext())) {
1454 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1457 DICompositeType SPTy = SP.getType();
1458 DIArray Args = SPTy.getTypeArray();
1459 unsigned SPTag = SPTy.getTag();
1460 if (SPTag == dwarf::DW_TAG_subroutine_type)
1461 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1462 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1463 DIType ATy = DIType(DIType(Args.getElement(i)));
1465 if (ATy.isArtificial())
1466 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1467 SPDie->addChild(Arg);
1469 DIE *SPDeclDie = SPDie;
1470 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1471 addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1473 SPCU->addDie(SPDie);
1476 // Pick up abstract subprogram DIE.
1477 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
1478 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1479 addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
1480 dwarf::DW_FORM_ref4, AbsSPDIE);
1481 SPCU->addDie(SPDie);
1484 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1485 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
1486 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1487 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
1488 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1489 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
1490 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1495 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1496 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1497 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1499 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1500 if (Scope->isAbstractScope())
1503 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1507 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1508 if (Ranges.size() > 1) {
1509 // .debug_range section has not been laid out yet. Emit offset in
1510 // .debug_range as a uint, size 4, for now. emitDIE will handle
1511 // DW_AT_ranges appropriately.
1512 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
1513 DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
1514 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1515 RE = Ranges.end(); RI != RE; ++RI) {
1516 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
1517 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
1519 DebugRangeSymbols.push_back(NULL);
1520 DebugRangeSymbols.push_back(NULL);
1524 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
1525 const MCSymbol *End = getLabelAfterInsn(RI->second);
1527 if (End == 0) return 0;
1529 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1530 assert(End->isDefined() && "Invalid end label for an inlined scope!");
1532 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
1533 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
1538 /// constructInlinedScopeDIE - This scope represents inlined body of
1539 /// a function. Construct DIE to represent this concrete inlined copy
1540 /// of the function.
1541 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1543 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1544 assert (Ranges.empty() == false
1545 && "DbgScope does not have instruction markers!");
1547 // FIXME : .debug_inlined section specification does not clearly state how
1548 // to emit inlined scope that is split into multiple instruction ranges.
1549 // For now, use first instruction range and emit low_pc/high_pc pair and
1550 // corresponding .debug_inlined section entry for this pair.
1551 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1552 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
1553 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
1555 if (StartLabel == 0 || EndLabel == 0) {
1556 assert (0 && "Unexpected Start and End labels for a inlined scope!");
1559 assert(StartLabel->isDefined() &&
1560 "Invalid starting label for an inlined scope!");
1561 assert(EndLabel->isDefined() &&
1562 "Invalid end label for an inlined scope!");
1564 if (!Scope->getScopeNode())
1566 DIScope DS(Scope->getScopeNode());
1567 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1569 DISubprogram InlinedSP = getDISubprogram(DS);
1570 CompileUnit *TheCU = getCompileUnit(InlinedSP);
1571 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
1572 assert(OriginDIE && "Unable to find Origin DIE!");
1573 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1574 dwarf::DW_FORM_ref4, OriginDIE);
1576 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1577 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1579 InlinedSubprogramDIEs.insert(OriginDIE);
1581 // Track the start label for this inlined function.
1582 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1583 I = InlineInfo.find(InlinedSP);
1585 if (I == InlineInfo.end()) {
1586 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
1588 InlinedSPNodes.push_back(InlinedSP);
1590 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1592 DILocation DL(Scope->getInlinedAt());
1593 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
1594 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1600 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1601 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1602 StringRef Name = DV->getName();
1606 // Translate tag to proper Dwarf tag. The result variable is dropped for
1609 switch (DV->getTag()) {
1610 case dwarf::DW_TAG_return_variable:
1612 case dwarf::DW_TAG_arg_variable:
1613 Tag = dwarf::DW_TAG_formal_parameter;
1615 case dwarf::DW_TAG_auto_variable: // fall thru
1617 Tag = dwarf::DW_TAG_variable;
1621 // Define variable debug information entry.
1622 DIE *VariableDie = new DIE(Tag);
1625 DenseMap<const DbgVariable *, const DbgVariable *>::iterator
1626 V2AVI = VarToAbstractVarMap.find(DV);
1627 if (V2AVI != VarToAbstractVarMap.end())
1628 AbsDIE = V2AVI->second->getDIE();
1631 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1632 dwarf::DW_FORM_ref4, AbsDIE);
1634 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1635 addSourceLine(VariableDie, DV->getVariable());
1637 // Add variable type.
1638 addType(VariableDie, DV->getType());
1641 if (Tag == dwarf::DW_TAG_formal_parameter && DV->getType().isArtificial())
1642 addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1643 else if (DIVariable(DV->getVariable()).isArtificial())
1644 addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1646 if (Scope->isAbstractScope()) {
1647 DV->setDIE(VariableDie);
1651 // Add variable address.
1653 unsigned Offset = DV->getDotDebugLocOffset();
1654 if (Offset != ~0U) {
1655 addLabel(VariableDie, dwarf::DW_AT_location, dwarf::DW_FORM_data4,
1656 Asm->GetTempSymbol("debug_loc", Offset));
1657 DV->setDIE(VariableDie);
1658 UseDotDebugLocEntry.insert(VariableDie);
1662 // Check if variable is described by a DBG_VALUE instruction.
1663 DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
1664 DbgVariableToDbgInstMap.find(DV);
1665 if (DVI != DbgVariableToDbgInstMap.end()) {
1666 const MachineInstr *DVInsn = DVI->second;
1667 const MCSymbol *DVLabel = findVariableLabel(DV);
1668 bool updated = false;
1669 // FIXME : Handle getNumOperands != 3
1670 if (DVInsn->getNumOperands() == 3) {
1671 if (DVInsn->getOperand(0).isReg()) {
1672 const MachineOperand RegOp = DVInsn->getOperand(0);
1673 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1674 if (DVInsn->getOperand(1).isImm() &&
1675 TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
1676 addVariableAddress(DV, VariableDie, DVInsn->getOperand(1).getImm());
1679 updated = addRegisterAddress(VariableDie, DVLabel, RegOp);
1681 else if (DVInsn->getOperand(0).isImm())
1682 updated = addConstantValue(VariableDie, DVLabel, DVInsn->getOperand(0));
1683 else if (DVInsn->getOperand(0).isFPImm())
1685 addConstantFPValue(VariableDie, DVLabel, DVInsn->getOperand(0));
1687 MachineLocation Location = Asm->getDebugValueLocation(DVInsn);
1688 if (Location.getReg()) {
1689 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1691 addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1697 // If variableDie is not updated then DBG_VALUE instruction does not
1698 // have valid variable info.
1702 DV->setDIE(VariableDie);
1706 // .. else use frame index, if available.
1708 if (findVariableFrameIndex(DV, &FI))
1709 addVariableAddress(DV, VariableDie, FI);
1711 DV->setDIE(VariableDie);
1716 void DwarfDebug::addPubTypes(DISubprogram SP) {
1717 DICompositeType SPTy = SP.getType();
1718 unsigned SPTag = SPTy.getTag();
1719 if (SPTag != dwarf::DW_TAG_subroutine_type)
1722 DIArray Args = SPTy.getTypeArray();
1723 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1724 DIType ATy(Args.getElement(i));
1727 DICompositeType CATy = getDICompositeType(ATy);
1728 if (DIDescriptor(CATy).Verify() && !CATy.getName().empty()
1729 && !CATy.isForwardDecl()) {
1730 CompileUnit *TheCU = getCompileUnit(CATy);
1731 if (DIEEntry *Entry = TheCU->getDIEEntry(CATy))
1732 TheCU->addGlobalType(CATy.getName(), Entry->getEntry());
1737 /// constructScopeDIE - Construct a DIE for this scope.
1738 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1739 if (!Scope || !Scope->getScopeNode())
1742 DIScope DS(Scope->getScopeNode());
1743 DIE *ScopeDIE = NULL;
1744 if (Scope->getInlinedAt())
1745 ScopeDIE = constructInlinedScopeDIE(Scope);
1746 else if (DS.isSubprogram()) {
1747 ProcessedSPNodes.insert(DS);
1748 if (Scope->isAbstractScope()) {
1749 ScopeDIE = getCompileUnit(DS)->getDIE(DS);
1750 // Note down abstract DIE.
1752 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
1755 ScopeDIE = updateSubprogramScopeDIE(DS);
1758 ScopeDIE = constructLexicalScopeDIE(Scope);
1759 if (!ScopeDIE) return NULL;
1761 // Add variables to scope.
1762 const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
1763 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1764 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1766 ScopeDIE->addChild(VariableDIE);
1769 // Add nested scopes.
1770 const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1771 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1772 // Define the Scope debug information entry.
1773 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1775 ScopeDIE->addChild(NestedDIE);
1778 if (DS.isSubprogram())
1779 addPubTypes(DISubprogram(DS));
1784 /// GetOrCreateSourceID - Look up the source id with the given directory and
1785 /// source file names. If none currently exists, create a new id and insert it
1786 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1788 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName){
1790 assert (DirName.empty() == false && "Invalid directory name!");
1792 // If FE did not provide a file name, then assume stdin.
1793 if (FileName.empty())
1794 return GetOrCreateSourceID(DirName, "<stdin>");
1796 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1797 if (DI != DirectoryIdMap.end()) {
1798 DId = DI->getValue();
1800 DId = DirectoryNames.size() + 1;
1801 DirectoryIdMap[DirName] = DId;
1802 DirectoryNames.push_back(DirName);
1806 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1807 if (FI != SourceFileIdMap.end()) {
1808 FId = FI->getValue();
1810 FId = SourceFileNames.size() + 1;
1811 SourceFileIdMap[FileName] = FId;
1812 SourceFileNames.push_back(FileName);
1815 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1816 SourceIdMap.find(std::make_pair(DId, FId));
1817 if (SI != SourceIdMap.end())
1820 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1821 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1822 SourceIds.push_back(std::make_pair(DId, FId));
1827 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1828 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1829 CompileUnit *TheCU = getCompileUnit(NS);
1830 DIE *NDie = TheCU->getDIE(NS);
1833 NDie = new DIE(dwarf::DW_TAG_namespace);
1834 TheCU->insertDIE(NS, NDie);
1835 if (!NS.getName().empty())
1836 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1837 addSourceLine(NDie, NS);
1838 addToContextOwner(NDie, NS.getContext());
1842 /// constructCompileUnit - Create new CompileUnit for the given
1843 /// metadata node with tag DW_TAG_compile_unit.
1844 void DwarfDebug::constructCompileUnit(const MDNode *N) {
1845 DICompileUnit DIUnit(N);
1846 StringRef FN = DIUnit.getFilename();
1847 StringRef Dir = DIUnit.getDirectory();
1848 unsigned ID = GetOrCreateSourceID(Dir, FN);
1850 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1851 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1852 DIUnit.getProducer());
1853 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1854 DIUnit.getLanguage());
1855 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1856 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
1857 // simplifies debug range entries.
1858 addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
1859 // DW_AT_stmt_list is a offset of line number information for this
1860 // compile unit in debug_line section.
1861 if (Asm->MAI->doesDwarfUsesAbsoluteLabelForStmtList())
1862 addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_addr,
1863 Asm->GetTempSymbol("section_line"));
1865 addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
1868 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1869 if (DIUnit.isOptimized())
1870 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1872 StringRef Flags = DIUnit.getFlags();
1874 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1876 unsigned RVer = DIUnit.getRunTimeVersion();
1878 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1879 dwarf::DW_FORM_data1, RVer);
1881 CompileUnit *NewCU = new CompileUnit(ID, Die);
1884 CUMap.insert(std::make_pair(N, NewCU));
1887 /// getCompielUnit - Get CompileUnit DIE.
1888 CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
1889 assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
1891 const MDNode *CUNode = NULL;
1892 if (D.isCompileUnit())
1894 else if (D.isSubprogram())
1895 CUNode = DISubprogram(N).getCompileUnit();
1896 else if (D.isType())
1897 CUNode = DIType(N).getCompileUnit();
1898 else if (D.isGlobalVariable())
1899 CUNode = DIGlobalVariable(N).getCompileUnit();
1900 else if (D.isVariable())
1901 CUNode = DIVariable(N).getCompileUnit();
1902 else if (D.isNameSpace())
1903 CUNode = DINameSpace(N).getCompileUnit();
1904 else if (D.isFile())
1905 CUNode = DIFile(N).getCompileUnit();
1909 DenseMap<const MDNode *, CompileUnit *>::const_iterator I
1910 = CUMap.find(CUNode);
1911 if (I == CUMap.end())
1916 /// isUnsignedDIType - Return true if type encoding is unsigned.
1917 static bool isUnsignedDIType(DIType Ty) {
1918 DIDerivedType DTy(Ty);
1920 return isUnsignedDIType(DTy.getTypeDerivedFrom());
1922 DIBasicType BTy(Ty);
1924 unsigned Encoding = BTy.getEncoding();
1925 if (Encoding == dwarf::DW_ATE_unsigned ||
1926 Encoding == dwarf::DW_ATE_unsigned_char)
1932 /// constructGlobalVariableDIE - Construct global variable DIE.
1933 void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
1934 DIGlobalVariable GV(N);
1936 // If debug information is malformed then ignore it.
1937 if (GV.Verify() == false)
1940 // Check for pre-existence.
1941 CompileUnit *TheCU = getCompileUnit(N);
1942 if (TheCU->getDIE(GV))
1945 DIType GTy = GV.getType();
1946 DIE *VariableDIE = new DIE(GV.getTag());
1948 bool isGlobalVariable = GV.getGlobal() != NULL;
1951 addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1952 GV.getDisplayName());
1953 StringRef LinkageName = GV.getLinkageName();
1954 if (!LinkageName.empty() && isGlobalVariable)
1955 addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1956 getRealLinkageName(LinkageName));
1958 addType(VariableDIE, GTy);
1959 if (GTy.isCompositeType() && !GTy.getName().empty()
1960 && !GTy.isForwardDecl()) {
1961 DIEEntry *Entry = TheCU->getDIEEntry(GTy);
1962 assert(Entry && "Missing global type!");
1963 TheCU->addGlobalType(GTy.getName(), Entry->getEntry());
1965 // Add scoping info.
1966 if (!GV.isLocalToUnit()) {
1967 addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1968 // Expose as global.
1969 TheCU->addGlobal(GV.getName(), VariableDIE);
1971 // Add line number info.
1972 addSourceLine(VariableDIE, GV);
1974 TheCU->insertDIE(N, VariableDIE);
1975 // Add to context owner.
1976 DIDescriptor GVContext = GV.getContext();
1977 addToContextOwner(VariableDIE, GVContext);
1979 if (isGlobalVariable) {
1980 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1981 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1982 addLabel(Block, 0, dwarf::DW_FORM_udata,
1983 Asm->Mang->getSymbol(GV.getGlobal()));
1984 // Do not create specification DIE if context is either compile unit
1986 if (GV.isDefinition() && !GVContext.isCompileUnit() &&
1987 !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1988 // Create specification DIE.
1989 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1990 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1991 dwarf::DW_FORM_ref4, VariableDIE);
1992 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1993 addUInt(VariableDIE, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1994 TheCU->addDie(VariableSpecDIE);
1996 addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1998 } else if (Constant *C = GV.getConstant()) {
1999 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
2000 if (isUnsignedDIType(GTy))
2001 addUInt(VariableDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
2002 CI->getZExtValue());
2004 addSInt(VariableDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
2005 CI->getSExtValue());
2011 /// construct SubprogramDIE - Construct subprogram DIE.
2012 void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
2015 // Check for pre-existence.
2016 CompileUnit *TheCU = getCompileUnit(N);
2017 if (TheCU->getDIE(N))
2020 if (!SP.isDefinition())
2021 // This is a method declaration which will be handled while constructing
2025 DIE *SubprogramDie = createSubprogramDIE(SP);
2028 TheCU->insertDIE(N, SubprogramDie);
2030 // Add to context owner.
2031 addToContextOwner(SubprogramDie, SP.getContext());
2033 // Expose as global.
2034 TheCU->addGlobal(SP.getName(), SubprogramDie);
2039 /// beginModule - Emit all Dwarf sections that should come prior to the
2040 /// content. Create global DIEs and emit initial debug info sections.
2041 /// This is inovked by the target AsmPrinter.
2042 void DwarfDebug::beginModule(Module *M) {
2043 if (DisableDebugInfoPrinting)
2046 DebugInfoFinder DbgFinder;
2047 DbgFinder.processModule(*M);
2049 bool HasDebugInfo = false;
2051 // Scan all the compile-units to see if there are any marked as the main unit.
2052 // if not, we do not generate debug info.
2053 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
2054 E = DbgFinder.compile_unit_end(); I != E; ++I) {
2055 if (DICompileUnit(*I).isMain()) {
2056 HasDebugInfo = true;
2061 if (!HasDebugInfo) return;
2063 // Tell MMI that we have debug info.
2064 MMI->setDebugInfoAvailability(true);
2066 // Emit initial sections.
2067 EmitSectionLabels();
2069 // Create all the compile unit DIEs.
2070 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
2071 E = DbgFinder.compile_unit_end(); I != E; ++I)
2072 constructCompileUnit(*I);
2074 // Create DIEs for each subprogram.
2075 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
2076 E = DbgFinder.subprogram_end(); I != E; ++I)
2077 constructSubprogramDIE(*I);
2079 // Create DIEs for each global variable.
2080 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
2081 E = DbgFinder.global_variable_end(); I != E; ++I)
2082 constructGlobalVariableDIE(*I);
2084 //getOrCreateTypeDIE
2085 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
2086 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
2087 getOrCreateTypeDIE(DIType(NMD->getOperand(i)));
2089 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
2090 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
2091 getOrCreateTypeDIE(DIType(NMD->getOperand(i)));
2093 // Prime section data.
2094 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
2096 // Print out .file directives to specify files for .loc directives. These are
2097 // printed out early so that they precede any .loc directives.
2098 if (Asm->MAI->hasDotLocAndDotFile()) {
2099 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
2100 // Remember source id starts at 1.
2101 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
2102 // FIXME: don't use sys::path for this! This should not depend on the
2104 sys::Path FullPath(getSourceDirectoryName(Id.first));
2106 FullPath.appendComponent(getSourceFileName(Id.second));
2107 assert(AppendOk && "Could not append filename to directory!");
2109 Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
2114 /// endModule - Emit all Dwarf sections that should come after the content.
2116 void DwarfDebug::endModule() {
2117 if (!FirstCU) return;
2118 const Module *M = MMI->getModule();
2119 DenseMap<const MDNode *, DbgScope *> DeadFnScopeMap;
2120 if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
2121 for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
2122 if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
2123 DISubprogram SP(AllSPs->getOperand(SI));
2124 if (!SP.Verify()) continue;
2126 // Collect info for variables that were optimized out.
2127 if (!SP.isDefinition()) continue;
2128 StringRef FName = SP.getLinkageName();
2130 FName = SP.getName();
2131 NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
2133 unsigned E = NMD->getNumOperands();
2135 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(SP), NULL);
2136 DeadFnScopeMap[SP] = Scope;
2137 for (unsigned I = 0; I != E; ++I) {
2138 DIVariable DV(NMD->getOperand(I));
2139 if (!DV.Verify()) continue;
2140 Scope->addVariable(new DbgVariable(DV));
2143 // Construct subprogram DIE and add variables DIEs.
2144 constructSubprogramDIE(SP);
2145 DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
2146 const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
2147 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2148 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
2150 ScopeDIE->addChild(VariableDIE);
2155 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
2156 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
2157 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
2159 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
2162 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
2163 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
2164 DIE *SPDie = CI->first;
2165 const MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
2167 DIE *NDie = getCompileUnit(N)->getDIE(N);
2168 if (!NDie) continue;
2169 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
2172 // Standard sections final addresses.
2173 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
2174 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
2175 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
2176 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
2178 // End text sections.
2179 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2180 Asm->OutStreamer.SwitchSection(SectionMap[i]);
2181 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
2184 // Emit common frame information.
2185 emitCommonDebugFrame();
2187 // Emit function debug frame information
2188 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2189 E = DebugFrames.end(); I != E; ++I)
2190 emitFunctionDebugFrame(*I);
2192 // Compute DIE offsets and sizes.
2193 computeSizeAndOffsets();
2195 // Emit all the DIEs into a debug info section
2198 // Corresponding abbreviations into a abbrev section.
2199 emitAbbreviations();
2201 // Emit source line correspondence into a debug line section.
2204 // Emit info into a debug pubnames section.
2205 emitDebugPubNames();
2207 // Emit info into a debug pubtypes section.
2208 emitDebugPubTypes();
2210 // Emit info into a debug loc section.
2213 // Emit info into a debug aranges section.
2216 // Emit info into a debug ranges section.
2219 // Emit info into a debug macinfo section.
2222 // Emit inline info.
2223 emitDebugInlineInfo();
2225 // Emit info into a debug str section.
2229 DeleteContainerSeconds(DeadFnScopeMap);
2230 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2231 E = CUMap.end(); I != E; ++I)
2233 FirstCU = NULL; // Reset for the next Module, if any.
2236 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2237 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2238 DebugLoc ScopeLoc) {
2240 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
2242 return AbsDbgVariable;
2244 LLVMContext &Ctx = Var->getContext();
2245 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2249 AbsDbgVariable = new DbgVariable(Var);
2250 Scope->addVariable(AbsDbgVariable);
2251 AbstractVariables[Var] = AbsDbgVariable;
2252 return AbsDbgVariable;
2255 /// collectVariableInfoFromMMITable - Collect variable information from
2256 /// side table maintained by MMI.
2258 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction * MF,
2259 SmallPtrSet<const MDNode *, 16> &Processed) {
2260 const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2261 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
2262 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
2263 VE = VMap.end(); VI != VE; ++VI) {
2264 const MDNode *Var = VI->first;
2266 Processed.insert(Var);
2268 const std::pair<unsigned, DebugLoc> &VP = VI->second;
2270 DbgScope *Scope = 0;
2271 if (const MDNode *IA = VP.second.getInlinedAt(Ctx))
2272 Scope = ConcreteScopes.lookup(IA);
2274 Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
2276 // If variable scope is not found then skip this variable.
2280 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
2281 DbgVariable *RegVar = new DbgVariable(DV);
2282 recordVariableFrameIndex(RegVar, VP.first);
2283 Scope->addVariable(RegVar);
2284 if (AbsDbgVariable) {
2285 recordVariableFrameIndex(AbsDbgVariable, VP.first);
2286 VarToAbstractVarMap[RegVar] = AbsDbgVariable;
2291 /// isDbgValueInUndefinedReg - Return true if debug value, encoded by
2292 /// DBG_VALUE instruction, is in undefined reg.
2293 static bool isDbgValueInUndefinedReg(const MachineInstr *MI) {
2294 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
2295 if (MI->getOperand(0).isReg() && !MI->getOperand(0).getReg())
2300 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
2301 /// DBG_VALUE instruction, is in a defined reg.
2302 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
2303 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
2304 if (MI->getOperand(0).isReg() && MI->getOperand(0).getReg())
2309 /// collectVariableInfo - Populate DbgScope entries with variables' info.
2311 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
2312 SmallPtrSet<const MDNode *, 16> &Processed) {
2314 /// collection info from MMI table.
2315 collectVariableInfoFromMMITable(MF, Processed);
2317 SmallVector<const MachineInstr *, 8> DbgValues;
2318 // Collect variable information from DBG_VALUE machine instructions;
2319 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2321 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2323 const MachineInstr *MInsn = II;
2324 if (!MInsn->isDebugValue() || isDbgValueInUndefinedReg(MInsn))
2326 DbgValues.push_back(MInsn);
2329 // This is a collection of DBV_VALUE instructions describing same variable.
2330 SmallVector<const MachineInstr *, 4> MultipleValues;
2331 for(SmallVector<const MachineInstr *, 8>::iterator I = DbgValues.begin(),
2332 E = DbgValues.end(); I != E; ++I) {
2333 const MachineInstr *MInsn = *I;
2334 MultipleValues.clear();
2335 if (isDbgValueInDefinedReg(MInsn))
2336 MultipleValues.push_back(MInsn);
2337 DIVariable DV(MInsn->getOperand(MInsn->getNumOperands() - 1).getMetadata());
2338 if (Processed.count(DV) != 0)
2341 const MachineInstr *PrevMI = MInsn;
2342 for (SmallVector<const MachineInstr *, 8>::iterator MI = I+1,
2343 ME = DbgValues.end(); MI != ME; ++MI) {
2345 (*MI)->getOperand((*MI)->getNumOperands()-1).getMetadata();
2346 if (Var == DV && isDbgValueInDefinedReg(*MI) &&
2347 !PrevMI->isIdenticalTo(*MI))
2348 MultipleValues.push_back(*MI);
2352 DbgScope *Scope = findDbgScope(MInsn);
2353 bool CurFnArg = false;
2354 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
2355 DISubprogram(DV.getContext()).describes(MF->getFunction()))
2357 if (!Scope && CurFnArg)
2358 Scope = CurrentFnDbgScope;
2359 // If variable scope is not found then skip this variable.
2363 Processed.insert(DV);
2364 DbgVariable *RegVar = new DbgVariable(DV);
2365 Scope->addVariable(RegVar);
2367 DbgVariableLabelsMap[RegVar] = getLabelBeforeInsn(MInsn);
2368 if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) {
2369 DbgVariableToDbgInstMap[AbsVar] = MInsn;
2370 VarToAbstractVarMap[RegVar] = AbsVar;
2372 if (MultipleValues.size() <= 1) {
2373 DbgVariableToDbgInstMap[RegVar] = MInsn;
2377 // handle multiple DBG_VALUE instructions describing one variable.
2378 if (DotDebugLocEntries.empty())
2379 RegVar->setDotDebugLocOffset(0);
2381 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
2382 const MachineInstr *Begin = NULL;
2383 const MachineInstr *End = NULL;
2384 for (SmallVector<const MachineInstr *, 4>::iterator
2385 MVI = MultipleValues.begin(), MVE = MultipleValues.end();
2386 MVI != MVE; ++MVI) {
2392 MachineLocation MLoc;
2393 if (Begin->getNumOperands() == 3) {
2394 if (Begin->getOperand(0).isReg() && Begin->getOperand(1).isImm())
2395 MLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
2397 MLoc = Asm->getDebugValueLocation(Begin);
2399 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
2400 const MCSymbol *SLabel = getLabelBeforeInsn(End);
2402 DotDebugLocEntries.push_back(DotDebugLocEntry(FLabel, SLabel, MLoc));
2405 if (MVI + 1 == MVE) {
2406 // If End is the last instruction then its value is valid
2407 // until the end of the funtion.
2408 MachineLocation EMLoc;
2409 if (End->getNumOperands() == 3) {
2410 if (End->getOperand(0).isReg() && Begin->getOperand(1).isImm())
2411 EMLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
2413 EMLoc = Asm->getDebugValueLocation(End);
2416 push_back(DotDebugLocEntry(SLabel, FunctionEndSym, EMLoc));
2419 DotDebugLocEntries.push_back(DotDebugLocEntry());
2422 // Collect info for variables that were optimized out.
2423 const Function *F = MF->getFunction();
2424 if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
2425 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2426 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2427 if (!DV || !Processed.insert(DV))
2429 DbgScope *Scope = DbgScopeMap.lookup(DV.getContext());
2431 Scope->addVariable(new DbgVariable(DV));
2436 /// getLabelBeforeInsn - Return Label preceding the instruction.
2437 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
2438 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
2439 LabelsBeforeInsn.find(MI);
2440 if (I == LabelsBeforeInsn.end())
2441 // FunctionBeginSym always preceeds all the instruction in current function.
2442 return FunctionBeginSym;
2446 /// getLabelAfterInsn - Return Label immediately following the instruction.
2447 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
2448 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
2449 LabelsAfterInsn.find(MI);
2450 if (I == LabelsAfterInsn.end())
2455 /// beginInstruction - Process beginning of an instruction.
2456 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
2457 if (InsnNeedsLabel.count(MI) == 0) {
2458 LabelsBeforeInsn[MI] = PrevLabel;
2463 DebugLoc DL = MI->getDebugLoc();
2464 if (!DL.isUnknown()) {
2465 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
2466 PrevLabel = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2468 LabelsBeforeInsn[MI] = PrevLabel;
2472 // If location is unknown then use temp label for this DBG_VALUE
2474 if (MI->isDebugValue()) {
2475 PrevLabel = MMI->getContext().CreateTempSymbol();
2476 Asm->OutStreamer.EmitLabel(PrevLabel);
2477 LabelsBeforeInsn[MI] = PrevLabel;
2481 if (UnknownLocations) {
2482 PrevLabel = recordSourceLine(0, 0, 0);
2483 LabelsBeforeInsn[MI] = PrevLabel;
2487 assert (0 && "Instruction is not processed!");
2490 /// endInstruction - Process end of an instruction.
2491 void DwarfDebug::endInstruction(const MachineInstr *MI) {
2492 if (InsnsEndScopeSet.count(MI) != 0) {
2493 // Emit a label if this instruction ends a scope.
2494 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2495 Asm->OutStreamer.EmitLabel(Label);
2496 LabelsAfterInsn[MI] = Label;
2500 /// getOrCreateDbgScope - Create DbgScope for the scope.
2501 DbgScope *DwarfDebug::getOrCreateDbgScope(const MDNode *Scope,
2502 const MDNode *InlinedAt) {
2504 DbgScope *WScope = DbgScopeMap.lookup(Scope);
2507 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2508 DbgScopeMap.insert(std::make_pair(Scope, WScope));
2509 if (DIDescriptor(Scope).isLexicalBlock()) {
2511 getOrCreateDbgScope(DILexicalBlock(Scope).getContext(), NULL);
2512 WScope->setParent(Parent);
2513 Parent->addScope(WScope);
2516 if (!WScope->getParent()) {
2517 StringRef SPName = DISubprogram(Scope).getLinkageName();
2518 // We used to check only for a linkage name, but that fails
2519 // since we began omitting the linkage name for private
2520 // functions. The new way is to check for the name in metadata,
2521 // but that's not supported in old .ll test cases. Ergo, we
2523 if (SPName == Asm->MF->getFunction()->getName() ||
2524 DISubprogram(Scope).getFunction() == Asm->MF->getFunction())
2525 CurrentFnDbgScope = WScope;
2531 getOrCreateAbstractScope(Scope);
2532 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2536 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2537 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2538 DILocation DL(InlinedAt);
2540 getOrCreateDbgScope(DL.getScope(), DL.getOrigLocation());
2541 WScope->setParent(Parent);
2542 Parent->addScope(WScope);
2544 ConcreteScopes[InlinedAt] = WScope;
2549 /// hasValidLocation - Return true if debug location entry attached with
2550 /// machine instruction encodes valid location info.
2551 static bool hasValidLocation(LLVMContext &Ctx,
2552 const MachineInstr *MInsn,
2553 const MDNode *&Scope, const MDNode *&InlinedAt) {
2554 DebugLoc DL = MInsn->getDebugLoc();
2555 if (DL.isUnknown()) return false;
2557 const MDNode *S = DL.getScope(Ctx);
2559 // There is no need to create another DIE for compile unit. For all
2560 // other scopes, create one DbgScope now. This will be translated
2561 // into a scope DIE at the end.
2562 if (DIScope(S).isCompileUnit()) return false;
2565 InlinedAt = DL.getInlinedAt(Ctx);
2569 /// calculateDominanceGraph - Calculate dominance graph for DbgScope
2571 static void calculateDominanceGraph(DbgScope *Scope) {
2572 assert (Scope && "Unable to calculate scop edominance graph!");
2573 SmallVector<DbgScope *, 4> WorkStack;
2574 WorkStack.push_back(Scope);
2575 unsigned Counter = 0;
2576 while (!WorkStack.empty()) {
2577 DbgScope *WS = WorkStack.back();
2578 const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
2579 bool visitedChildren = false;
2580 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2581 SE = Children.end(); SI != SE; ++SI) {
2582 DbgScope *ChildScope = *SI;
2583 if (!ChildScope->getDFSOut()) {
2584 WorkStack.push_back(ChildScope);
2585 visitedChildren = true;
2586 ChildScope->setDFSIn(++Counter);
2590 if (!visitedChildren) {
2591 WorkStack.pop_back();
2592 WS->setDFSOut(++Counter);
2597 /// printDbgScopeInfo - Print DbgScope info for each machine instruction.
2599 void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
2600 DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
2603 unsigned PrevDFSIn = 0;
2604 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2606 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2608 const MachineInstr *MInsn = II;
2609 const MDNode *Scope = NULL;
2610 const MDNode *InlinedAt = NULL;
2612 // Check if instruction has valid location information.
2613 if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2617 DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
2618 MI2ScopeMap.find(MInsn);
2619 if (DI != MI2ScopeMap.end()) {
2620 DbgScope *S = DI->second;
2621 dbgs() << S->getDFSIn();
2622 PrevDFSIn = S->getDFSIn();
2624 dbgs() << PrevDFSIn;
2626 dbgs() << " [ x" << PrevDFSIn;
2634 /// extractScopeInformation - Scan machine instructions in this function
2635 /// and collect DbgScopes. Return true, if at least one scope was found.
2636 bool DwarfDebug::extractScopeInformation() {
2637 // If scope information was extracted using .dbg intrinsics then there is not
2638 // any need to extract these information by scanning each instruction.
2639 if (!DbgScopeMap.empty())
2642 // Scan each instruction and create scopes. First build working set of scopes.
2643 LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2644 SmallVector<DbgRange, 4> MIRanges;
2645 DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
2646 const MDNode *PrevScope = NULL;
2647 const MDNode *PrevInlinedAt = NULL;
2648 const MachineInstr *RangeBeginMI = NULL;
2649 const MachineInstr *PrevMI = NULL;
2650 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2652 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2654 const MachineInstr *MInsn = II;
2655 const MDNode *Scope = NULL;
2656 const MDNode *InlinedAt = NULL;
2658 // Check if instruction has valid location information.
2659 if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2664 // If scope has not changed then skip this instruction.
2665 if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
2671 // If we have alread seen a beginning of a instruction range and
2672 // current instruction scope does not match scope of first instruction
2673 // in this range then create a new instruction range.
2674 DbgRange R(RangeBeginMI, PrevMI);
2675 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope,
2677 MIRanges.push_back(R);
2680 // This is a beginning of a new instruction range.
2681 RangeBeginMI = MInsn;
2683 // Reset previous markers.
2686 PrevInlinedAt = InlinedAt;
2690 // Create last instruction range.
2691 if (RangeBeginMI && PrevMI && PrevScope) {
2692 DbgRange R(RangeBeginMI, PrevMI);
2693 MIRanges.push_back(R);
2694 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2697 if (!CurrentFnDbgScope)
2700 calculateDominanceGraph(CurrentFnDbgScope);
2702 printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
2704 // Find ranges of instructions covered by each DbgScope;
2705 DbgScope *PrevDbgScope = NULL;
2706 for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
2707 RE = MIRanges.end(); RI != RE; ++RI) {
2708 const DbgRange &R = *RI;
2709 DbgScope *S = MI2ScopeMap.lookup(R.first);
2710 assert (S && "Lost DbgScope for a machine instruction!");
2711 if (PrevDbgScope && !PrevDbgScope->dominates(S))
2712 PrevDbgScope->closeInsnRange(S);
2713 S->openInsnRange(R.first);
2714 S->extendInsnRange(R.second);
2719 PrevDbgScope->closeInsnRange();
2721 identifyScopeMarkers();
2723 return !DbgScopeMap.empty();
2726 /// identifyScopeMarkers() -
2727 /// Each DbgScope has first instruction and last instruction to mark beginning
2728 /// and end of a scope respectively. Create an inverse map that list scopes
2729 /// starts (and ends) with an instruction. One instruction may start (or end)
2730 /// multiple scopes. Ignore scopes that are not reachable.
2731 void DwarfDebug::identifyScopeMarkers() {
2732 SmallVector<DbgScope *, 4> WorkList;
2733 WorkList.push_back(CurrentFnDbgScope);
2734 while (!WorkList.empty()) {
2735 DbgScope *S = WorkList.pop_back_val();
2737 const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2738 if (!Children.empty())
2739 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2740 SE = Children.end(); SI != SE; ++SI)
2741 WorkList.push_back(*SI);
2743 if (S->isAbstractScope())
2746 const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
2749 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
2750 RE = Ranges.end(); RI != RE; ++RI) {
2751 assert(RI->first && "DbgRange does not have first instruction!");
2752 assert(RI->second && "DbgRange does not have second instruction!");
2753 InsnsEndScopeSet.insert(RI->second);
2758 /// FindFirstDebugLoc - Find the first debug location in the function. This
2759 /// is intended to be an approximation for the source position of the
2760 /// beginning of the function.
2761 static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
2762 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2764 for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
2765 MBBI != MBBE; ++MBBI) {
2766 DebugLoc DL = MBBI->getDebugLoc();
2767 if (!DL.isUnknown())
2774 /// CheckLineNumbers - Count basicblocks whose instructions do not have any
2775 /// line number information.
2776 static void CheckLineNumbers(const MachineFunction *MF) {
2777 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2779 bool FoundLineNo = false;
2780 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2782 const MachineInstr *MI = II;
2783 if (!MI->getDebugLoc().isUnknown()) {
2788 if (!FoundLineNo && I->size())
2789 ++BlocksWithoutLineNo;
2794 /// beginFunction - Gather pre-function debug information. Assumes being
2795 /// emitted immediately after the function entry point.
2796 void DwarfDebug::beginFunction(const MachineFunction *MF) {
2797 if (!MMI->hasDebugInfo()) return;
2798 if (!extractScopeInformation()) return;
2801 CheckLineNumbers(MF);
2804 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
2805 Asm->getFunctionNumber());
2806 // Assumes in correct section after the entry point.
2807 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
2809 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2811 DebugLoc FDL = FindFirstDebugLoc(MF);
2812 if (FDL.isUnknown()) return;
2814 const MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
2815 const MDNode *TheScope = 0;
2817 DISubprogram SP = getDISubprogram(Scope);
2820 Line = SP.getLineNumber();
2824 Line = FDL.getLine();
2829 recordSourceLine(Line, Col, TheScope);
2831 /// ProcessedArgs - Collection of arguments already processed.
2832 SmallPtrSet<const MDNode *, 8> ProcessedArgs;
2835 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2837 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2839 const MachineInstr *MI = II;
2840 DebugLoc DL = MI->getDebugLoc();
2841 if (MI->isDebugValue()) {
2842 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
2843 DIVariable DV(MI->getOperand(MI->getNumOperands() - 1).getMetadata());
2844 if (!DV.Verify()) continue;
2845 // If DBG_VALUE is for a local variable then it needs a label.
2846 if (DV.getTag() != dwarf::DW_TAG_arg_variable
2847 && isDbgValueInUndefinedReg(MI) == false)
2848 InsnNeedsLabel.insert(MI);
2849 // DBG_VALUE for inlined functions argument needs a label.
2850 else if (!DISubprogram(getDISubprogram(DV.getContext())).
2851 describes(MF->getFunction()))
2852 InsnNeedsLabel.insert(MI);
2853 // DBG_VALUE indicating argument location change needs a label.
2854 else if (isDbgValueInUndefinedReg(MI) == false
2855 && !ProcessedArgs.insert(DV))
2856 InsnNeedsLabel.insert(MI);
2858 // If location is unknown then instruction needs a location only if
2859 // UnknownLocations flag is set.
2860 if (DL.isUnknown()) {
2861 if (UnknownLocations && !PrevLoc.isUnknown())
2862 InsnNeedsLabel.insert(MI);
2863 } else if (DL != PrevLoc)
2864 // Otherwise, instruction needs a location only if it is new location.
2865 InsnNeedsLabel.insert(MI);
2868 if (!DL.isUnknown() || UnknownLocations)
2872 PrevLabel = FunctionBeginSym;
2875 /// endFunction - Gather and emit post-function debug information.
2877 void DwarfDebug::endFunction(const MachineFunction *MF) {
2878 if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2880 if (CurrentFnDbgScope) {
2882 // Define end label for subprogram.
2883 FunctionEndSym = Asm->GetTempSymbol("func_end",
2884 Asm->getFunctionNumber());
2885 // Assumes in correct section after the entry point.
2886 Asm->OutStreamer.EmitLabel(FunctionEndSym);
2888 SmallPtrSet<const MDNode *, 16> ProcessedVars;
2889 collectVariableInfo(MF, ProcessedVars);
2891 // Get function line info.
2892 if (!Lines.empty()) {
2893 // Get section line info.
2894 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2895 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2896 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2897 // Append the function info to section info.
2898 SectionLineInfos.insert(SectionLineInfos.end(),
2899 Lines.begin(), Lines.end());
2902 // Construct abstract scopes.
2903 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2904 AE = AbstractScopesList.end(); AI != AE; ++AI) {
2905 DISubprogram SP((*AI)->getScopeNode());
2907 // Collect info for variables that were optimized out.
2908 StringRef FName = SP.getLinkageName();
2910 FName = SP.getName();
2911 if (NamedMDNode *NMD =
2912 getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
2913 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2914 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2915 if (!DV || !ProcessedVars.insert(DV))
2917 DbgScope *Scope = AbstractScopes.lookup(DV.getContext());
2919 Scope->addVariable(new DbgVariable(DV));
2923 if (ProcessedSPNodes.count((*AI)->getScopeNode()) == 0)
2924 constructScopeDIE(*AI);
2927 DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope);
2929 if (!DisableFramePointerElim(*MF))
2930 addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
2931 dwarf::DW_FORM_flag, 1);
2934 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2935 MMI->getFrameMoves()));
2939 CurrentFnDbgScope = NULL;
2940 InsnNeedsLabel.clear();
2941 DbgVariableToFrameIndexMap.clear();
2942 VarToAbstractVarMap.clear();
2943 DbgVariableToDbgInstMap.clear();
2944 DbgVariableLabelsMap.clear();
2945 DeleteContainerSeconds(DbgScopeMap);
2946 InsnsEndScopeSet.clear();
2947 ConcreteScopes.clear();
2948 DeleteContainerSeconds(AbstractScopes);
2949 AbstractScopesList.clear();
2950 AbstractVariables.clear();
2951 LabelsBeforeInsn.clear();
2952 LabelsAfterInsn.clear();
2957 /// recordVariableFrameIndex - Record a variable's index.
2958 void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
2959 assert (V && "Invalid DbgVariable!");
2960 DbgVariableToFrameIndexMap[V] = Index;
2963 /// findVariableFrameIndex - Return true if frame index for the variable
2964 /// is found. Update FI to hold value of the index.
2965 bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
2966 assert (V && "Invalid DbgVariable!");
2967 DenseMap<const DbgVariable *, int>::iterator I =
2968 DbgVariableToFrameIndexMap.find(V);
2969 if (I == DbgVariableToFrameIndexMap.end())
2975 /// findVariableLabel - Find MCSymbol for the variable.
2976 const MCSymbol *DwarfDebug::findVariableLabel(const DbgVariable *V) {
2977 DenseMap<const DbgVariable *, const MCSymbol *>::iterator I
2978 = DbgVariableLabelsMap.find(V);
2979 if (I == DbgVariableLabelsMap.end())
2981 else return I->second;
2984 /// findDbgScope - Find DbgScope for the debug loc attached with an
2986 DbgScope *DwarfDebug::findDbgScope(const MachineInstr *MInsn) {
2987 DbgScope *Scope = NULL;
2989 MInsn->getParent()->getParent()->getFunction()->getContext();
2990 DebugLoc DL = MInsn->getDebugLoc();
2995 if (const MDNode *IA = DL.getInlinedAt(Ctx))
2996 Scope = ConcreteScopes.lookup(IA);
2998 Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
3004 /// recordSourceLine - Register a source line with debug info. Returns the
3005 /// unique label that was emitted and which provides correspondence to
3006 /// the source line list.
3007 MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col,
3014 DIDescriptor Scope(S);
3016 if (Scope.isCompileUnit()) {
3017 DICompileUnit CU(S);
3018 Dir = CU.getDirectory();
3019 Fn = CU.getFilename();
3020 } else if (Scope.isFile()) {
3022 Dir = F.getDirectory();
3023 Fn = F.getFilename();
3024 } else if (Scope.isSubprogram()) {
3026 Dir = SP.getDirectory();
3027 Fn = SP.getFilename();
3028 } else if (Scope.isLexicalBlock()) {
3029 DILexicalBlock DB(S);
3030 Dir = DB.getDirectory();
3031 Fn = DB.getFilename();
3033 assert(0 && "Unexpected scope info");
3035 Src = GetOrCreateSourceID(Dir, Fn);
3038 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
3039 Lines.push_back(SrcLineInfo(Line, Col, Src, Label));
3041 Asm->OutStreamer.EmitLabel(Label);
3045 //===----------------------------------------------------------------------===//
3047 //===----------------------------------------------------------------------===//
3049 /// computeSizeAndOffset - Compute the size and offset of a DIE.
3052 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
3053 // Get the children.
3054 const std::vector<DIE *> &Children = Die->getChildren();
3056 // If not last sibling and has children then add sibling offset attribute.
3057 if (!Last && !Children.empty())
3058 Die->addSiblingOffset(DIEValueAllocator);
3060 // Record the abbreviation.
3061 assignAbbrevNumber(Die->getAbbrev());
3063 // Get the abbreviation for this DIE.
3064 unsigned AbbrevNumber = Die->getAbbrevNumber();
3065 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
3068 Die->setOffset(Offset);
3070 // Start the size with the size of abbreviation code.
3071 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
3073 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
3074 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
3076 // Size the DIE attribute values.
3077 for (unsigned i = 0, N = Values.size(); i < N; ++i)
3078 // Size attribute value.
3079 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
3081 // Size the DIE children if any.
3082 if (!Children.empty()) {
3083 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
3084 "Children flag not set");
3086 for (unsigned j = 0, M = Children.size(); j < M; ++j)
3087 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
3089 // End of children marker.
3090 Offset += sizeof(int8_t);
3093 Die->setSize(Offset - Die->getOffset());
3097 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
3099 void DwarfDebug::computeSizeAndOffsets() {
3100 unsigned PrevOffset = 0;
3101 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3102 E = CUMap.end(); I != E; ++I) {
3103 // Compute size of compile unit header.
3104 static unsigned Offset = PrevOffset +
3105 sizeof(int32_t) + // Length of Compilation Unit Info
3106 sizeof(int16_t) + // DWARF version number
3107 sizeof(int32_t) + // Offset Into Abbrev. Section
3108 sizeof(int8_t); // Pointer Size (in bytes)
3109 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
3110 PrevOffset = Offset;
3114 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
3115 /// temporary label to it if SymbolStem is specified.
3116 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
3117 const char *SymbolStem = 0) {
3118 Asm->OutStreamer.SwitchSection(Section);
3119 if (!SymbolStem) return 0;
3121 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
3122 Asm->OutStreamer.EmitLabel(TmpSym);
3126 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
3127 /// the start of each one.
3128 void DwarfDebug::EmitSectionLabels() {
3129 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
3131 // Dwarf sections base addresses.
3132 if (Asm->MAI->doesDwarfRequireFrameSection()) {
3133 DwarfFrameSectionSym =
3134 EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
3137 DwarfInfoSectionSym =
3138 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
3139 DwarfAbbrevSectionSym =
3140 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
3141 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
3143 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
3144 EmitSectionSym(Asm, MacroInfo);
3146 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
3147 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
3148 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
3149 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
3150 DwarfStrSectionSym =
3151 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
3152 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
3155 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
3156 "section_debug_loc");
3158 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
3159 EmitSectionSym(Asm, TLOF.getDataSection());
3162 /// emitDIE - Recusively Emits a debug information entry.
3164 void DwarfDebug::emitDIE(DIE *Die) {
3165 // Get the abbreviation for this DIE.
3166 unsigned AbbrevNumber = Die->getAbbrevNumber();
3167 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
3169 // Emit the code (index) for the abbreviation.
3170 if (Asm->isVerbose())
3171 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
3172 Twine::utohexstr(Die->getOffset()) + ":0x" +
3173 Twine::utohexstr(Die->getSize()) + " " +
3174 dwarf::TagString(Abbrev->getTag()));
3175 Asm->EmitULEB128(AbbrevNumber);
3177 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
3178 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
3180 // Emit the DIE attribute values.
3181 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3182 unsigned Attr = AbbrevData[i].getAttribute();
3183 unsigned Form = AbbrevData[i].getForm();
3184 assert(Form && "Too many attributes for DIE (check abbreviation)");
3186 if (Asm->isVerbose())
3187 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
3190 case dwarf::DW_AT_sibling:
3191 Asm->EmitInt32(Die->getSiblingOffset());
3193 case dwarf::DW_AT_abstract_origin: {
3194 DIEEntry *E = cast<DIEEntry>(Values[i]);
3195 DIE *Origin = E->getEntry();
3196 unsigned Addr = Origin->getOffset();
3197 Asm->EmitInt32(Addr);
3200 case dwarf::DW_AT_ranges: {
3201 // DW_AT_range Value encodes offset in debug_range section.
3202 DIEInteger *V = cast<DIEInteger>(Values[i]);
3204 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
3205 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
3209 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
3211 DwarfDebugRangeSectionSym,
3216 case dwarf::DW_AT_location: {
3217 if (UseDotDebugLocEntry.count(Die) != 0) {
3218 DIELabel *L = cast<DIELabel>(Values[i]);
3219 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
3221 Values[i]->EmitValue(Asm, Form);
3224 case dwarf::DW_AT_accessibility: {
3225 if (Asm->isVerbose()) {
3226 DIEInteger *V = cast<DIEInteger>(Values[i]);
3227 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
3229 Values[i]->EmitValue(Asm, Form);
3233 // Emit an attribute using the defined form.
3234 Values[i]->EmitValue(Asm, Form);
3239 // Emit the DIE children if any.
3240 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
3241 const std::vector<DIE *> &Children = Die->getChildren();
3243 for (unsigned j = 0, M = Children.size(); j < M; ++j)
3244 emitDIE(Children[j]);
3246 if (Asm->isVerbose())
3247 Asm->OutStreamer.AddComment("End Of Children Mark");
3252 /// emitDebugInfo - Emit the debug info section.
3254 void DwarfDebug::emitDebugInfo() {
3255 // Start debug info section.
3256 Asm->OutStreamer.SwitchSection(
3257 Asm->getObjFileLowering().getDwarfInfoSection());
3258 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3259 E = CUMap.end(); I != E; ++I) {
3260 CompileUnit *TheCU = I->second;
3261 DIE *Die = TheCU->getCUDie();
3263 // Emit the compile units header.
3264 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
3267 // Emit size of content not including length itself
3268 unsigned ContentSize = Die->getSize() +
3269 sizeof(int16_t) + // DWARF version number
3270 sizeof(int32_t) + // Offset Into Abbrev. Section
3271 sizeof(int8_t) + // Pointer Size (in bytes)
3272 sizeof(int32_t); // FIXME - extra pad for gdb bug.
3274 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
3275 Asm->EmitInt32(ContentSize);
3276 Asm->OutStreamer.AddComment("DWARF version number");
3277 Asm->EmitInt16(dwarf::DWARF_VERSION);
3278 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
3279 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
3280 DwarfAbbrevSectionSym);
3281 Asm->OutStreamer.AddComment("Address Size (in bytes)");
3282 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3285 // FIXME - extra padding for gdb bug.
3286 Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
3291 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
3295 /// emitAbbreviations - Emit the abbreviation section.
3297 void DwarfDebug::emitAbbreviations() const {
3298 // Check to see if it is worth the effort.
3299 if (!Abbreviations.empty()) {
3300 // Start the debug abbrev section.
3301 Asm->OutStreamer.SwitchSection(
3302 Asm->getObjFileLowering().getDwarfAbbrevSection());
3304 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
3306 // For each abbrevation.
3307 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
3308 // Get abbreviation data
3309 const DIEAbbrev *Abbrev = Abbreviations[i];
3311 // Emit the abbrevations code (base 1 index.)
3312 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
3314 // Emit the abbreviations data.
3318 // Mark end of abbreviations.
3319 Asm->EmitULEB128(0, "EOM(3)");
3321 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
3325 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
3326 /// the line matrix.
3328 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
3329 // Define last address of section.
3330 Asm->OutStreamer.AddComment("Extended Op");
3333 Asm->OutStreamer.AddComment("Op size");
3334 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
3335 Asm->OutStreamer.AddComment("DW_LNE_set_address");
3336 Asm->EmitInt8(dwarf::DW_LNE_set_address);
3338 Asm->OutStreamer.AddComment("Section end label");
3340 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
3341 Asm->getTargetData().getPointerSize(),
3344 // Mark end of matrix.
3345 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
3351 /// emitDebugLines - Emit source line information.
3353 void DwarfDebug::emitDebugLines() {
3354 // If the target is using .loc/.file, the assembler will be emitting the
3355 // .debug_line table automatically.
3356 if (Asm->MAI->hasDotLocAndDotFile())
3359 // Minimum line delta, thus ranging from -10..(255-10).
3360 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
3361 // Maximum line delta, thus ranging from -10..(255-10).
3362 const int MaxLineDelta = 255 + MinLineDelta;
3364 // Start the dwarf line section.
3365 Asm->OutStreamer.SwitchSection(
3366 Asm->getObjFileLowering().getDwarfLineSection());
3368 // Construct the section header.
3369 Asm->OutStreamer.AddComment("Length of Source Line Info");
3370 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_end"),
3371 Asm->GetTempSymbol("line_begin"), 4);
3372 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_begin"));
3374 Asm->OutStreamer.AddComment("DWARF version number");
3375 Asm->EmitInt16(dwarf::DWARF_VERSION);
3377 Asm->OutStreamer.AddComment("Prolog Length");
3378 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_prolog_end"),
3379 Asm->GetTempSymbol("line_prolog_begin"), 4);
3380 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_begin"));
3382 Asm->OutStreamer.AddComment("Minimum Instruction Length");
3384 Asm->OutStreamer.AddComment("Default is_stmt_start flag");
3386 Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)");
3387 Asm->EmitInt8(MinLineDelta);
3388 Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)");
3389 Asm->EmitInt8(MaxLineDelta);
3390 Asm->OutStreamer.AddComment("Special Opcode Base");
3391 Asm->EmitInt8(-MinLineDelta);
3393 // Line number standard opcode encodings argument count
3394 Asm->OutStreamer.AddComment("DW_LNS_copy arg count");
3396 Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count");
3398 Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count");
3400 Asm->OutStreamer.AddComment("DW_LNS_set_file arg count");
3402 Asm->OutStreamer.AddComment("DW_LNS_set_column arg count");
3404 Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count");
3406 Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count");
3408 Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count");
3410 Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count");
3413 // Emit directories.
3414 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
3415 const std::string &Dir = getSourceDirectoryName(DI);
3416 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Directory");
3417 Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
3420 Asm->OutStreamer.AddComment("End of directories");
3424 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
3425 // Remember source id starts at 1.
3426 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
3427 const std::string &FN = getSourceFileName(Id.second);
3428 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Source");
3429 Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
3431 Asm->EmitULEB128(Id.first, "Directory #");
3432 Asm->EmitULEB128(0, "Mod date");
3433 Asm->EmitULEB128(0, "File size");
3436 Asm->OutStreamer.AddComment("End of files");
3439 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_end"));
3441 // A sequence for each text section.
3442 unsigned SecSrcLinesSize = SectionSourceLines.size();
3444 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
3445 // Isolate current sections line info.
3446 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
3448 // Dwarf assumes we start with first line of first source file.
3449 unsigned Source = 1;
3452 // Construct rows of the address, source, line, column matrix.
3453 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
3454 const SrcLineInfo &LineInfo = LineInfos[i];
3455 MCSymbol *Label = LineInfo.getLabel();
3456 if (!Label->isDefined()) continue; // Not emitted, in dead code.
3458 if (Asm->isVerbose()) {
3459 std::pair<unsigned, unsigned> SrcID =
3460 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
3461 Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) +
3463 Twine(getSourceFileName(SrcID.second)) +
3464 ":" + Twine(LineInfo.getLine()));
3467 // Define the line address.
3468 Asm->OutStreamer.AddComment("Extended Op");
3470 Asm->OutStreamer.AddComment("Op size");
3471 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
3473 Asm->OutStreamer.AddComment("DW_LNE_set_address");
3474 Asm->EmitInt8(dwarf::DW_LNE_set_address);
3476 Asm->OutStreamer.AddComment("Location label");
3477 Asm->OutStreamer.EmitSymbolValue(Label,
3478 Asm->getTargetData().getPointerSize(),
3481 // If change of source, then switch to the new source.
3482 if (Source != LineInfo.getSourceID()) {
3483 Source = LineInfo.getSourceID();
3484 Asm->OutStreamer.AddComment("DW_LNS_set_file");
3485 Asm->EmitInt8(dwarf::DW_LNS_set_file);
3486 Asm->EmitULEB128(Source, "New Source");
3489 // If change of line.
3490 if (Line != LineInfo.getLine()) {
3491 // Determine offset.
3492 int Offset = LineInfo.getLine() - Line;
3493 int Delta = Offset - MinLineDelta;
3496 Line = LineInfo.getLine();
3498 // If delta is small enough and in range...
3499 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
3500 // ... then use fast opcode.
3501 Asm->OutStreamer.AddComment("Line Delta");
3502 Asm->EmitInt8(Delta - MinLineDelta);
3504 // ... otherwise use long hand.
3505 Asm->OutStreamer.AddComment("DW_LNS_advance_line");
3506 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
3507 Asm->EmitSLEB128(Offset, "Line Offset");
3508 Asm->OutStreamer.AddComment("DW_LNS_copy");
3509 Asm->EmitInt8(dwarf::DW_LNS_copy);
3512 // Copy the previous row (different address or source)
3513 Asm->OutStreamer.AddComment("DW_LNS_copy");
3514 Asm->EmitInt8(dwarf::DW_LNS_copy);
3518 emitEndOfLineMatrix(j + 1);
3521 if (SecSrcLinesSize == 0)
3522 // Because we're emitting a debug_line section, we still need a line
3523 // table. The linker and friends expect it to exist. If there's nothing to
3524 // put into it, emit an empty table.
3525 emitEndOfLineMatrix(1);
3527 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_end"));
3530 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
3532 void DwarfDebug::emitCommonDebugFrame() {
3533 if (!Asm->MAI->doesDwarfRequireFrameSection())
3536 int stackGrowth = Asm->getTargetData().getPointerSize();
3537 if (Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3538 TargetFrameInfo::StackGrowsDown)
3541 // Start the dwarf frame section.
3542 Asm->OutStreamer.SwitchSection(
3543 Asm->getObjFileLowering().getDwarfFrameSection());
3545 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
3546 Asm->OutStreamer.AddComment("Length of Common Information Entry");
3547 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
3548 Asm->GetTempSymbol("debug_frame_common_begin"), 4);
3550 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
3551 Asm->OutStreamer.AddComment("CIE Identifier Tag");
3552 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
3553 Asm->OutStreamer.AddComment("CIE Version");
3554 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
3555 Asm->OutStreamer.AddComment("CIE Augmentation");
3556 Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
3557 Asm->EmitULEB128(1, "CIE Code Alignment Factor");
3558 Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
3559 Asm->OutStreamer.AddComment("CIE RA Column");
3560 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3561 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3563 std::vector<MachineMove> Moves;
3564 RI->getInitialFrameState(Moves);
3566 Asm->EmitFrameMoves(Moves, 0, false);
3568 Asm->EmitAlignment(2);
3569 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
3572 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
3575 emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3576 if (!Asm->MAI->doesDwarfRequireFrameSection())
3579 // Start the dwarf frame section.
3580 Asm->OutStreamer.SwitchSection(
3581 Asm->getObjFileLowering().getDwarfFrameSection());
3583 Asm->OutStreamer.AddComment("Length of Frame Information Entry");
3584 MCSymbol *DebugFrameBegin =
3585 Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
3586 MCSymbol *DebugFrameEnd =
3587 Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
3588 Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
3590 Asm->OutStreamer.EmitLabel(DebugFrameBegin);
3592 Asm->OutStreamer.AddComment("FDE CIE offset");
3593 Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
3594 DwarfFrameSectionSym);
3596 Asm->OutStreamer.AddComment("FDE initial location");
3597 MCSymbol *FuncBeginSym =
3598 Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
3599 Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
3600 Asm->getTargetData().getPointerSize(),
3604 Asm->OutStreamer.AddComment("FDE address range");
3605 Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
3606 FuncBeginSym, Asm->getTargetData().getPointerSize());
3608 Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
3610 Asm->EmitAlignment(2);
3611 Asm->OutStreamer.EmitLabel(DebugFrameEnd);
3614 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
3616 void DwarfDebug::emitDebugPubNames() {
3617 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3618 E = CUMap.end(); I != E; ++I) {
3619 CompileUnit *TheCU = I->second;
3620 // Start the dwarf pubnames section.
3621 Asm->OutStreamer.SwitchSection(
3622 Asm->getObjFileLowering().getDwarfPubNamesSection());
3624 Asm->OutStreamer.AddComment("Length of Public Names Info");
3625 Asm->EmitLabelDifference(
3626 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
3627 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
3629 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
3632 Asm->OutStreamer.AddComment("DWARF Version");
3633 Asm->EmitInt16(dwarf::DWARF_VERSION);
3635 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3636 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
3637 DwarfInfoSectionSym);
3639 Asm->OutStreamer.AddComment("Compilation Unit Length");
3640 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
3641 Asm->GetTempSymbol("info_begin", TheCU->getID()),
3644 const StringMap<DIE*> &Globals = TheCU->getGlobals();
3645 for (StringMap<DIE*>::const_iterator
3646 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3647 const char *Name = GI->getKeyData();
3648 DIE *Entity = GI->second;
3650 Asm->OutStreamer.AddComment("DIE offset");
3651 Asm->EmitInt32(Entity->getOffset());
3653 if (Asm->isVerbose())
3654 Asm->OutStreamer.AddComment("External Name");
3655 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
3658 Asm->OutStreamer.AddComment("End Mark");
3660 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
3665 void DwarfDebug::emitDebugPubTypes() {
3666 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3667 E = CUMap.end(); I != E; ++I) {
3668 CompileUnit *TheCU = I->second;
3669 // Start the dwarf pubnames section.
3670 Asm->OutStreamer.SwitchSection(
3671 Asm->getObjFileLowering().getDwarfPubTypesSection());
3672 Asm->OutStreamer.AddComment("Length of Public Types Info");
3673 Asm->EmitLabelDifference(
3674 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
3675 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
3677 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
3680 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
3681 Asm->EmitInt16(dwarf::DWARF_VERSION);
3683 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3684 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
3685 DwarfInfoSectionSym);
3687 Asm->OutStreamer.AddComment("Compilation Unit Length");
3688 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
3689 Asm->GetTempSymbol("info_begin", TheCU->getID()),
3692 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
3693 for (StringMap<DIE*>::const_iterator
3694 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3695 const char *Name = GI->getKeyData();
3696 DIE * Entity = GI->second;
3698 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3699 Asm->EmitInt32(Entity->getOffset());
3701 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
3702 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
3705 Asm->OutStreamer.AddComment("End Mark");
3707 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
3712 /// emitDebugStr - Emit visible names into a debug str section.
3714 void DwarfDebug::emitDebugStr() {
3715 // Check to see if it is worth the effort.
3716 if (StringPool.empty()) return;
3718 // Start the dwarf str section.
3719 Asm->OutStreamer.SwitchSection(
3720 Asm->getObjFileLowering().getDwarfStrSection());
3722 // Get all of the string pool entries and put them in an array by their ID so
3723 // we can sort them.
3724 SmallVector<std::pair<unsigned,
3725 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
3727 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
3728 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
3729 Entries.push_back(std::make_pair(I->second.second, &*I));
3731 array_pod_sort(Entries.begin(), Entries.end());
3733 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
3734 // Emit a label for reference from debug information entries.
3735 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
3737 // Emit the string itself.
3738 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
3742 /// emitDebugLoc - Emit visible names into a debug loc section.
3744 void DwarfDebug::emitDebugLoc() {
3745 if (DotDebugLocEntries.empty())
3748 // Start the dwarf loc section.
3749 Asm->OutStreamer.SwitchSection(
3750 Asm->getObjFileLowering().getDwarfLocSection());
3751 unsigned char Size = Asm->getTargetData().getPointerSize();
3752 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
3754 for (SmallVector<DotDebugLocEntry, 4>::iterator
3755 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
3756 I != E; ++I, ++index) {
3757 DotDebugLocEntry Entry = *I;
3758 if (Entry.isEmpty()) {
3759 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3760 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3761 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
3763 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
3764 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
3765 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3766 unsigned Reg = RI->getDwarfRegNum(Entry.Loc.getReg(), false);
3767 if (int Offset = Entry.Loc.getOffset()) {
3768 // If the value is at a certain offset from frame register then
3770 unsigned OffsetSize = Offset ? MCAsmInfo::getSLEB128Size(Offset) : 1;
3771 Asm->OutStreamer.AddComment("Loc expr size");
3772 Asm->EmitInt16(1 + OffsetSize);
3773 Asm->OutStreamer.AddComment(
3774 dwarf::OperationEncodingString(dwarf::DW_OP_fbreg));
3775 Asm->EmitInt8(dwarf::DW_OP_fbreg);
3776 Asm->OutStreamer.AddComment("Offset");
3777 Asm->EmitSLEB128(Offset);
3780 Asm->OutStreamer.AddComment("Loc expr size");
3782 Asm->OutStreamer.AddComment(
3783 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
3784 Asm->EmitInt8(dwarf::DW_OP_reg0 + Reg);
3786 Asm->OutStreamer.AddComment("Loc expr size");
3787 Asm->EmitInt16(1 + MCAsmInfo::getULEB128Size(Reg));
3788 Asm->EmitInt8(dwarf::DW_OP_regx);
3789 Asm->EmitULEB128(Reg);
3796 /// EmitDebugARanges - Emit visible names into a debug aranges section.
3798 void DwarfDebug::EmitDebugARanges() {
3799 // Start the dwarf aranges section.
3800 Asm->OutStreamer.SwitchSection(
3801 Asm->getObjFileLowering().getDwarfARangesSection());
3804 /// emitDebugRanges - Emit visible names into a debug ranges section.
3806 void DwarfDebug::emitDebugRanges() {
3807 // Start the dwarf ranges section.
3808 Asm->OutStreamer.SwitchSection(
3809 Asm->getObjFileLowering().getDwarfRangesSection());
3810 unsigned char Size = Asm->getTargetData().getPointerSize();
3811 for (SmallVector<const MCSymbol *, 8>::iterator
3812 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
3815 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
3817 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3821 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
3823 void DwarfDebug::emitDebugMacInfo() {
3824 if (const MCSection *LineInfo =
3825 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
3826 // Start the dwarf macinfo section.
3827 Asm->OutStreamer.SwitchSection(LineInfo);
3831 /// emitDebugInlineInfo - Emit inline info using following format.
3833 /// 1. length of section
3834 /// 2. Dwarf version number
3835 /// 3. address size.
3837 /// Entries (one "entry" for each function that was inlined):
3839 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
3840 /// otherwise offset into __debug_str for regular function name.
3841 /// 2. offset into __debug_str section for regular function name.
3842 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
3843 /// instances for the function.
3845 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
3846 /// inlined instance; the die_offset points to the inlined_subroutine die in the
3847 /// __debug_info section, and the low_pc is the starting address for the
3848 /// inlining instance.
3849 void DwarfDebug::emitDebugInlineInfo() {
3850 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
3856 Asm->OutStreamer.SwitchSection(
3857 Asm->getObjFileLowering().getDwarfDebugInlineSection());
3859 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
3860 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
3861 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
3863 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
3865 Asm->OutStreamer.AddComment("Dwarf Version");
3866 Asm->EmitInt16(dwarf::DWARF_VERSION);
3867 Asm->OutStreamer.AddComment("Address Size (in bytes)");
3868 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3870 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3871 E = InlinedSPNodes.end(); I != E; ++I) {
3873 const MDNode *Node = *I;
3874 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3875 = InlineInfo.find(Node);
3876 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3877 DISubprogram SP(Node);
3878 StringRef LName = SP.getLinkageName();
3879 StringRef Name = SP.getName();
3881 Asm->OutStreamer.AddComment("MIPS linkage name");
3882 if (LName.empty()) {
3883 Asm->OutStreamer.EmitBytes(Name, 0);
3884 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
3886 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
3887 DwarfStrSectionSym);
3889 Asm->OutStreamer.AddComment("Function name");
3890 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
3891 Asm->EmitULEB128(Labels.size(), "Inline count");
3893 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3894 LE = Labels.end(); LI != LE; ++LI) {
3895 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3896 Asm->EmitInt32(LI->second->getOffset());
3898 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
3899 Asm->OutStreamer.EmitSymbolValue(LI->first,
3900 Asm->getTargetData().getPointerSize(),0);
3904 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));