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 //===----------------------------------------------------------------------===//
13 #define DEBUG_TYPE "dwarfdebug"
14 #include "DwarfDebug.h"
15 #include "llvm/Module.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineModuleInfo.h"
18 #include "llvm/MC/MCSection.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetFrameInfo.h"
23 #include "llvm/Target/TargetLoweringObjectFile.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/Mangler.h"
29 #include "llvm/Support/Timer.h"
30 #include "llvm/System/Path.h"
33 static TimerGroup &getDwarfTimerGroup() {
34 static TimerGroup DwarfTimerGroup("Dwarf Debugging");
35 return DwarfTimerGroup;
38 //===----------------------------------------------------------------------===//
40 /// Configuration values for initial hash set sizes (log2).
42 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
46 //===----------------------------------------------------------------------===//
47 /// CompileUnit - This dwarf writer support class manages information associate
48 /// with a source file.
50 /// ID - File identifier for source.
54 /// Die - Compile unit debug information entry.
58 /// IndexTyDie - An anonymous type for index type.
61 /// GVToDieMap - Tracks the mapping of unit level debug informaton
62 /// variables to debug information entries.
63 /// FIXME : Rename GVToDieMap -> NodeToDieMap
64 ValueMap<MDNode *, DIE *> GVToDieMap;
66 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
67 /// descriptors to debug information entries using a DIEEntry proxy.
69 ValueMap<MDNode *, DIEEntry *> GVToDIEEntryMap;
71 /// Globals - A map of globally visible named entities for this unit.
73 StringMap<DIE*> Globals;
75 /// GlobalTypes - A map of globally visible types for this unit.
77 StringMap<DIE*> GlobalTypes;
80 CompileUnit(unsigned I, DIE *D)
81 : ID(I), CUDie(D), IndexTyDie(0) {}
82 ~CompileUnit() { delete CUDie; delete IndexTyDie; }
85 unsigned getID() const { return ID; }
86 DIE* getCUDie() const { return CUDie; }
87 const StringMap<DIE*> &getGlobals() const { return Globals; }
88 const StringMap<DIE*> &getGlobalTypes() const { return GlobalTypes; }
90 /// hasContent - Return true if this compile unit has something to write out.
92 bool hasContent() const { return !CUDie->getChildren().empty(); }
94 /// addGlobal - Add a new global entity to the compile unit.
96 void addGlobal(const std::string &Name, DIE *Die) { Globals[Name] = Die; }
98 /// addGlobalType - Add a new global type to the compile unit.
100 void addGlobalType(const std::string &Name, DIE *Die) {
101 GlobalTypes[Name] = Die;
104 /// getDIE - Returns the debug information entry map slot for the
105 /// specified debug variable.
106 DIE *getDIE(MDNode *N) { return GVToDieMap.lookup(N); }
108 /// insertDIE - Insert DIE into the map.
109 void insertDIE(MDNode *N, DIE *D) {
110 GVToDieMap.insert(std::make_pair(N, D));
113 /// getDIEEntry - Returns the debug information entry for the speciefied
115 DIEEntry *getDIEEntry(MDNode *N) { return GVToDIEEntryMap.lookup(N); }
117 /// insertDIEEntry - Insert debug information entry into the map.
118 void insertDIEEntry(MDNode *N, DIEEntry *E) {
119 GVToDIEEntryMap.insert(std::make_pair(N, E));
122 /// addDie - Adds or interns the DIE to the compile unit.
124 void addDie(DIE *Buffer) {
125 this->CUDie->addChild(Buffer);
128 // getIndexTyDie - Get an anonymous type for index type.
129 DIE *getIndexTyDie() {
133 // setIndexTyDie - Set D as anonymous type for index which can be reused
135 void setIndexTyDie(DIE *D) {
141 //===----------------------------------------------------------------------===//
142 /// DbgVariable - This class is used to track local variable information.
145 DIVariable Var; // Variable Descriptor.
146 unsigned FrameIndex; // Variable frame index.
147 DbgVariable *AbstractVar; // Abstract variable for this variable.
150 DbgVariable(DIVariable V, unsigned I)
151 : Var(V), FrameIndex(I), AbstractVar(0), TheDIE(0) {}
154 DIVariable getVariable() const { return Var; }
155 unsigned getFrameIndex() const { return FrameIndex; }
156 void setAbstractVariable(DbgVariable *V) { AbstractVar = V; }
157 DbgVariable *getAbstractVariable() const { return AbstractVar; }
158 void setDIE(DIE *D) { TheDIE = D; }
159 DIE *getDIE() const { return TheDIE; }
162 //===----------------------------------------------------------------------===//
163 /// DbgScope - This class is used to track scope information.
166 DbgScope *Parent; // Parent to this scope.
167 DIDescriptor Desc; // Debug info descriptor for scope.
168 WeakVH InlinedAtLocation; // Location at which scope is inlined.
169 bool AbstractScope; // Abstract Scope
170 unsigned StartLabelID; // Label ID of the beginning of scope.
171 unsigned EndLabelID; // Label ID of the end of scope.
172 const MachineInstr *LastInsn; // Last instruction of this scope.
173 const MachineInstr *FirstInsn; // First instruction of this scope.
174 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
175 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
177 // Private state for dump()
178 mutable unsigned IndentLevel;
180 DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0)
181 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
182 StartLabelID(0), EndLabelID(0),
183 LastInsn(0), FirstInsn(0), IndentLevel(0) {}
187 DbgScope *getParent() const { return Parent; }
188 void setParent(DbgScope *P) { Parent = P; }
189 DIDescriptor getDesc() const { return Desc; }
190 MDNode *getInlinedAt() const {
191 return dyn_cast_or_null<MDNode>(InlinedAtLocation);
193 MDNode *getScopeNode() const { return Desc.getNode(); }
194 unsigned getStartLabelID() const { return StartLabelID; }
195 unsigned getEndLabelID() const { return EndLabelID; }
196 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
197 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
198 void setStartLabelID(unsigned S) { StartLabelID = S; }
199 void setEndLabelID(unsigned E) { EndLabelID = E; }
200 void setLastInsn(const MachineInstr *MI) { LastInsn = MI; }
201 const MachineInstr *getLastInsn() { return LastInsn; }
202 void setFirstInsn(const MachineInstr *MI) { FirstInsn = MI; }
203 void setAbstractScope() { AbstractScope = true; }
204 bool isAbstractScope() const { return AbstractScope; }
205 const MachineInstr *getFirstInsn() { return FirstInsn; }
207 /// addScope - Add a scope to the scope.
209 void addScope(DbgScope *S) { Scopes.push_back(S); }
211 /// addVariable - Add a variable to the scope.
213 void addVariable(DbgVariable *V) { Variables.push_back(V); }
215 void fixInstructionMarkers() {
216 assert (getFirstInsn() && "First instruction is missing!");
220 // If a scope does not have an instruction to mark an end then use
221 // the end of last child scope.
222 SmallVector<DbgScope *, 4> &Scopes = getScopes();
223 assert (!Scopes.empty() && "Inner most scope does not have last insn!");
224 DbgScope *L = Scopes.back();
225 if (!L->getLastInsn())
226 L->fixInstructionMarkers();
227 setLastInsn(L->getLastInsn());
236 void DbgScope::dump() const {
237 raw_ostream &err = errs();
238 err.indent(IndentLevel);
239 MDNode *N = Desc.getNode();
241 err << " [" << StartLabelID << ", " << EndLabelID << "]\n";
243 err << "Abstract Scope\n";
247 err << "Children ...\n";
248 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
249 if (Scopes[i] != this)
256 DbgScope::~DbgScope() {
257 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
259 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
263 } // end llvm namespace
265 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T)
266 : Dwarf(OS, A, T, "dbg"), ModuleCU(0),
267 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
268 DIEValues(), StringPool(),
269 SectionSourceLines(), didInitial(false), shouldEmit(false),
270 CurrentFnDbgScope(0), DebugTimer(0) {
271 if (TimePassesIsEnabled)
272 DebugTimer = new Timer("Dwarf Debug Writer",
273 getDwarfTimerGroup());
275 DwarfDebug::~DwarfDebug() {
276 for (unsigned j = 0, M = DIEValues.size(); j < M; ++j)
282 /// assignAbbrevNumber - Define a unique number for the abbreviation.
284 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
285 // Profile the node so that we can make it unique.
289 // Check the set for priors.
290 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
292 // If it's newly added.
293 if (InSet == &Abbrev) {
294 // Add to abbreviation list.
295 Abbreviations.push_back(&Abbrev);
297 // Assign the vector position + 1 as its number.
298 Abbrev.setNumber(Abbreviations.size());
300 // Assign existing abbreviation number.
301 Abbrev.setNumber(InSet->getNumber());
305 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
306 /// information entry.
307 DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
308 DIEEntry *Value = new DIEEntry(Entry);
309 DIEValues.push_back(Value);
313 /// addUInt - Add an unsigned integer attribute data and value.
315 void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
316 unsigned Form, uint64_t Integer) {
317 if (!Form) Form = DIEInteger::BestForm(false, Integer);
318 DIEValue *Value = new DIEInteger(Integer);
319 DIEValues.push_back(Value);
320 Die->addValue(Attribute, Form, Value);
323 /// addSInt - Add an signed integer attribute data and value.
325 void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
326 unsigned Form, int64_t Integer) {
327 if (!Form) Form = DIEInteger::BestForm(true, Integer);
328 DIEValue *Value = new DIEInteger(Integer);
329 DIEValues.push_back(Value);
330 Die->addValue(Attribute, Form, Value);
333 /// addString - Add a string attribute data and value. DIEString only
334 /// keeps string reference.
335 void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
336 const StringRef String) {
337 DIEValue *Value = new DIEString(String);
338 DIEValues.push_back(Value);
339 Die->addValue(Attribute, Form, Value);
342 /// addLabel - Add a Dwarf label attribute data and value.
344 void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
345 const DWLabel &Label) {
346 DIEValue *Value = new DIEDwarfLabel(Label);
347 DIEValues.push_back(Value);
348 Die->addValue(Attribute, Form, Value);
351 /// addObjectLabel - Add an non-Dwarf label attribute data and value.
353 void DwarfDebug::addObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
354 const std::string &Label) {
355 DIEValue *Value = new DIEObjectLabel(Label);
356 DIEValues.push_back(Value);
357 Die->addValue(Attribute, Form, Value);
360 /// addSectionOffset - Add a section offset label attribute data and value.
362 void DwarfDebug::addSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
363 const DWLabel &Label, const DWLabel &Section,
364 bool isEH, bool useSet) {
365 DIEValue *Value = new DIESectionOffset(Label, Section, isEH, useSet);
366 DIEValues.push_back(Value);
367 Die->addValue(Attribute, Form, Value);
370 /// addDelta - Add a label delta attribute data and value.
372 void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
373 const DWLabel &Hi, const DWLabel &Lo) {
374 DIEValue *Value = new DIEDelta(Hi, Lo);
375 DIEValues.push_back(Value);
376 Die->addValue(Attribute, Form, Value);
379 /// addBlock - Add block data.
381 void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
383 Block->ComputeSize(TD);
384 DIEValues.push_back(Block);
385 Die->addValue(Attribute, Block->BestForm(), Block);
388 /// addSourceLine - Add location information to specified debug information
390 void DwarfDebug::addSourceLine(DIE *Die, const DIVariable *V) {
391 // If there is no compile unit specified, don't add a line #.
392 if (V->getCompileUnit().isNull())
395 unsigned Line = V->getLineNumber();
396 unsigned FileID = findCompileUnit(V->getCompileUnit()).getID();
397 assert(FileID && "Invalid file id");
398 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
399 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
402 /// addSourceLine - Add location information to specified debug information
404 void DwarfDebug::addSourceLine(DIE *Die, const DIGlobal *G) {
405 // If there is no compile unit specified, don't add a line #.
406 if (G->getCompileUnit().isNull())
409 unsigned Line = G->getLineNumber();
410 unsigned FileID = findCompileUnit(G->getCompileUnit()).getID();
411 assert(FileID && "Invalid file id");
412 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
413 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
416 /// addSourceLine - Add location information to specified debug information
418 void DwarfDebug::addSourceLine(DIE *Die, const DISubprogram *SP) {
419 // If there is no compile unit specified, don't add a line #.
420 if (SP->getCompileUnit().isNull())
422 // If the line number is 0, don't add it.
423 if (SP->getLineNumber() == 0)
427 unsigned Line = SP->getLineNumber();
428 unsigned FileID = findCompileUnit(SP->getCompileUnit()).getID();
429 assert(FileID && "Invalid file id");
430 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
431 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
434 /// addSourceLine - Add location information to specified debug information
436 void DwarfDebug::addSourceLine(DIE *Die, const DIType *Ty) {
437 // If there is no compile unit specified, don't add a line #.
438 DICompileUnit CU = Ty->getCompileUnit();
442 unsigned Line = Ty->getLineNumber();
443 unsigned FileID = findCompileUnit(CU).getID();
444 assert(FileID && "Invalid file id");
445 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
446 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
449 /// addSourceLine - Add location information to specified debug information
451 void DwarfDebug::addSourceLine(DIE *Die, const DINameSpace *NS) {
452 // If there is no compile unit specified, don't add a line #.
453 if (NS->getCompileUnit().isNull())
456 unsigned Line = NS->getLineNumber();
457 StringRef FN = NS->getFilename();
458 StringRef Dir = NS->getDirectory();
460 unsigned FileID = GetOrCreateSourceID(Dir, FN);
461 assert(FileID && "Invalid file id");
462 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
463 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
466 /* Byref variables, in Blocks, are declared by the programmer as
467 "SomeType VarName;", but the compiler creates a
468 __Block_byref_x_VarName struct, and gives the variable VarName
469 either the struct, or a pointer to the struct, as its type. This
470 is necessary for various behind-the-scenes things the compiler
471 needs to do with by-reference variables in blocks.
473 However, as far as the original *programmer* is concerned, the
474 variable should still have type 'SomeType', as originally declared.
476 The following function dives into the __Block_byref_x_VarName
477 struct to find the original type of the variable. This will be
478 passed back to the code generating the type for the Debug
479 Information Entry for the variable 'VarName'. 'VarName' will then
480 have the original type 'SomeType' in its debug information.
482 The original type 'SomeType' will be the type of the field named
483 'VarName' inside the __Block_byref_x_VarName struct.
485 NOTE: In order for this to not completely fail on the debugger
486 side, the Debug Information Entry for the variable VarName needs to
487 have a DW_AT_location that tells the debugger how to unwind through
488 the pointers and __Block_byref_x_VarName struct to find the actual
489 value of the variable. The function addBlockByrefType does this. */
491 /// Find the type the programmer originally declared the variable to be
492 /// and return that type.
494 DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) {
497 unsigned tag = Ty.getTag();
499 if (tag == dwarf::DW_TAG_pointer_type) {
500 DIDerivedType DTy = DIDerivedType(Ty.getNode());
501 subType = DTy.getTypeDerivedFrom();
504 DICompositeType blockStruct = DICompositeType(subType.getNode());
506 DIArray Elements = blockStruct.getTypeArray();
508 if (Elements.isNull())
511 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
512 DIDescriptor Element = Elements.getElement(i);
513 DIDerivedType DT = DIDerivedType(Element.getNode());
514 if (Name == DT.getName())
515 return (DT.getTypeDerivedFrom());
521 /// addComplexAddress - Start with the address based on the location provided,
522 /// and generate the DWARF information necessary to find the actual variable
523 /// given the extra address information encoded in the DIVariable, starting from
524 /// the starting location. Add the DWARF information to the die.
526 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
528 const MachineLocation &Location) {
529 const DIVariable &VD = DV->getVariable();
530 DIType Ty = VD.getType();
532 // Decode the original location, and use that as the start of the byref
533 // variable's location.
534 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
535 DIEBlock *Block = new DIEBlock();
537 if (Location.isReg()) {
539 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
541 Reg = Reg - dwarf::DW_OP_reg0;
542 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
543 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
547 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
549 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
550 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
553 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
556 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
557 uint64_t Element = VD.getAddrElement(i);
559 if (Element == DIFactory::OpPlus) {
560 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
561 addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
562 } else if (Element == DIFactory::OpDeref) {
563 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
564 } else llvm_unreachable("unknown DIFactory Opcode");
567 // Now attach the location information to the DIE.
568 addBlock(Die, Attribute, 0, Block);
571 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
572 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
573 gives the variable VarName either the struct, or a pointer to the struct, as
574 its type. This is necessary for various behind-the-scenes things the
575 compiler needs to do with by-reference variables in Blocks.
577 However, as far as the original *programmer* is concerned, the variable
578 should still have type 'SomeType', as originally declared.
580 The function getBlockByrefType dives into the __Block_byref_x_VarName
581 struct to find the original type of the variable, which is then assigned to
582 the variable's Debug Information Entry as its real type. So far, so good.
583 However now the debugger will expect the variable VarName to have the type
584 SomeType. So we need the location attribute for the variable to be an
585 expression that explains to the debugger how to navigate through the
586 pointers and struct to find the actual variable of type SomeType.
588 The following function does just that. We start by getting
589 the "normal" location for the variable. This will be the location
590 of either the struct __Block_byref_x_VarName or the pointer to the
591 struct __Block_byref_x_VarName.
593 The struct will look something like:
595 struct __Block_byref_x_VarName {
597 struct __Block_byref_x_VarName *forwarding;
598 ... <various other fields>
600 ... <maybe more fields>
603 If we are given the struct directly (as our starting point) we
604 need to tell the debugger to:
606 1). Add the offset of the forwarding field.
608 2). Follow that pointer to get the the real __Block_byref_x_VarName
609 struct to use (the real one may have been copied onto the heap).
611 3). Add the offset for the field VarName, to find the actual variable.
613 If we started with a pointer to the struct, then we need to
614 dereference that pointer first, before the other steps.
615 Translating this into DWARF ops, we will need to append the following
616 to the current location description for the variable:
618 DW_OP_deref -- optional, if we start with a pointer
619 DW_OP_plus_uconst <forward_fld_offset>
621 DW_OP_plus_uconst <varName_fld_offset>
623 That is what this function does. */
625 /// addBlockByrefAddress - Start with the address based on the location
626 /// provided, and generate the DWARF information necessary to find the
627 /// actual Block variable (navigating the Block struct) based on the
628 /// starting location. Add the DWARF information to the die. For
629 /// more information, read large comment just above here.
631 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
633 const MachineLocation &Location) {
634 const DIVariable &VD = DV->getVariable();
635 DIType Ty = VD.getType();
637 unsigned Tag = Ty.getTag();
638 bool isPointer = false;
640 StringRef varName = VD.getName();
642 if (Tag == dwarf::DW_TAG_pointer_type) {
643 DIDerivedType DTy = DIDerivedType(Ty.getNode());
644 TmpTy = DTy.getTypeDerivedFrom();
648 DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
650 // Find the __forwarding field and the variable field in the __Block_byref
652 DIArray Fields = blockStruct.getTypeArray();
653 DIDescriptor varField = DIDescriptor();
654 DIDescriptor forwardingField = DIDescriptor();
657 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
658 DIDescriptor Element = Fields.getElement(i);
659 DIDerivedType DT = DIDerivedType(Element.getNode());
660 StringRef fieldName = DT.getName();
661 if (fieldName == "__forwarding")
662 forwardingField = Element;
663 else if (fieldName == varName)
667 assert(!varField.isNull() && "Can't find byref variable in Block struct");
668 assert(!forwardingField.isNull()
669 && "Can't find forwarding field in Block struct");
671 // Get the offsets for the forwarding field and the variable field.
672 unsigned int forwardingFieldOffset =
673 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
674 unsigned int varFieldOffset =
675 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
677 // Decode the original location, and use that as the start of the byref
678 // variable's location.
679 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
680 DIEBlock *Block = new DIEBlock();
682 if (Location.isReg()) {
684 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
686 Reg = Reg - dwarf::DW_OP_reg0;
687 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
688 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
692 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
694 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
695 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
698 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
701 // If we started with a pointer to the __Block_byref... struct, then
702 // the first thing we need to do is dereference the pointer (DW_OP_deref).
704 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
706 // Next add the offset for the '__forwarding' field:
707 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
708 // adding the offset if it's 0.
709 if (forwardingFieldOffset > 0) {
710 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
711 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
714 // Now dereference the __forwarding field to get to the real __Block_byref
715 // struct: DW_OP_deref.
716 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
718 // Now that we've got the real __Block_byref... struct, add the offset
719 // for the variable's field to get to the location of the actual variable:
720 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
721 if (varFieldOffset > 0) {
722 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
723 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
726 // Now attach the location information to the DIE.
727 addBlock(Die, Attribute, 0, Block);
730 /// addAddress - Add an address attribute to a die based on the location
732 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
733 const MachineLocation &Location) {
734 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
735 DIEBlock *Block = new DIEBlock();
737 if (Location.isReg()) {
739 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
741 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
742 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
746 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
748 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
749 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
752 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
755 addBlock(Die, Attribute, 0, Block);
758 /// addType - Add a new type attribute to the specified entity.
759 void DwarfDebug::addType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
763 // Check for pre-existence.
764 DIEEntry *Entry = DW_Unit->getDIEEntry(Ty.getNode());
766 // If it exists then use the existing value.
768 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
773 Entry = createDIEEntry();
774 DW_Unit->insertDIEEntry(Ty.getNode(), Entry);
777 DIE *Buffer = new DIE(dwarf::DW_TAG_base_type);
778 ModuleCU->insertDIE(Ty.getNode(), Buffer);
779 if (Ty.isBasicType())
780 constructTypeDIE(DW_Unit, *Buffer, DIBasicType(Ty.getNode()));
781 else if (Ty.isCompositeType())
782 constructTypeDIE(DW_Unit, *Buffer, DICompositeType(Ty.getNode()));
784 assert(Ty.isDerivedType() && "Unknown kind of DIType");
785 constructTypeDIE(DW_Unit, *Buffer, DIDerivedType(Ty.getNode()));
788 // Add debug information entry to entity and appropriate context.
790 DIDescriptor Context = Ty.getContext();
791 if (!Context.isNull()) {
792 if (Context.isNameSpace()) {
793 DINameSpace NS(Context.getNode());
794 Die = getOrCreateNameSpace(NS);
796 Die = DW_Unit->getDIE(Context.getNode());
799 Die->addChild(Buffer);
801 DW_Unit->addDie(Buffer);
802 Entry->setEntry(Buffer);
803 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
806 /// constructTypeDIE - Construct basic type die from DIBasicType.
807 void DwarfDebug::constructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
809 // Get core information.
810 StringRef Name = BTy.getName();
811 Buffer.setTag(dwarf::DW_TAG_base_type);
812 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
815 // Add name if not anonymous or intermediate type.
817 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
818 uint64_t Size = BTy.getSizeInBits() >> 3;
819 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
822 /// constructTypeDIE - Construct derived type die from DIDerivedType.
823 void DwarfDebug::constructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
825 // Get core information.
826 StringRef Name = DTy.getName();
827 uint64_t Size = DTy.getSizeInBits() >> 3;
828 unsigned Tag = DTy.getTag();
830 // FIXME - Workaround for templates.
831 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
835 // Map to main type, void will not have a type.
836 DIType FromTy = DTy.getTypeDerivedFrom();
837 addType(DW_Unit, &Buffer, FromTy);
839 // Add name if not anonymous or intermediate type.
841 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
843 // Add size if non-zero (derived types might be zero-sized.)
845 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
847 // Add source line info if available and TyDesc is not a forward declaration.
848 if (!DTy.isForwardDecl())
849 addSourceLine(&Buffer, &DTy);
852 /// constructTypeDIE - Construct type DIE from DICompositeType.
853 void DwarfDebug::constructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
854 DICompositeType CTy) {
855 // Get core information.
856 StringRef Name = CTy.getName();
858 uint64_t Size = CTy.getSizeInBits() >> 3;
859 unsigned Tag = CTy.getTag();
863 case dwarf::DW_TAG_vector_type:
864 case dwarf::DW_TAG_array_type:
865 constructArrayTypeDIE(DW_Unit, Buffer, &CTy);
867 case dwarf::DW_TAG_enumeration_type: {
868 DIArray Elements = CTy.getTypeArray();
870 // Add enumerators to enumeration type.
871 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
873 DIEnumerator Enum(Elements.getElement(i).getNode());
874 if (!Enum.isNull()) {
875 ElemDie = constructEnumTypeDIE(DW_Unit, &Enum);
876 Buffer.addChild(ElemDie);
881 case dwarf::DW_TAG_subroutine_type: {
883 DIArray Elements = CTy.getTypeArray();
884 DIDescriptor RTy = Elements.getElement(0);
885 addType(DW_Unit, &Buffer, DIType(RTy.getNode()));
887 // Add prototype flag.
888 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
891 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
892 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
893 DIDescriptor Ty = Elements.getElement(i);
894 addType(DW_Unit, Arg, DIType(Ty.getNode()));
895 Buffer.addChild(Arg);
899 case dwarf::DW_TAG_structure_type:
900 case dwarf::DW_TAG_union_type:
901 case dwarf::DW_TAG_class_type: {
902 // Add elements to structure type.
903 DIArray Elements = CTy.getTypeArray();
905 // A forward struct declared type may not have elements available.
906 if (Elements.isNull())
909 // Add elements to structure type.
910 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
911 DIDescriptor Element = Elements.getElement(i);
912 if (Element.isNull())
915 if (Element.getTag() == dwarf::DW_TAG_subprogram)
916 ElemDie = createMemberSubprogramDIE(DW_Unit,
917 DISubprogram(Element.getNode()));
919 ElemDie = createMemberDIE(DW_Unit,
920 DIDerivedType(Element.getNode()));
921 Buffer.addChild(ElemDie);
924 if (CTy.isAppleBlockExtension())
925 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
927 unsigned RLang = CTy.getRunTimeLang();
929 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
930 dwarf::DW_FORM_data1, RLang);
937 // Add name if not anonymous or intermediate type.
939 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
941 if (Tag == dwarf::DW_TAG_enumeration_type ||
942 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
943 // Add size if non-zero (derived types might be zero-sized.)
945 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
947 // Add zero size if it is not a forward declaration.
948 if (CTy.isForwardDecl())
949 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
951 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
954 // Add source line info if available.
955 if (!CTy.isForwardDecl())
956 addSourceLine(&Buffer, &CTy);
960 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
961 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
962 int64_t L = SR.getLo();
963 int64_t H = SR.getHi();
964 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
966 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
968 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
969 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
971 Buffer.addChild(DW_Subrange);
974 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
975 void DwarfDebug::constructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
976 DICompositeType *CTy) {
977 Buffer.setTag(dwarf::DW_TAG_array_type);
978 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
979 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
981 // Emit derived type.
982 addType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
983 DIArray Elements = CTy->getTypeArray();
985 // Get an anonymous type for index type.
986 DIE *IdxTy = DW_Unit->getIndexTyDie();
988 // Construct an anonymous type for index type.
989 IdxTy = new DIE(dwarf::DW_TAG_base_type);
990 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
991 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
992 dwarf::DW_ATE_signed);
993 DW_Unit->addDie(IdxTy);
994 DW_Unit->setIndexTyDie(IdxTy);
997 // Add subranges to array type.
998 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
999 DIDescriptor Element = Elements.getElement(i);
1000 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1001 constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
1005 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1006 DIE *DwarfDebug::constructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
1007 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1008 StringRef Name = ETy->getName();
1009 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1010 int64_t Value = ETy->getEnumValue();
1011 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1015 /// createGlobalVariableDIE - Create new DIE using GV.
1016 DIE *DwarfDebug::createGlobalVariableDIE(CompileUnit *DW_Unit,
1017 const DIGlobalVariable &GV) {
1018 // If the global variable was optmized out then no need to create debug info
1020 if (!GV.getGlobal()) return NULL;
1021 if (GV.getDisplayName().empty()) return NULL;
1023 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1024 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1025 GV.getDisplayName());
1027 StringRef LinkageName = GV.getLinkageName();
1028 if (!LinkageName.empty()) {
1029 // Skip special LLVM prefix that is used to inform the asm printer to not
1030 // emit usual symbol prefix before the symbol name. This happens for
1031 // Objective-C symbol names and symbol whose name is replaced using GCC's
1032 // __asm__ attribute.
1033 if (LinkageName[0] == 1)
1034 LinkageName = LinkageName.substr(1);
1035 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1038 addType(DW_Unit, GVDie, GV.getType());
1039 if (!GV.isLocalToUnit())
1040 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1041 addSourceLine(GVDie, &GV);
1044 DIEBlock *Block = new DIEBlock();
1045 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1046 addObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1047 Asm->Mang->getMangledName(GV.getGlobal()));
1048 addBlock(GVDie, dwarf::DW_AT_location, 0, Block);
1053 /// createMemberDIE - Create new member DIE.
1054 DIE *DwarfDebug::createMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
1055 DIE *MemberDie = new DIE(DT.getTag());
1056 StringRef Name = DT.getName();
1058 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1060 addType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1062 addSourceLine(MemberDie, &DT);
1064 DIEBlock *MemLocationDie = new DIEBlock();
1065 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1067 uint64_t Size = DT.getSizeInBits();
1068 uint64_t FieldSize = DT.getOriginalTypeSize();
1070 if (Size != FieldSize) {
1072 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1073 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1075 uint64_t Offset = DT.getOffsetInBits();
1076 uint64_t FieldOffset = Offset;
1077 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1078 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1079 FieldOffset = (HiMark - FieldSize);
1080 Offset -= FieldOffset;
1082 // Maybe we need to work from the other end.
1083 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1084 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1086 // Here WD_AT_data_member_location points to the anonymous
1087 // field that includes this bit field.
1088 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1091 // This is not a bitfield.
1092 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1094 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1096 if (DT.isProtected())
1097 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1098 dwarf::DW_ACCESS_protected);
1099 else if (DT.isPrivate())
1100 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1101 dwarf::DW_ACCESS_private);
1102 else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1103 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1104 dwarf::DW_ACCESS_public);
1106 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1107 dwarf::DW_VIRTUALITY_virtual);
1111 /// createRawSubprogramDIE - Create new partially incomplete DIE. This is
1112 /// a helper routine used by createMemberSubprogramDIE and
1113 /// createSubprogramDIE.
1114 DIE *DwarfDebug::createRawSubprogramDIE(CompileUnit *DW_Unit,
1115 const DISubprogram &SP) {
1116 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
1117 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1119 StringRef LinkageName = SP.getLinkageName();
1120 if (!LinkageName.empty()) {
1121 // Skip special LLVM prefix that is used to inform the asm printer to not
1122 // emit usual symbol prefix before the symbol name. This happens for
1123 // Objective-C symbol names and symbol whose name is replaced using GCC's
1124 // __asm__ attribute.
1125 if (LinkageName[0] == 1)
1126 LinkageName = LinkageName.substr(1);
1127 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1130 addSourceLine(SPDie, &SP);
1132 // Add prototyped tag, if C or ObjC.
1133 unsigned Lang = SP.getCompileUnit().getLanguage();
1134 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1135 Lang == dwarf::DW_LANG_ObjC)
1136 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1139 DICompositeType SPTy = SP.getType();
1140 DIArray Args = SPTy.getTypeArray();
1141 unsigned SPTag = SPTy.getTag();
1143 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
1144 addType(DW_Unit, SPDie, SPTy);
1146 addType(DW_Unit, SPDie, DIType(Args.getElement(0).getNode()));
1148 unsigned VK = SP.getVirtuality();
1150 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1151 DIEBlock *Block = new DIEBlock();
1152 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1153 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1154 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1155 ContainingTypeMap.insert(std::make_pair(SPDie, WeakVH(SP.getContainingType().getNode())));
1161 /// createMemberSubprogramDIE - Create new member DIE using SP. This routine
1162 /// always returns a die with DW_AT_declaration attribute.
1163 DIE *DwarfDebug::createMemberSubprogramDIE(CompileUnit *DW_Unit,
1164 const DISubprogram &SP) {
1165 DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1167 SPDie = createSubprogramDIE(DW_Unit, SP);
1169 // If SPDie has DW_AT_declaration then reuse it.
1170 if (!SP.isDefinition())
1173 // Otherwise create new DIE for the declaration. First push definition
1174 // DIE at the top level.
1175 if (TopLevelDIEs.insert(SPDie))
1176 TopLevelDIEsVector.push_back(SPDie);
1178 SPDie = createRawSubprogramDIE(DW_Unit, SP);
1181 DICompositeType SPTy = SP.getType();
1182 DIArray Args = SPTy.getTypeArray();
1183 unsigned SPTag = SPTy.getTag();
1184 if (SPTag == dwarf::DW_TAG_subroutine_type)
1185 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1186 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1187 addType(DW_Unit, Arg, DIType(Args.getElement(i).getNode()));
1188 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1189 SPDie->addChild(Arg);
1192 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1196 /// createSubprogramDIE - Create new DIE using SP.
1197 DIE *DwarfDebug::createSubprogramDIE(CompileUnit *DW_Unit,
1198 const DISubprogram &SP) {
1199 DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1203 SPDie = createRawSubprogramDIE(DW_Unit, SP);
1205 if (!SP.isDefinition()) {
1206 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1208 // Add arguments. Do not add arguments for subprogram definition. They will
1209 // be handled while processing variables.
1210 DICompositeType SPTy = SP.getType();
1211 DIArray Args = SPTy.getTypeArray();
1212 unsigned SPTag = SPTy.getTag();
1214 if (SPTag == dwarf::DW_TAG_subroutine_type)
1215 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1216 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1217 addType(DW_Unit, Arg, DIType(Args.getElement(i).getNode()));
1218 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1219 SPDie->addChild(Arg);
1223 // DW_TAG_inlined_subroutine may refer to this DIE.
1224 DW_Unit->insertDIE(SP.getNode(), SPDie);
1228 /// findCompileUnit - Get the compile unit for the given descriptor.
1230 CompileUnit &DwarfDebug::findCompileUnit(DICompileUnit Unit) const {
1231 DenseMap<Value *, CompileUnit *>::const_iterator I =
1232 CompileUnitMap.find(Unit.getNode());
1233 assert(I != CompileUnitMap.end() && "Missing compile unit.");
1237 /// createDbgScopeVariable - Create a new scope variable.
1239 DIE *DwarfDebug::createDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1240 // Get the descriptor.
1241 const DIVariable &VD = DV->getVariable();
1242 StringRef Name = VD.getName();
1246 // Translate tag to proper Dwarf tag. The result variable is dropped for
1249 switch (VD.getTag()) {
1250 case dwarf::DW_TAG_return_variable:
1252 case dwarf::DW_TAG_arg_variable:
1253 Tag = dwarf::DW_TAG_formal_parameter;
1255 case dwarf::DW_TAG_auto_variable: // fall thru
1257 Tag = dwarf::DW_TAG_variable;
1261 // Define variable debug information entry.
1262 DIE *VariableDie = new DIE(Tag);
1263 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1265 // Add source line info if available.
1266 addSourceLine(VariableDie, &VD);
1268 // Add variable type.
1269 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1270 // addresses instead.
1271 if (VD.isBlockByrefVariable())
1272 addType(Unit, VariableDie, getBlockByrefType(VD.getType(), Name));
1274 addType(Unit, VariableDie, VD.getType());
1276 // Add variable address.
1277 // Variables for abstract instances of inlined functions don't get a
1279 MachineLocation Location;
1281 int Offset = RI->getFrameIndexReference(*MF, DV->getFrameIndex(), FrameReg);
1282 Location.set(FrameReg, Offset);
1285 if (VD.hasComplexAddress())
1286 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1287 else if (VD.isBlockByrefVariable())
1288 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1290 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1295 /// getUpdatedDbgScope - Find or create DbgScope assicated with the instruction.
1296 /// Initialize scope and update scope hierarchy.
1297 DbgScope *DwarfDebug::getUpdatedDbgScope(MDNode *N, const MachineInstr *MI,
1298 MDNode *InlinedAt) {
1299 assert (N && "Invalid Scope encoding!");
1300 assert (MI && "Missing machine instruction!");
1301 bool GetConcreteScope = (MI && InlinedAt);
1303 DbgScope *NScope = NULL;
1306 NScope = DbgScopeMap.lookup(InlinedAt);
1308 NScope = DbgScopeMap.lookup(N);
1309 assert (NScope && "Unable to find working scope!");
1311 if (NScope->getFirstInsn())
1314 DbgScope *Parent = NULL;
1315 if (GetConcreteScope) {
1316 DILocation IL(InlinedAt);
1317 Parent = getUpdatedDbgScope(IL.getScope().getNode(), MI,
1318 IL.getOrigLocation().getNode());
1319 assert (Parent && "Unable to find Parent scope!");
1320 NScope->setParent(Parent);
1321 Parent->addScope(NScope);
1322 } else if (DIDescriptor(N).isLexicalBlock()) {
1323 DILexicalBlock DB(N);
1324 if (!DB.getContext().isNull()) {
1325 Parent = getUpdatedDbgScope(DB.getContext().getNode(), MI, InlinedAt);
1326 NScope->setParent(Parent);
1327 Parent->addScope(NScope);
1331 NScope->setFirstInsn(MI);
1333 if (!Parent && !InlinedAt) {
1334 StringRef SPName = DISubprogram(N).getLinkageName();
1335 if (SPName == MF->getFunction()->getName())
1336 CurrentFnDbgScope = NScope;
1339 if (GetConcreteScope) {
1340 ConcreteScopes[InlinedAt] = NScope;
1341 getOrCreateAbstractScope(N);
1347 DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1348 assert (N && "Invalid Scope encoding!");
1350 DbgScope *AScope = AbstractScopes.lookup(N);
1354 DbgScope *Parent = NULL;
1356 DIDescriptor Scope(N);
1357 if (Scope.isLexicalBlock()) {
1358 DILexicalBlock DB(N);
1359 DIDescriptor ParentDesc = DB.getContext();
1360 if (!ParentDesc.isNull())
1361 Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1364 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1367 Parent->addScope(AScope);
1368 AScope->setAbstractScope();
1369 AbstractScopes[N] = AScope;
1370 if (DIDescriptor(N).isSubprogram())
1371 AbstractScopesList.push_back(AScope);
1375 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1376 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1377 /// If there are global variables in this scope then create and insert
1378 /// DIEs for these variables.
1379 DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
1381 DIE *SPDie = ModuleCU->getDIE(SPNode);
1382 assert (SPDie && "Unable to find subprogram DIE!");
1383 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1384 DWLabel("func_begin", SubprogramCount));
1385 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1386 DWLabel("func_end", SubprogramCount));
1387 MachineLocation Location(RI->getFrameRegister(*MF));
1388 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1390 if (!DISubprogram(SPNode).isLocalToUnit())
1391 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1393 // If there are global variables at this scope then add their dies.
1394 for (SmallVector<WeakVH, 4>::iterator SGI = ScopedGVs.begin(),
1395 SGE = ScopedGVs.end(); SGI != SGE; ++SGI) {
1396 MDNode *N = dyn_cast_or_null<MDNode>(*SGI);
1398 DIGlobalVariable GV(N);
1399 if (GV.getContext().getNode() == SPNode) {
1400 DIE *ScopedGVDie = createGlobalVariableDIE(ModuleCU, GV);
1402 SPDie->addChild(ScopedGVDie);
1409 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1410 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1411 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1412 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1413 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1415 // Ignore empty scopes.
1416 if (StartID == EndID && StartID != 0)
1419 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1420 if (Scope->isAbstractScope())
1423 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1425 DWLabel("label", StartID)
1426 : DWLabel("func_begin", SubprogramCount));
1427 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1429 DWLabel("label", EndID)
1430 : DWLabel("func_end", SubprogramCount));
1437 /// constructInlinedScopeDIE - This scope represents inlined body of
1438 /// a function. Construct DIE to represent this concrete inlined copy
1439 /// of the function.
1440 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1441 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1442 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1443 assert (StartID && "Invalid starting label for an inlined scope!");
1444 assert (EndID && "Invalid end label for an inlined scope!");
1445 // Ignore empty scopes.
1446 if (StartID == EndID && StartID != 0)
1449 DIScope DS(Scope->getScopeNode());
1452 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1454 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1455 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1456 assert (OriginDIE && "Unable to find Origin DIE!");
1457 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1458 dwarf::DW_FORM_ref4, OriginDIE);
1460 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1461 DWLabel("label", StartID));
1462 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1463 DWLabel("label", EndID));
1465 InlinedSubprogramDIEs.insert(OriginDIE);
1467 // Track the start label for this inlined function.
1468 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1469 I = InlineInfo.find(InlinedSP.getNode());
1471 if (I == InlineInfo.end()) {
1472 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartID,
1474 InlinedSPNodes.push_back(InlinedSP.getNode());
1476 I->second.push_back(std::make_pair(StartID, ScopeDIE));
1478 StringPool.insert(InlinedSP.getName());
1479 StringPool.insert(InlinedSP.getLinkageName());
1480 DILocation DL(Scope->getInlinedAt());
1481 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1482 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1488 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1489 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV,
1490 DbgScope *Scope, CompileUnit *Unit) {
1491 // Get the descriptor.
1492 const DIVariable &VD = DV->getVariable();
1493 StringRef Name = VD.getName();
1497 // Translate tag to proper Dwarf tag. The result variable is dropped for
1500 switch (VD.getTag()) {
1501 case dwarf::DW_TAG_return_variable:
1503 case dwarf::DW_TAG_arg_variable:
1504 Tag = dwarf::DW_TAG_formal_parameter;
1506 case dwarf::DW_TAG_auto_variable: // fall thru
1508 Tag = dwarf::DW_TAG_variable;
1512 // Define variable debug information entry.
1513 DIE *VariableDie = new DIE(Tag);
1517 if (DbgVariable *AV = DV->getAbstractVariable())
1518 AbsDIE = AV->getDIE();
1521 DIScope DS(Scope->getScopeNode());
1522 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1523 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1525 assert (OriginSPDIE && "Unable to find Origin DIE for the SP!");
1526 DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1527 assert (AbsDIE && "Unable to find Origin DIE for the Variable!");
1528 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1529 dwarf::DW_FORM_ref4, AbsDIE);
1532 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1533 addSourceLine(VariableDie, &VD);
1535 // Add variable type.
1536 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1537 // addresses instead.
1538 if (VD.isBlockByrefVariable())
1539 addType(Unit, VariableDie, getBlockByrefType(VD.getType(), Name));
1541 addType(Unit, VariableDie, VD.getType());
1544 // Add variable address.
1545 if (!Scope->isAbstractScope()) {
1546 MachineLocation Location;
1548 int Offset = RI->getFrameIndexReference(*MF, DV->getFrameIndex(), FrameReg);
1549 Location.set(FrameReg, Offset);
1551 if (VD.hasComplexAddress())
1552 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1553 else if (VD.isBlockByrefVariable())
1554 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1556 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1558 DV->setDIE(VariableDie);
1563 void DwarfDebug::addPubTypes(DISubprogram SP) {
1564 DICompositeType SPTy = SP.getType();
1565 unsigned SPTag = SPTy.getTag();
1566 if (SPTag != dwarf::DW_TAG_subroutine_type)
1569 DIArray Args = SPTy.getTypeArray();
1573 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1574 DIType ATy(Args.getElement(i).getNode());
1577 DICompositeType CATy = getDICompositeType(ATy);
1578 if (!CATy.isNull() && !CATy.getName().empty()) {
1579 if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode()))
1580 ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry());
1585 /// constructScopeDIE - Construct a DIE for this scope.
1586 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1589 DIScope DS(Scope->getScopeNode());
1593 DIE *ScopeDIE = NULL;
1594 if (Scope->getInlinedAt())
1595 ScopeDIE = constructInlinedScopeDIE(Scope);
1596 else if (DS.isSubprogram()) {
1597 if (Scope->isAbstractScope())
1598 ScopeDIE = ModuleCU->getDIE(DS.getNode());
1600 ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
1603 ScopeDIE = constructLexicalScopeDIE(Scope);
1604 if (!ScopeDIE) return NULL;
1607 // Add variables to scope.
1608 SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1609 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1610 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope, ModuleCU);
1612 ScopeDIE->addChild(VariableDIE);
1615 // Add nested scopes.
1616 SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1617 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1618 // Define the Scope debug information entry.
1619 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1621 ScopeDIE->addChild(NestedDIE);
1624 if (DS.isSubprogram())
1625 addPubTypes(DISubprogram(DS.getNode()));
1630 /// GetOrCreateSourceID - Look up the source id with the given directory and
1631 /// source file names. If none currently exists, create a new id and insert it
1632 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1634 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName) {
1636 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1637 if (DI != DirectoryIdMap.end()) {
1638 DId = DI->getValue();
1640 DId = DirectoryNames.size() + 1;
1641 DirectoryIdMap[DirName] = DId;
1642 DirectoryNames.push_back(DirName);
1646 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1647 if (FI != SourceFileIdMap.end()) {
1648 FId = FI->getValue();
1650 FId = SourceFileNames.size() + 1;
1651 SourceFileIdMap[FileName] = FId;
1652 SourceFileNames.push_back(FileName);
1655 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1656 SourceIdMap.find(std::make_pair(DId, FId));
1657 if (SI != SourceIdMap.end())
1660 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1661 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1662 SourceIds.push_back(std::make_pair(DId, FId));
1667 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1668 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace &NS) {
1669 DIE *NDie = ModuleCU->getDIE(NS.getNode());
1673 NDie = new DIE(dwarf::DW_TAG_namespace);
1674 ModuleCU->insertDIE(NS.getNode(), NDie);
1675 if (!NS.getName().empty())
1676 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1677 addSourceLine(NDie, &NS);
1678 DIDescriptor NSContext = NS.getContext();
1679 DIE *Context = NULL;
1680 if (NSContext.isNameSpace()) {
1681 DINameSpace NS2(NSContext.getNode());
1682 Context = getOrCreateNameSpace(NS2);
1685 Context = ModuleCU->getCUDie();
1686 Context->addChild(NDie);
1690 void DwarfDebug::constructCompileUnit(MDNode *N) {
1691 DICompileUnit DIUnit(N);
1692 StringRef FN = DIUnit.getFilename();
1693 StringRef Dir = DIUnit.getDirectory();
1694 unsigned ID = GetOrCreateSourceID(Dir, FN);
1696 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1697 addSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1698 DWLabel("section_line", 0), DWLabel("section_line", 0),
1700 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1701 DIUnit.getProducer());
1702 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1703 DIUnit.getLanguage());
1704 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1707 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1708 if (DIUnit.isOptimized())
1709 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1711 StringRef Flags = DIUnit.getFlags();
1713 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1715 unsigned RVer = DIUnit.getRunTimeVersion();
1717 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1718 dwarf::DW_FORM_data1, RVer);
1720 CompileUnit *Unit = new CompileUnit(ID, Die);
1721 if (!ModuleCU && DIUnit.isMain()) {
1722 // Use first compile unit marked as isMain as the compile unit
1727 CompileUnitMap[DIUnit.getNode()] = Unit;
1728 CompileUnits.push_back(Unit);
1731 void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
1732 DIGlobalVariable DI_GV(N);
1734 // If debug information is malformed then ignore it.
1735 if (DI_GV.Verify() == false)
1738 // Check for pre-existence.
1739 if (ModuleCU->getDIE(DI_GV.getNode()))
1742 DIE *VariableDie = createGlobalVariableDIE(ModuleCU, DI_GV);
1745 ModuleCU->insertDIE(N, VariableDie);
1747 // Add to context owner.
1748 if (TopLevelDIEs.insert(VariableDie))
1749 TopLevelDIEsVector.push_back(VariableDie);
1751 // Expose as global. FIXME - need to check external flag.
1752 ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1754 DIType GTy = DI_GV.getType();
1755 if (GTy.isCompositeType() && !GTy.getName().empty()) {
1756 DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode());
1757 assert (Entry && "Missing global type!");
1758 ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry());
1763 void DwarfDebug::constructSubprogramDIE(MDNode *N) {
1766 // Check for pre-existence.
1767 if (ModuleCU->getDIE(N))
1770 if (!SP.isDefinition())
1771 // This is a method declaration which will be handled while constructing
1775 DIE *SubprogramDie = createSubprogramDIE(ModuleCU, SP);
1778 ModuleCU->insertDIE(N, SubprogramDie);
1780 // Add to context owner.
1781 DIDescriptor SPContext = SP.getContext();
1782 if (SPContext.isCompileUnit()
1783 && SPContext.getNode() == SP.getCompileUnit().getNode()) {
1784 if (TopLevelDIEs.insert(SubprogramDie))
1785 TopLevelDIEsVector.push_back(SubprogramDie);
1786 } else if (SPContext.isNameSpace()) {
1787 DINameSpace NS(SPContext.getNode());
1788 DIE *NDie = getOrCreateNameSpace(NS);
1789 NDie->addChild(SubprogramDie);
1792 // Expose as global.
1793 ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1798 /// beginModule - Emit all Dwarf sections that should come prior to the
1799 /// content. Create global DIEs and emit initial debug info sections.
1800 /// This is inovked by the target AsmPrinter.
1801 void DwarfDebug::beginModule(Module *M, MachineModuleInfo *mmi) {
1804 if (TimePassesIsEnabled)
1805 DebugTimer->startTimer();
1807 if (!MAI->doesSupportDebugInformation())
1810 DebugInfoFinder DbgFinder;
1811 DbgFinder.processModule(*M);
1813 // Create all the compile unit DIEs.
1814 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1815 E = DbgFinder.compile_unit_end(); I != E; ++I)
1816 constructCompileUnit(*I);
1818 if (CompileUnits.empty()) {
1819 if (TimePassesIsEnabled)
1820 DebugTimer->stopTimer();
1825 // If main compile unit for this module is not seen than randomly
1826 // select first compile unit.
1828 ModuleCU = CompileUnits[0];
1830 // Create DIEs for each of the externally visible global variables.
1831 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1832 E = DbgFinder.global_variable_end(); I != E; ++I) {
1833 DIGlobalVariable GV(*I);
1834 DIDescriptor GVContext = GV.getContext();
1835 if (GVContext.isCompileUnit()
1836 && GVContext.getNode() == GV.getCompileUnit().getNode())
1837 constructGlobalVariableDIE(*I);
1838 else if (GVContext.isNameSpace()) {
1839 DIE *GVDie = createGlobalVariableDIE(ModuleCU, GV);
1840 DINameSpace NS(GVContext.getNode());
1841 DIE *NDie = getOrCreateNameSpace(NS);
1842 NDie->addChild(GVDie);
1845 ScopedGVs.push_back(*I);
1848 // Create DIEs for each subprogram.
1849 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1850 E = DbgFinder.subprogram_end(); I != E; ++I)
1851 constructSubprogramDIE(*I);
1855 MMI->setDebugInfoAvailability(true);
1857 // Prime section data.
1858 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1860 // Print out .file directives to specify files for .loc directives. These are
1861 // printed out early so that they precede any .loc directives.
1862 if (MAI->hasDotLocAndDotFile()) {
1863 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1864 // Remember source id starts at 1.
1865 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1866 sys::Path FullPath(getSourceDirectoryName(Id.first));
1868 FullPath.appendComponent(getSourceFileName(Id.second));
1869 assert(AppendOk && "Could not append filename to directory!");
1871 Asm->EmitFile(i, FullPath.str());
1876 // Emit initial sections
1879 if (TimePassesIsEnabled)
1880 DebugTimer->stopTimer();
1883 /// endModule - Emit all Dwarf sections that should come after the content.
1885 void DwarfDebug::endModule() {
1889 if (TimePassesIsEnabled)
1890 DebugTimer->startTimer();
1892 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1893 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1894 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1896 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1899 // Insert top level DIEs.
1900 for (SmallVector<DIE *, 4>::iterator TI = TopLevelDIEsVector.begin(),
1901 TE = TopLevelDIEsVector.end(); TI != TE; ++TI)
1902 ModuleCU->getCUDie()->addChild(*TI);
1904 for (DenseMap<DIE *, WeakVH>::iterator CI = ContainingTypeMap.begin(),
1905 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1906 DIE *SPDie = CI->first;
1907 MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1909 DIE *NDie = ModuleCU->getDIE(N);
1910 if (!NDie) continue;
1911 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1912 addDIEEntry(NDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1915 // Standard sections final addresses.
1916 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1917 EmitLabel("text_end", 0);
1918 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1919 EmitLabel("data_end", 0);
1921 // End text sections.
1922 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1923 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1924 EmitLabel("section_end", i);
1927 // Emit common frame information.
1928 emitCommonDebugFrame();
1930 // Emit function debug frame information
1931 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1932 E = DebugFrames.end(); I != E; ++I)
1933 emitFunctionDebugFrame(*I);
1935 // Compute DIE offsets and sizes.
1936 computeSizeAndOffsets();
1938 // Emit all the DIEs into a debug info section
1941 // Corresponding abbreviations into a abbrev section.
1942 emitAbbreviations();
1944 // Emit source line correspondence into a debug line section.
1947 // Emit info into a debug pubnames section.
1948 emitDebugPubNames();
1950 // Emit info into a debug pubtypes section.
1951 emitDebugPubTypes();
1953 // Emit info into a debug str section.
1956 // Emit info into a debug loc section.
1959 // Emit info into a debug aranges section.
1962 // Emit info into a debug ranges section.
1965 // Emit info into a debug macinfo section.
1968 // Emit inline info.
1969 emitDebugInlineInfo();
1971 if (TimePassesIsEnabled)
1972 DebugTimer->stopTimer();
1975 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
1976 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
1978 DILocation &ScopeLoc) {
1980 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
1982 return AbsDbgVariable;
1984 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope().getNode());
1988 AbsDbgVariable = new DbgVariable(Var, FrameIdx);
1989 Scope->addVariable(AbsDbgVariable);
1990 AbstractVariables[Var.getNode()] = AbsDbgVariable;
1991 return AbsDbgVariable;
1994 /// collectVariableInfo - Populate DbgScope entries with variables' info.
1995 void DwarfDebug::collectVariableInfo() {
1998 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1999 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
2000 VE = VMap.end(); VI != VE; ++VI) {
2001 MetadataBase *MB = VI->first;
2002 MDNode *Var = dyn_cast_or_null<MDNode>(MB);
2004 DIVariable DV (Var);
2005 std::pair< unsigned, MDNode *> VP = VI->second;
2006 DILocation ScopeLoc(VP.second);
2009 ConcreteScopes.lookup(ScopeLoc.getOrigLocation().getNode());
2011 Scope = DbgScopeMap.lookup(ScopeLoc.getScope().getNode());
2012 // If variable scope is not found then skip this variable.
2016 DbgVariable *RegVar = new DbgVariable(DV, VP.first);
2017 Scope->addVariable(RegVar);
2018 if (DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first,
2020 RegVar->setAbstractVariable(AbsDbgVariable);
2024 /// beginScope - Process beginning of a scope starting at Label.
2025 void DwarfDebug::beginScope(const MachineInstr *MI, unsigned Label) {
2026 InsnToDbgScopeMapTy::iterator I = DbgScopeBeginMap.find(MI);
2027 if (I == DbgScopeBeginMap.end())
2029 ScopeVector &SD = I->second;
2030 for (ScopeVector::iterator SDI = SD.begin(), SDE = SD.end();
2032 (*SDI)->setStartLabelID(Label);
2035 /// endScope - Process end of a scope.
2036 void DwarfDebug::endScope(const MachineInstr *MI) {
2037 InsnToDbgScopeMapTy::iterator I = DbgScopeEndMap.find(MI);
2038 if (I == DbgScopeEndMap.end())
2041 unsigned Label = MMI->NextLabelID();
2042 Asm->printLabel(Label);
2045 SmallVector<DbgScope *, 2> &SD = I->second;
2046 for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
2048 (*SDI)->setEndLabelID(Label);
2052 /// createDbgScope - Create DbgScope for the scope.
2053 void DwarfDebug::createDbgScope(MDNode *Scope, MDNode *InlinedAt) {
2056 DbgScope *WScope = DbgScopeMap.lookup(Scope);
2059 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2060 DbgScopeMap.insert(std::make_pair(Scope, WScope));
2061 if (DIDescriptor(Scope).isLexicalBlock())
2062 createDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
2066 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2070 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2071 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2072 DILocation DL(InlinedAt);
2073 createDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
2076 /// extractScopeInformation - Scan machine instructions in this function
2077 /// and collect DbgScopes. Return true, if atleast one scope was found.
2078 bool DwarfDebug::extractScopeInformation(MachineFunction *MF) {
2079 // If scope information was extracted using .dbg intrinsics then there is not
2080 // any need to extract these information by scanning each instruction.
2081 if (!DbgScopeMap.empty())
2084 // Scan each instruction and create scopes. First build working set of scopes.
2085 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2087 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2089 const MachineInstr *MInsn = II;
2090 DebugLoc DL = MInsn->getDebugLoc();
2091 if (DL.isUnknown()) continue;
2092 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
2093 if (!DLT.Scope) continue;
2094 // There is no need to create another DIE for compile unit. For all
2095 // other scopes, create one DbgScope now. This will be translated
2096 // into a scope DIE at the end.
2097 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
2098 createDbgScope(DLT.Scope, DLT.InlinedAtLoc);
2103 // Build scope hierarchy using working set of scopes.
2104 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2106 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2108 const MachineInstr *MInsn = II;
2109 DebugLoc DL = MInsn->getDebugLoc();
2110 if (DL.isUnknown()) continue;
2111 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
2112 if (!DLT.Scope) continue;
2113 // There is no need to create another DIE for compile unit. For all
2114 // other scopes, create one DbgScope now. This will be translated
2115 // into a scope DIE at the end.
2116 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
2117 DbgScope *Scope = getUpdatedDbgScope(DLT.Scope, MInsn, DLT.InlinedAtLoc);
2118 Scope->setLastInsn(MInsn);
2122 // If a scope's last instruction is not set then use its child scope's
2123 // last instruction as this scope's last instrunction.
2124 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
2125 DE = DbgScopeMap.end(); DI != DE; ++DI) {
2126 if (DI->second->isAbstractScope())
2128 assert (DI->second->getFirstInsn() && "Invalid first instruction!");
2129 DI->second->fixInstructionMarkers();
2130 assert (DI->second->getLastInsn() && "Invalid last instruction!");
2133 // Each scope has first instruction and last instruction to mark beginning
2134 // and end of a scope respectively. Create an inverse map that list scopes
2135 // starts (and ends) with an instruction. One instruction may start (or end)
2137 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
2138 DE = DbgScopeMap.end(); DI != DE; ++DI) {
2139 DbgScope *S = DI->second;
2140 if (S->isAbstractScope())
2142 const MachineInstr *MI = S->getFirstInsn();
2143 assert (MI && "DbgScope does not have first instruction!");
2145 InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI);
2146 if (IDI != DbgScopeBeginMap.end())
2147 IDI->second.push_back(S);
2149 DbgScopeBeginMap[MI].push_back(S);
2151 MI = S->getLastInsn();
2152 assert (MI && "DbgScope does not have last instruction!");
2153 IDI = DbgScopeEndMap.find(MI);
2154 if (IDI != DbgScopeEndMap.end())
2155 IDI->second.push_back(S);
2157 DbgScopeEndMap[MI].push_back(S);
2160 return !DbgScopeMap.empty();
2163 /// beginFunction - Gather pre-function debug information. Assumes being
2164 /// emitted immediately after the function entry point.
2165 void DwarfDebug::beginFunction(MachineFunction *MF) {
2168 if (!ShouldEmitDwarfDebug()) return;
2170 if (TimePassesIsEnabled)
2171 DebugTimer->startTimer();
2173 if (!extractScopeInformation(MF))
2176 collectVariableInfo();
2178 // Begin accumulating function debug information.
2179 MMI->BeginFunction(MF);
2181 // Assumes in correct section after the entry point.
2182 EmitLabel("func_begin", ++SubprogramCount);
2184 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2186 DebugLoc FDL = MF->getDefaultDebugLoc();
2187 if (!FDL.isUnknown()) {
2188 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
2189 unsigned LabelID = 0;
2190 DISubprogram SP = getDISubprogram(DLT.Scope);
2192 LabelID = recordSourceLine(SP.getLineNumber(), 0, DLT.Scope);
2194 LabelID = recordSourceLine(DLT.Line, DLT.Col, DLT.Scope);
2195 Asm->printLabel(LabelID);
2198 if (TimePassesIsEnabled)
2199 DebugTimer->stopTimer();
2202 /// endFunction - Gather and emit post-function debug information.
2204 void DwarfDebug::endFunction(MachineFunction *MF) {
2205 if (!ShouldEmitDwarfDebug()) return;
2207 if (TimePassesIsEnabled)
2208 DebugTimer->startTimer();
2210 if (DbgScopeMap.empty())
2213 // Define end label for subprogram.
2214 EmitLabel("func_end", SubprogramCount);
2216 // Get function line info.
2217 if (!Lines.empty()) {
2218 // Get section line info.
2219 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2220 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2221 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2222 // Append the function info to section info.
2223 SectionLineInfos.insert(SectionLineInfos.end(),
2224 Lines.begin(), Lines.end());
2227 // Construct abstract scopes.
2228 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2229 AE = AbstractScopesList.end(); AI != AE; ++AI)
2230 constructScopeDIE(*AI);
2232 constructScopeDIE(CurrentFnDbgScope);
2234 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2235 MMI->getFrameMoves()));
2238 CurrentFnDbgScope = NULL;
2239 DbgScopeMap.clear();
2240 DbgScopeBeginMap.clear();
2241 DbgScopeEndMap.clear();
2242 ConcreteScopes.clear();
2243 AbstractScopesList.clear();
2247 if (TimePassesIsEnabled)
2248 DebugTimer->stopTimer();
2251 /// recordSourceLine - Records location information and associates it with a
2252 /// label. Returns a unique label ID used to generate a label and provide
2253 /// correspondence to the source line list.
2254 unsigned DwarfDebug::recordSourceLine(unsigned Line, unsigned Col,
2259 if (TimePassesIsEnabled)
2260 DebugTimer->startTimer();
2265 DIDescriptor Scope(S);
2266 if (Scope.isCompileUnit()) {
2267 DICompileUnit CU(S);
2268 Dir = CU.getDirectory();
2269 Fn = CU.getFilename();
2270 } else if (Scope.isSubprogram()) {
2272 Dir = SP.getDirectory();
2273 Fn = SP.getFilename();
2274 } else if (Scope.isLexicalBlock()) {
2275 DILexicalBlock DB(S);
2276 Dir = DB.getDirectory();
2277 Fn = DB.getFilename();
2279 assert (0 && "Unexpected scope info");
2281 unsigned Src = GetOrCreateSourceID(Dir, Fn);
2282 unsigned ID = MMI->NextLabelID();
2283 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2285 if (TimePassesIsEnabled)
2286 DebugTimer->stopTimer();
2291 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2292 /// timed. Look up the source id with the given directory and source file
2293 /// names. If none currently exists, create a new id and insert it in the
2294 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2296 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2297 const std::string &FileName) {
2298 if (TimePassesIsEnabled)
2299 DebugTimer->startTimer();
2301 unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str());
2303 if (TimePassesIsEnabled)
2304 DebugTimer->stopTimer();
2309 //===----------------------------------------------------------------------===//
2311 //===----------------------------------------------------------------------===//
2313 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2316 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2317 // Get the children.
2318 const std::vector<DIE *> &Children = Die->getChildren();
2320 // If not last sibling and has children then add sibling offset attribute.
2321 if (!Last && !Children.empty()) Die->addSiblingOffset();
2323 // Record the abbreviation.
2324 assignAbbrevNumber(Die->getAbbrev());
2326 // Get the abbreviation for this DIE.
2327 unsigned AbbrevNumber = Die->getAbbrevNumber();
2328 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2331 Die->setOffset(Offset);
2333 // Start the size with the size of abbreviation code.
2334 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2336 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2337 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2339 // Size the DIE attribute values.
2340 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2341 // Size attribute value.
2342 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
2344 // Size the DIE children if any.
2345 if (!Children.empty()) {
2346 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2347 "Children flag not set");
2349 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2350 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2352 // End of children marker.
2353 Offset += sizeof(int8_t);
2356 Die->setSize(Offset - Die->getOffset());
2360 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2362 void DwarfDebug::computeSizeAndOffsets() {
2363 // Compute size of compile unit header.
2364 static unsigned Offset =
2365 sizeof(int32_t) + // Length of Compilation Unit Info
2366 sizeof(int16_t) + // DWARF version number
2367 sizeof(int32_t) + // Offset Into Abbrev. Section
2368 sizeof(int8_t); // Pointer Size (in bytes)
2370 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2371 CompileUnitOffsets[ModuleCU] = 0;
2374 /// emitInitial - Emit initial Dwarf declarations. This is necessary for cc
2375 /// tools to recognize the object file contains Dwarf information.
2376 void DwarfDebug::emitInitial() {
2377 // Check to see if we already emitted intial headers.
2378 if (didInitial) return;
2381 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2383 // Dwarf sections base addresses.
2384 if (MAI->doesDwarfRequireFrameSection()) {
2385 Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
2386 EmitLabel("section_debug_frame", 0);
2389 Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
2390 EmitLabel("section_info", 0);
2391 Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
2392 EmitLabel("section_abbrev", 0);
2393 Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
2394 EmitLabel("section_aranges", 0);
2396 if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
2397 Asm->OutStreamer.SwitchSection(LineInfoDirective);
2398 EmitLabel("section_macinfo", 0);
2401 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
2402 EmitLabel("section_line", 0);
2403 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
2404 EmitLabel("section_loc", 0);
2405 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
2406 EmitLabel("section_pubnames", 0);
2407 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubTypesSection());
2408 EmitLabel("section_pubtypes", 0);
2409 Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
2410 EmitLabel("section_str", 0);
2411 Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
2412 EmitLabel("section_ranges", 0);
2414 Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
2415 EmitLabel("text_begin", 0);
2416 Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
2417 EmitLabel("data_begin", 0);
2420 /// emitDIE - Recusively Emits a debug information entry.
2422 void DwarfDebug::emitDIE(DIE *Die) {
2423 // Get the abbreviation for this DIE.
2424 unsigned AbbrevNumber = Die->getAbbrevNumber();
2425 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2429 // Emit the code (index) for the abbreviation.
2430 Asm->EmitULEB128Bytes(AbbrevNumber);
2432 if (Asm->isVerbose())
2433 Asm->EOL(std::string("Abbrev [" +
2434 utostr(AbbrevNumber) +
2435 "] 0x" + utohexstr(Die->getOffset()) +
2436 ":0x" + utohexstr(Die->getSize()) + " " +
2437 dwarf::TagString(Abbrev->getTag())));
2441 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2442 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2444 // Emit the DIE attribute values.
2445 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2446 unsigned Attr = AbbrevData[i].getAttribute();
2447 unsigned Form = AbbrevData[i].getForm();
2448 assert(Form && "Too many attributes for DIE (check abbreviation)");
2451 case dwarf::DW_AT_sibling:
2452 Asm->EmitInt32(Die->getSiblingOffset());
2454 case dwarf::DW_AT_abstract_origin: {
2455 DIEEntry *E = cast<DIEEntry>(Values[i]);
2456 DIE *Origin = E->getEntry();
2457 unsigned Addr = Origin->getOffset();
2458 Asm->EmitInt32(Addr);
2462 // Emit an attribute using the defined form.
2463 Values[i]->EmitValue(this, Form);
2467 Asm->EOL(dwarf::AttributeString(Attr));
2470 // Emit the DIE children if any.
2471 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2472 const std::vector<DIE *> &Children = Die->getChildren();
2474 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2475 emitDIE(Children[j]);
2477 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2481 /// emitDebugInfo / emitDebugInfoPerCU - Emit the debug info section.
2483 void DwarfDebug::emitDebugInfoPerCU(CompileUnit *Unit) {
2484 DIE *Die = Unit->getCUDie();
2486 // Emit the compile units header.
2487 EmitLabel("info_begin", Unit->getID());
2489 // Emit size of content not including length itself
2490 unsigned ContentSize = Die->getSize() +
2491 sizeof(int16_t) + // DWARF version number
2492 sizeof(int32_t) + // Offset Into Abbrev. Section
2493 sizeof(int8_t) + // Pointer Size (in bytes)
2494 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2496 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2497 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2498 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2499 Asm->EOL("Offset Into Abbrev. Section");
2500 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2503 // FIXME - extra padding for gdb bug.
2504 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2505 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2506 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2507 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2508 EmitLabel("info_end", Unit->getID());
2513 void DwarfDebug::emitDebugInfo() {
2514 // Start debug info section.
2515 Asm->OutStreamer.SwitchSection(
2516 Asm->getObjFileLowering().getDwarfInfoSection());
2518 emitDebugInfoPerCU(ModuleCU);
2521 /// emitAbbreviations - Emit the abbreviation section.
2523 void DwarfDebug::emitAbbreviations() const {
2524 // Check to see if it is worth the effort.
2525 if (!Abbreviations.empty()) {
2526 // Start the debug abbrev section.
2527 Asm->OutStreamer.SwitchSection(
2528 Asm->getObjFileLowering().getDwarfAbbrevSection());
2530 EmitLabel("abbrev_begin", 0);
2532 // For each abbrevation.
2533 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2534 // Get abbreviation data
2535 const DIEAbbrev *Abbrev = Abbreviations[i];
2537 // Emit the abbrevations code (base 1 index.)
2538 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2539 Asm->EOL("Abbreviation Code");
2541 // Emit the abbreviations data.
2547 // Mark end of abbreviations.
2548 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2550 EmitLabel("abbrev_end", 0);
2555 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2556 /// the line matrix.
2558 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2559 // Define last address of section.
2560 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2561 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2562 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2563 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2565 // Mark end of matrix.
2566 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2567 Asm->EmitULEB128Bytes(1); Asm->EOL();
2568 Asm->EmitInt8(1); Asm->EOL();
2571 /// emitDebugLines - Emit source line information.
2573 void DwarfDebug::emitDebugLines() {
2574 // If the target is using .loc/.file, the assembler will be emitting the
2575 // .debug_line table automatically.
2576 if (MAI->hasDotLocAndDotFile())
2579 // Minimum line delta, thus ranging from -10..(255-10).
2580 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2581 // Maximum line delta, thus ranging from -10..(255-10).
2582 const int MaxLineDelta = 255 + MinLineDelta;
2584 // Start the dwarf line section.
2585 Asm->OutStreamer.SwitchSection(
2586 Asm->getObjFileLowering().getDwarfLineSection());
2588 // Construct the section header.
2589 EmitDifference("line_end", 0, "line_begin", 0, true);
2590 Asm->EOL("Length of Source Line Info");
2591 EmitLabel("line_begin", 0);
2593 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2595 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2596 Asm->EOL("Prolog Length");
2597 EmitLabel("line_prolog_begin", 0);
2599 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2601 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2603 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2605 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2607 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2609 // Line number standard opcode encodings argument count
2610 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2611 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2612 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2613 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2614 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2615 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2616 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2617 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2618 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2620 // Emit directories.
2621 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2622 Asm->EmitString(getSourceDirectoryName(DI));
2623 Asm->EOL("Directory");
2626 Asm->EmitInt8(0); Asm->EOL("End of directories");
2629 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2630 // Remember source id starts at 1.
2631 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2632 Asm->EmitString(getSourceFileName(Id.second));
2634 Asm->EmitULEB128Bytes(Id.first);
2635 Asm->EOL("Directory #");
2636 Asm->EmitULEB128Bytes(0);
2637 Asm->EOL("Mod date");
2638 Asm->EmitULEB128Bytes(0);
2639 Asm->EOL("File size");
2642 Asm->EmitInt8(0); Asm->EOL("End of files");
2644 EmitLabel("line_prolog_end", 0);
2646 // A sequence for each text section.
2647 unsigned SecSrcLinesSize = SectionSourceLines.size();
2649 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2650 // Isolate current sections line info.
2651 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2653 /*if (Asm->isVerbose()) {
2654 const MCSection *S = SectionMap[j + 1];
2655 O << '\t' << MAI->getCommentString() << " Section"
2656 << S->getName() << '\n';
2660 // Dwarf assumes we start with first line of first source file.
2661 unsigned Source = 1;
2664 // Construct rows of the address, source, line, column matrix.
2665 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2666 const SrcLineInfo &LineInfo = LineInfos[i];
2667 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2668 if (!LabelID) continue;
2670 if (LineInfo.getLine() == 0) continue;
2672 if (!Asm->isVerbose())
2675 std::pair<unsigned, unsigned> SourceID =
2676 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2677 O << '\t' << MAI->getCommentString() << ' '
2678 << getSourceDirectoryName(SourceID.first) << '/'
2679 << getSourceFileName(SourceID.second)
2680 << ':' << utostr_32(LineInfo.getLine()) << '\n';
2683 // Define the line address.
2684 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2685 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2686 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2687 EmitReference("label", LabelID); Asm->EOL("Location label");
2689 // If change of source, then switch to the new source.
2690 if (Source != LineInfo.getSourceID()) {
2691 Source = LineInfo.getSourceID();
2692 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2693 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2696 // If change of line.
2697 if (Line != LineInfo.getLine()) {
2698 // Determine offset.
2699 int Offset = LineInfo.getLine() - Line;
2700 int Delta = Offset - MinLineDelta;
2703 Line = LineInfo.getLine();
2705 // If delta is small enough and in range...
2706 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2707 // ... then use fast opcode.
2708 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2710 // ... otherwise use long hand.
2711 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2712 Asm->EOL("DW_LNS_advance_line");
2713 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2714 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2717 // Copy the previous row (different address or source)
2718 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2722 emitEndOfLineMatrix(j + 1);
2725 if (SecSrcLinesSize == 0)
2726 // Because we're emitting a debug_line section, we still need a line
2727 // table. The linker and friends expect it to exist. If there's nothing to
2728 // put into it, emit an empty table.
2729 emitEndOfLineMatrix(1);
2731 EmitLabel("line_end", 0);
2735 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
2737 void DwarfDebug::emitCommonDebugFrame() {
2738 if (!MAI->doesDwarfRequireFrameSection())
2742 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2743 TargetFrameInfo::StackGrowsUp ?
2744 TD->getPointerSize() : -TD->getPointerSize();
2746 // Start the dwarf frame section.
2747 Asm->OutStreamer.SwitchSection(
2748 Asm->getObjFileLowering().getDwarfFrameSection());
2750 EmitLabel("debug_frame_common", 0);
2751 EmitDifference("debug_frame_common_end", 0,
2752 "debug_frame_common_begin", 0, true);
2753 Asm->EOL("Length of Common Information Entry");
2755 EmitLabel("debug_frame_common_begin", 0);
2756 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2757 Asm->EOL("CIE Identifier Tag");
2758 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2759 Asm->EOL("CIE Version");
2760 Asm->EmitString("");
2761 Asm->EOL("CIE Augmentation");
2762 Asm->EmitULEB128Bytes(1);
2763 Asm->EOL("CIE Code Alignment Factor");
2764 Asm->EmitSLEB128Bytes(stackGrowth);
2765 Asm->EOL("CIE Data Alignment Factor");
2766 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2767 Asm->EOL("CIE RA Column");
2769 std::vector<MachineMove> Moves;
2770 RI->getInitialFrameState(Moves);
2772 EmitFrameMoves(NULL, 0, Moves, false);
2774 Asm->EmitAlignment(2, 0, 0, false);
2775 EmitLabel("debug_frame_common_end", 0);
2780 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
2783 DwarfDebug::emitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2784 if (!MAI->doesDwarfRequireFrameSection())
2787 // Start the dwarf frame section.
2788 Asm->OutStreamer.SwitchSection(
2789 Asm->getObjFileLowering().getDwarfFrameSection());
2791 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2792 "debug_frame_begin", DebugFrameInfo.Number, true);
2793 Asm->EOL("Length of Frame Information Entry");
2795 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2797 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2799 Asm->EOL("FDE CIE offset");
2801 EmitReference("func_begin", DebugFrameInfo.Number);
2802 Asm->EOL("FDE initial location");
2803 EmitDifference("func_end", DebugFrameInfo.Number,
2804 "func_begin", DebugFrameInfo.Number);
2805 Asm->EOL("FDE address range");
2807 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2810 Asm->EmitAlignment(2, 0, 0, false);
2811 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2816 void DwarfDebug::emitDebugPubNamesPerCU(CompileUnit *Unit) {
2817 EmitDifference("pubnames_end", Unit->getID(),
2818 "pubnames_begin", Unit->getID(), true);
2819 Asm->EOL("Length of Public Names Info");
2821 EmitLabel("pubnames_begin", Unit->getID());
2823 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2825 EmitSectionOffset("info_begin", "section_info",
2826 Unit->getID(), 0, true, false);
2827 Asm->EOL("Offset of Compilation Unit Info");
2829 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2831 Asm->EOL("Compilation Unit Length");
2833 const StringMap<DIE*> &Globals = Unit->getGlobals();
2834 for (StringMap<DIE*>::const_iterator
2835 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2836 const char *Name = GI->getKeyData();
2837 DIE * Entity = GI->second;
2839 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2840 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2843 Asm->EmitInt32(0); Asm->EOL("End Mark");
2844 EmitLabel("pubnames_end", Unit->getID());
2849 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2851 void DwarfDebug::emitDebugPubNames() {
2852 // Start the dwarf pubnames section.
2853 Asm->OutStreamer.SwitchSection(
2854 Asm->getObjFileLowering().getDwarfPubNamesSection());
2856 emitDebugPubNamesPerCU(ModuleCU);
2859 void DwarfDebug::emitDebugPubTypes() {
2860 // Start the dwarf pubnames section.
2861 Asm->OutStreamer.SwitchSection(
2862 Asm->getObjFileLowering().getDwarfPubTypesSection());
2863 EmitDifference("pubtypes_end", ModuleCU->getID(),
2864 "pubtypes_begin", ModuleCU->getID(), true);
2865 Asm->EOL("Length of Public Types Info");
2867 EmitLabel("pubtypes_begin", ModuleCU->getID());
2869 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2871 EmitSectionOffset("info_begin", "section_info",
2872 ModuleCU->getID(), 0, true, false);
2873 Asm->EOL("Offset of Compilation ModuleCU Info");
2875 EmitDifference("info_end", ModuleCU->getID(), "info_begin", ModuleCU->getID(),
2877 Asm->EOL("Compilation ModuleCU Length");
2879 const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
2880 for (StringMap<DIE*>::const_iterator
2881 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2882 const char *Name = GI->getKeyData();
2883 DIE * Entity = GI->second;
2885 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2886 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2889 Asm->EmitInt32(0); Asm->EOL("End Mark");
2890 EmitLabel("pubtypes_end", ModuleCU->getID());
2895 /// emitDebugStr - Emit visible names into a debug str section.
2897 void DwarfDebug::emitDebugStr() {
2898 // Check to see if it is worth the effort.
2899 if (!StringPool.empty()) {
2900 // Start the dwarf str section.
2901 Asm->OutStreamer.SwitchSection(
2902 Asm->getObjFileLowering().getDwarfStrSection());
2904 // For each of strings in the string pool.
2905 for (unsigned StringID = 1, N = StringPool.size();
2906 StringID <= N; ++StringID) {
2907 // Emit a label for reference from debug information entries.
2908 EmitLabel("string", StringID);
2910 // Emit the string itself.
2911 const std::string &String = StringPool[StringID];
2912 Asm->EmitString(String); Asm->EOL();
2919 /// emitDebugLoc - Emit visible names into a debug loc section.
2921 void DwarfDebug::emitDebugLoc() {
2922 // Start the dwarf loc section.
2923 Asm->OutStreamer.SwitchSection(
2924 Asm->getObjFileLowering().getDwarfLocSection());
2928 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2930 void DwarfDebug::EmitDebugARanges() {
2931 // Start the dwarf aranges section.
2932 Asm->OutStreamer.SwitchSection(
2933 Asm->getObjFileLowering().getDwarfARangesSection());
2937 CompileUnit *Unit = GetBaseCompileUnit();
2939 // Don't include size of length
2940 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2942 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2944 EmitReference("info_begin", Unit->getID());
2945 Asm->EOL("Offset of Compilation Unit Info");
2947 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2949 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2951 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2952 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2955 EmitReference("text_begin", 0); Asm->EOL("Address");
2956 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2958 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2959 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2965 /// emitDebugRanges - Emit visible names into a debug ranges section.
2967 void DwarfDebug::emitDebugRanges() {
2968 // Start the dwarf ranges section.
2969 Asm->OutStreamer.SwitchSection(
2970 Asm->getObjFileLowering().getDwarfRangesSection());
2974 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2976 void DwarfDebug::emitDebugMacInfo() {
2977 if (const MCSection *LineInfo =
2978 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2979 // Start the dwarf macinfo section.
2980 Asm->OutStreamer.SwitchSection(LineInfo);
2985 /// emitDebugInlineInfo - Emit inline info using following format.
2987 /// 1. length of section
2988 /// 2. Dwarf version number
2989 /// 3. address size.
2991 /// Entries (one "entry" for each function that was inlined):
2993 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2994 /// otherwise offset into __debug_str for regular function name.
2995 /// 2. offset into __debug_str section for regular function name.
2996 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2997 /// instances for the function.
2999 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
3000 /// inlined instance; the die_offset points to the inlined_subroutine die in the
3001 /// __debug_info section, and the low_pc is the starting address for the
3002 /// inlining instance.
3003 void DwarfDebug::emitDebugInlineInfo() {
3004 if (!MAI->doesDwarfUsesInlineInfoSection())
3010 Asm->OutStreamer.SwitchSection(
3011 Asm->getObjFileLowering().getDwarfDebugInlineSection());
3013 EmitDifference("debug_inlined_end", 1,
3014 "debug_inlined_begin", 1, true);
3015 Asm->EOL("Length of Debug Inlined Information Entry");
3017 EmitLabel("debug_inlined_begin", 1);
3019 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
3020 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
3022 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3023 E = InlinedSPNodes.end(); I != E; ++I) {
3025 // for (ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
3026 // I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
3028 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3029 = InlineInfo.find(Node);
3030 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3031 DISubprogram SP(Node);
3032 StringRef LName = SP.getLinkageName();
3033 StringRef Name = SP.getName();
3036 Asm->EmitString(Name);
3038 // Skip special LLVM prefix that is used to inform the asm printer to not
3039 // emit usual symbol prefix before the symbol name. This happens for
3040 // Objective-C symbol names and symbol whose name is replaced using GCC's
3041 // __asm__ attribute.
3043 LName = LName.substr(1);
3044 // Asm->EmitString(LName);
3045 EmitSectionOffset("string", "section_str",
3046 StringPool.idFor(LName), false, true);
3049 Asm->EOL("MIPS linkage name");
3050 // Asm->EmitString(Name);
3051 EmitSectionOffset("string", "section_str",
3052 StringPool.idFor(Name), false, true);
3053 Asm->EOL("Function name");
3054 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
3056 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3057 LE = Labels.end(); LI != LE; ++LI) {
3058 DIE *SP = LI->second;
3059 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
3061 if (TD->getPointerSize() == sizeof(int32_t))
3062 O << MAI->getData32bitsDirective();
3064 O << MAI->getData64bitsDirective();
3066 PrintLabelName("label", LI->first); Asm->EOL("low_pc");
3070 EmitLabel("debug_inlined_end", 1);