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) {
116 ValueMap<MDNode *, DIEEntry *>::iterator I = GVToDIEEntryMap.find(N);
117 if (I == GVToDIEEntryMap.end())
122 /// insertDIEEntry - Insert debug information entry into the map.
123 void insertDIEEntry(MDNode *N, DIEEntry *E) {
124 GVToDIEEntryMap.insert(std::make_pair(N, E));
127 /// addDie - Adds or interns the DIE to the compile unit.
129 void addDie(DIE *Buffer) {
130 this->CUDie->addChild(Buffer);
133 // getIndexTyDie - Get an anonymous type for index type.
134 DIE *getIndexTyDie() {
138 // setIndexTyDie - Set D as anonymous type for index which can be reused
140 void setIndexTyDie(DIE *D) {
146 //===----------------------------------------------------------------------===//
147 /// DbgVariable - This class is used to track local variable information.
150 DIVariable Var; // Variable Descriptor.
151 unsigned FrameIndex; // Variable frame index.
152 DbgVariable *AbstractVar; // Abstract variable for this variable.
155 DbgVariable(DIVariable V, unsigned I)
156 : Var(V), FrameIndex(I), AbstractVar(0), TheDIE(0) {}
159 DIVariable getVariable() const { return Var; }
160 unsigned getFrameIndex() const { return FrameIndex; }
161 void setAbstractVariable(DbgVariable *V) { AbstractVar = V; }
162 DbgVariable *getAbstractVariable() const { return AbstractVar; }
163 void setDIE(DIE *D) { TheDIE = D; }
164 DIE *getDIE() const { return TheDIE; }
167 //===----------------------------------------------------------------------===//
168 /// DbgScope - This class is used to track scope information.
171 DbgScope *Parent; // Parent to this scope.
172 DIDescriptor Desc; // Debug info descriptor for scope.
173 WeakVH InlinedAtLocation; // Location at which scope is inlined.
174 bool AbstractScope; // Abstract Scope
175 unsigned StartLabelID; // Label ID of the beginning of scope.
176 unsigned EndLabelID; // Label ID of the end of scope.
177 const MachineInstr *LastInsn; // Last instruction of this scope.
178 const MachineInstr *FirstInsn; // First instruction of this scope.
179 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
180 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
182 // Private state for dump()
183 mutable unsigned IndentLevel;
185 DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0)
186 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
187 StartLabelID(0), EndLabelID(0),
188 LastInsn(0), FirstInsn(0), IndentLevel(0) {}
192 DbgScope *getParent() const { return Parent; }
193 void setParent(DbgScope *P) { Parent = P; }
194 DIDescriptor getDesc() const { return Desc; }
195 MDNode *getInlinedAt() const {
196 return dyn_cast_or_null<MDNode>(InlinedAtLocation);
198 MDNode *getScopeNode() const { return Desc.getNode(); }
199 unsigned getStartLabelID() const { return StartLabelID; }
200 unsigned getEndLabelID() const { return EndLabelID; }
201 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
202 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
203 void setStartLabelID(unsigned S) { StartLabelID = S; }
204 void setEndLabelID(unsigned E) { EndLabelID = E; }
205 void setLastInsn(const MachineInstr *MI) { LastInsn = MI; }
206 const MachineInstr *getLastInsn() { return LastInsn; }
207 void setFirstInsn(const MachineInstr *MI) { FirstInsn = MI; }
208 void setAbstractScope() { AbstractScope = true; }
209 bool isAbstractScope() const { return AbstractScope; }
210 const MachineInstr *getFirstInsn() { return FirstInsn; }
212 /// addScope - Add a scope to the scope.
214 void addScope(DbgScope *S) { Scopes.push_back(S); }
216 /// addVariable - Add a variable to the scope.
218 void addVariable(DbgVariable *V) { Variables.push_back(V); }
220 void fixInstructionMarkers() {
221 assert (getFirstInsn() && "First instruction is missing!");
225 // If a scope does not have an instruction to mark an end then use
226 // the end of last child scope.
227 SmallVector<DbgScope *, 4> &Scopes = getScopes();
228 assert (!Scopes.empty() && "Inner most scope does not have last insn!");
229 DbgScope *L = Scopes.back();
230 if (!L->getLastInsn())
231 L->fixInstructionMarkers();
232 setLastInsn(L->getLastInsn());
241 void DbgScope::dump() const {
242 raw_ostream &err = errs();
243 err.indent(IndentLevel);
244 MDNode *N = Desc.getNode();
246 err << " [" << StartLabelID << ", " << EndLabelID << "]\n";
248 err << "Abstract Scope\n";
252 err << "Children ...\n";
253 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
254 if (Scopes[i] != this)
261 DbgScope::~DbgScope() {
262 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
264 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
268 } // end llvm namespace
270 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T)
271 : Dwarf(OS, A, T, "dbg"), ModuleCU(0),
272 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
273 DIEValues(), StringPool(),
274 SectionSourceLines(), didInitial(false), shouldEmit(false),
275 CurrentFnDbgScope(0), DebugTimer(0) {
276 if (TimePassesIsEnabled)
277 DebugTimer = new Timer("Dwarf Debug Writer",
278 getDwarfTimerGroup());
280 DwarfDebug::~DwarfDebug() {
281 for (unsigned j = 0, M = DIEValues.size(); j < M; ++j)
287 /// assignAbbrevNumber - Define a unique number for the abbreviation.
289 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
290 // Profile the node so that we can make it unique.
294 // Check the set for priors.
295 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
297 // If it's newly added.
298 if (InSet == &Abbrev) {
299 // Add to abbreviation list.
300 Abbreviations.push_back(&Abbrev);
302 // Assign the vector position + 1 as its number.
303 Abbrev.setNumber(Abbreviations.size());
305 // Assign existing abbreviation number.
306 Abbrev.setNumber(InSet->getNumber());
310 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
311 /// information entry.
312 DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
313 DIEEntry *Value = new DIEEntry(Entry);
314 DIEValues.push_back(Value);
318 /// addUInt - Add an unsigned integer attribute data and value.
320 void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
321 unsigned Form, uint64_t Integer) {
322 if (!Form) Form = DIEInteger::BestForm(false, Integer);
323 DIEValue *Value = new DIEInteger(Integer);
324 DIEValues.push_back(Value);
325 Die->addValue(Attribute, Form, Value);
328 /// addSInt - Add an signed integer attribute data and value.
330 void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
331 unsigned Form, int64_t Integer) {
332 if (!Form) Form = DIEInteger::BestForm(true, Integer);
333 DIEValue *Value = new DIEInteger(Integer);
334 DIEValues.push_back(Value);
335 Die->addValue(Attribute, Form, Value);
338 /// addString - Add a string attribute data and value. DIEString only
339 /// keeps string reference.
340 void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
341 const StringRef String) {
342 DIEValue *Value = new DIEString(String);
343 DIEValues.push_back(Value);
344 Die->addValue(Attribute, Form, Value);
347 /// addLabel - Add a Dwarf label attribute data and value.
349 void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
350 const DWLabel &Label) {
351 DIEValue *Value = new DIEDwarfLabel(Label);
352 DIEValues.push_back(Value);
353 Die->addValue(Attribute, Form, Value);
356 /// addObjectLabel - Add an non-Dwarf label attribute data and value.
358 void DwarfDebug::addObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
359 const std::string &Label) {
360 DIEValue *Value = new DIEObjectLabel(Label);
361 DIEValues.push_back(Value);
362 Die->addValue(Attribute, Form, Value);
365 /// addSectionOffset - Add a section offset label attribute data and value.
367 void DwarfDebug::addSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
368 const DWLabel &Label, const DWLabel &Section,
369 bool isEH, bool useSet) {
370 DIEValue *Value = new DIESectionOffset(Label, Section, isEH, useSet);
371 DIEValues.push_back(Value);
372 Die->addValue(Attribute, Form, Value);
375 /// addDelta - Add a label delta attribute data and value.
377 void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
378 const DWLabel &Hi, const DWLabel &Lo) {
379 DIEValue *Value = new DIEDelta(Hi, Lo);
380 DIEValues.push_back(Value);
381 Die->addValue(Attribute, Form, Value);
384 /// addBlock - Add block data.
386 void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
388 Block->ComputeSize(TD);
389 DIEValues.push_back(Block);
390 Die->addValue(Attribute, Block->BestForm(), Block);
393 /// addSourceLine - Add location information to specified debug information
395 void DwarfDebug::addSourceLine(DIE *Die, const DIVariable *V) {
396 // If there is no compile unit specified, don't add a line #.
397 if (V->getCompileUnit().isNull())
400 unsigned Line = V->getLineNumber();
401 unsigned FileID = findCompileUnit(V->getCompileUnit())->getID();
402 assert(FileID && "Invalid file id");
403 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
404 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
407 /// addSourceLine - Add location information to specified debug information
409 void DwarfDebug::addSourceLine(DIE *Die, const DIGlobal *G) {
410 // If there is no compile unit specified, don't add a line #.
411 if (G->getCompileUnit().isNull())
414 unsigned Line = G->getLineNumber();
415 unsigned FileID = findCompileUnit(G->getCompileUnit())->getID();
416 assert(FileID && "Invalid file id");
417 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
418 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
421 /// addSourceLine - Add location information to specified debug information
423 void DwarfDebug::addSourceLine(DIE *Die, const DISubprogram *SP) {
424 // If there is no compile unit specified, don't add a line #.
425 if (SP->getCompileUnit().isNull())
427 // If the line number is 0, don't add it.
428 if (SP->getLineNumber() == 0)
432 unsigned Line = SP->getLineNumber();
433 unsigned FileID = findCompileUnit(SP->getCompileUnit())->getID();
434 assert(FileID && "Invalid file id");
435 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
436 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
439 /// addSourceLine - Add location information to specified debug information
441 void DwarfDebug::addSourceLine(DIE *Die, const DIType *Ty) {
442 // If there is no compile unit specified, don't add a line #.
443 DICompileUnit CU = Ty->getCompileUnit();
447 unsigned Line = Ty->getLineNumber();
448 unsigned FileID = findCompileUnit(CU)->getID();
449 assert(FileID && "Invalid file id");
450 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
451 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
454 /// addSourceLine - Add location information to specified debug information
456 void DwarfDebug::addSourceLine(DIE *Die, const DINameSpace *NS) {
457 // If there is no compile unit specified, don't add a line #.
458 if (NS->getCompileUnit().isNull())
461 unsigned Line = NS->getLineNumber();
462 StringRef FN = NS->getFilename();
463 StringRef Dir = NS->getDirectory();
465 unsigned FileID = GetOrCreateSourceID(Dir, FN);
466 assert(FileID && "Invalid file id");
467 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
468 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
471 /* Byref variables, in Blocks, are declared by the programmer as
472 "SomeType VarName;", but the compiler creates a
473 __Block_byref_x_VarName struct, and gives the variable VarName
474 either the struct, or a pointer to the struct, as its type. This
475 is necessary for various behind-the-scenes things the compiler
476 needs to do with by-reference variables in blocks.
478 However, as far as the original *programmer* is concerned, the
479 variable should still have type 'SomeType', as originally declared.
481 The following function dives into the __Block_byref_x_VarName
482 struct to find the original type of the variable. This will be
483 passed back to the code generating the type for the Debug
484 Information Entry for the variable 'VarName'. 'VarName' will then
485 have the original type 'SomeType' in its debug information.
487 The original type 'SomeType' will be the type of the field named
488 'VarName' inside the __Block_byref_x_VarName struct.
490 NOTE: In order for this to not completely fail on the debugger
491 side, the Debug Information Entry for the variable VarName needs to
492 have a DW_AT_location that tells the debugger how to unwind through
493 the pointers and __Block_byref_x_VarName struct to find the actual
494 value of the variable. The function addBlockByrefType does this. */
496 /// Find the type the programmer originally declared the variable to be
497 /// and return that type.
499 DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) {
502 unsigned tag = Ty.getTag();
504 if (tag == dwarf::DW_TAG_pointer_type) {
505 DIDerivedType DTy = DIDerivedType(Ty.getNode());
506 subType = DTy.getTypeDerivedFrom();
509 DICompositeType blockStruct = DICompositeType(subType.getNode());
511 DIArray Elements = blockStruct.getTypeArray();
513 if (Elements.isNull())
516 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
517 DIDescriptor Element = Elements.getElement(i);
518 DIDerivedType DT = DIDerivedType(Element.getNode());
519 if (Name == DT.getName())
520 return (DT.getTypeDerivedFrom());
526 /// addComplexAddress - Start with the address based on the location provided,
527 /// and generate the DWARF information necessary to find the actual variable
528 /// given the extra address information encoded in the DIVariable, starting from
529 /// the starting location. Add the DWARF information to the die.
531 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
533 const MachineLocation &Location) {
534 const DIVariable &VD = DV->getVariable();
535 DIType Ty = VD.getType();
537 // Decode the original location, and use that as the start of the byref
538 // variable's location.
539 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
540 DIEBlock *Block = new DIEBlock();
542 if (Location.isReg()) {
544 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
546 Reg = Reg - dwarf::DW_OP_reg0;
547 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
548 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
552 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
554 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
555 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
558 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
561 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
562 uint64_t Element = VD.getAddrElement(i);
564 if (Element == DIFactory::OpPlus) {
565 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
566 addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
567 } else if (Element == DIFactory::OpDeref) {
568 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
569 } else llvm_unreachable("unknown DIFactory Opcode");
572 // Now attach the location information to the DIE.
573 addBlock(Die, Attribute, 0, Block);
576 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
577 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
578 gives the variable VarName either the struct, or a pointer to the struct, as
579 its type. This is necessary for various behind-the-scenes things the
580 compiler needs to do with by-reference variables in Blocks.
582 However, as far as the original *programmer* is concerned, the variable
583 should still have type 'SomeType', as originally declared.
585 The function getBlockByrefType dives into the __Block_byref_x_VarName
586 struct to find the original type of the variable, which is then assigned to
587 the variable's Debug Information Entry as its real type. So far, so good.
588 However now the debugger will expect the variable VarName to have the type
589 SomeType. So we need the location attribute for the variable to be an
590 expression that explains to the debugger how to navigate through the
591 pointers and struct to find the actual variable of type SomeType.
593 The following function does just that. We start by getting
594 the "normal" location for the variable. This will be the location
595 of either the struct __Block_byref_x_VarName or the pointer to the
596 struct __Block_byref_x_VarName.
598 The struct will look something like:
600 struct __Block_byref_x_VarName {
602 struct __Block_byref_x_VarName *forwarding;
603 ... <various other fields>
605 ... <maybe more fields>
608 If we are given the struct directly (as our starting point) we
609 need to tell the debugger to:
611 1). Add the offset of the forwarding field.
613 2). Follow that pointer to get the the real __Block_byref_x_VarName
614 struct to use (the real one may have been copied onto the heap).
616 3). Add the offset for the field VarName, to find the actual variable.
618 If we started with a pointer to the struct, then we need to
619 dereference that pointer first, before the other steps.
620 Translating this into DWARF ops, we will need to append the following
621 to the current location description for the variable:
623 DW_OP_deref -- optional, if we start with a pointer
624 DW_OP_plus_uconst <forward_fld_offset>
626 DW_OP_plus_uconst <varName_fld_offset>
628 That is what this function does. */
630 /// addBlockByrefAddress - Start with the address based on the location
631 /// provided, and generate the DWARF information necessary to find the
632 /// actual Block variable (navigating the Block struct) based on the
633 /// starting location. Add the DWARF information to the die. For
634 /// more information, read large comment just above here.
636 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
638 const MachineLocation &Location) {
639 const DIVariable &VD = DV->getVariable();
640 DIType Ty = VD.getType();
642 unsigned Tag = Ty.getTag();
643 bool isPointer = false;
645 StringRef varName = VD.getName();
647 if (Tag == dwarf::DW_TAG_pointer_type) {
648 DIDerivedType DTy = DIDerivedType(Ty.getNode());
649 TmpTy = DTy.getTypeDerivedFrom();
653 DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
655 // Find the __forwarding field and the variable field in the __Block_byref
657 DIArray Fields = blockStruct.getTypeArray();
658 DIDescriptor varField = DIDescriptor();
659 DIDescriptor forwardingField = DIDescriptor();
662 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
663 DIDescriptor Element = Fields.getElement(i);
664 DIDerivedType DT = DIDerivedType(Element.getNode());
665 StringRef fieldName = DT.getName();
666 if (fieldName == "__forwarding")
667 forwardingField = Element;
668 else if (fieldName == varName)
672 assert(!varField.isNull() && "Can't find byref variable in Block struct");
673 assert(!forwardingField.isNull()
674 && "Can't find forwarding field in Block struct");
676 // Get the offsets for the forwarding field and the variable field.
677 unsigned int forwardingFieldOffset =
678 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
679 unsigned int varFieldOffset =
680 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
682 // Decode the original location, and use that as the start of the byref
683 // variable's location.
684 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
685 DIEBlock *Block = new DIEBlock();
687 if (Location.isReg()) {
689 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
691 Reg = Reg - dwarf::DW_OP_reg0;
692 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
693 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
697 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
699 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
700 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
703 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
706 // If we started with a pointer to the __Block_byref... struct, then
707 // the first thing we need to do is dereference the pointer (DW_OP_deref).
709 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
711 // Next add the offset for the '__forwarding' field:
712 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
713 // adding the offset if it's 0.
714 if (forwardingFieldOffset > 0) {
715 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
716 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
719 // Now dereference the __forwarding field to get to the real __Block_byref
720 // struct: DW_OP_deref.
721 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
723 // Now that we've got the real __Block_byref... struct, add the offset
724 // for the variable's field to get to the location of the actual variable:
725 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
726 if (varFieldOffset > 0) {
727 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
728 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
731 // Now attach the location information to the DIE.
732 addBlock(Die, Attribute, 0, Block);
735 /// addAddress - Add an address attribute to a die based on the location
737 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
738 const MachineLocation &Location) {
739 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
740 DIEBlock *Block = new DIEBlock();
742 if (Location.isReg()) {
744 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
746 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
747 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
751 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
753 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
754 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
757 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
760 addBlock(Die, Attribute, 0, Block);
763 /// addToContextOwner - Add Die into the list of its context owner's children.
764 void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
765 if (Context.isNull())
766 ModuleCU->addDie(Die);
767 else if (Context.isType()) {
768 DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context.getNode()));
769 ContextDIE->addChild(Die);
770 } else if (Context.isNameSpace()) {
771 DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context.getNode()));
772 ContextDIE->addChild(Die);
773 } else if (DIE *ContextDIE = ModuleCU->getDIE(Context.getNode()))
774 ContextDIE->addChild(Die);
776 ModuleCU->addDie(Die);
779 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
781 DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
782 DIE *TyDIE = ModuleCU->getDIE(Ty.getNode());
787 TyDIE = new DIE(dwarf::DW_TAG_base_type);
788 ModuleCU->insertDIE(Ty.getNode(), TyDIE);
789 if (Ty.isBasicType())
790 constructTypeDIE(*TyDIE, DIBasicType(Ty.getNode()));
791 else if (Ty.isCompositeType())
792 constructTypeDIE(*TyDIE, DICompositeType(Ty.getNode()));
794 assert(Ty.isDerivedType() && "Unknown kind of DIType");
795 constructTypeDIE(*TyDIE, DIDerivedType(Ty.getNode()));
798 addToContextOwner(TyDIE, Ty.getContext());
802 /// addType - Add a new type attribute to the specified entity.
803 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
807 // Check for pre-existence.
808 DIEEntry *Entry = ModuleCU->getDIEEntry(Ty.getNode());
809 // If it exists then use the existing value.
811 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
816 Entry = createDIEEntry();
817 ModuleCU->insertDIEEntry(Ty.getNode(), Entry);
820 DIE *Buffer = getOrCreateTypeDIE(Ty);
822 Entry->setEntry(Buffer);
823 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
826 /// constructTypeDIE - Construct basic type die from DIBasicType.
827 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
828 // Get core information.
829 StringRef Name = BTy.getName();
830 Buffer.setTag(dwarf::DW_TAG_base_type);
831 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
834 // Add name if not anonymous or intermediate type.
836 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
837 uint64_t Size = BTy.getSizeInBits() >> 3;
838 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
841 /// constructTypeDIE - Construct derived type die from DIDerivedType.
842 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
843 // Get core information.
844 StringRef Name = DTy.getName();
845 uint64_t Size = DTy.getSizeInBits() >> 3;
846 unsigned Tag = DTy.getTag();
848 // FIXME - Workaround for templates.
849 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
853 // Map to main type, void will not have a type.
854 DIType FromTy = DTy.getTypeDerivedFrom();
855 addType(&Buffer, FromTy);
857 // Add name if not anonymous or intermediate type.
859 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
861 // Add size if non-zero (derived types might be zero-sized.)
863 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
865 // Add source line info if available and TyDesc is not a forward declaration.
866 if (!DTy.isForwardDecl())
867 addSourceLine(&Buffer, &DTy);
870 /// constructTypeDIE - Construct type DIE from DICompositeType.
871 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
872 // Get core information.
873 StringRef Name = CTy.getName();
875 uint64_t Size = CTy.getSizeInBits() >> 3;
876 unsigned Tag = CTy.getTag();
880 case dwarf::DW_TAG_vector_type:
881 case dwarf::DW_TAG_array_type:
882 constructArrayTypeDIE(Buffer, &CTy);
884 case dwarf::DW_TAG_enumeration_type: {
885 DIArray Elements = CTy.getTypeArray();
887 // Add enumerators to enumeration type.
888 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
890 DIEnumerator Enum(Elements.getElement(i).getNode());
891 if (!Enum.isNull()) {
892 ElemDie = constructEnumTypeDIE(&Enum);
893 Buffer.addChild(ElemDie);
898 case dwarf::DW_TAG_subroutine_type: {
900 DIArray Elements = CTy.getTypeArray();
901 DIDescriptor RTy = Elements.getElement(0);
902 addType(&Buffer, DIType(RTy.getNode()));
904 // Add prototype flag.
905 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
908 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
909 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
910 DIDescriptor Ty = Elements.getElement(i);
911 addType(Arg, DIType(Ty.getNode()));
912 Buffer.addChild(Arg);
916 case dwarf::DW_TAG_structure_type:
917 case dwarf::DW_TAG_union_type:
918 case dwarf::DW_TAG_class_type: {
919 // Add elements to structure type.
920 DIArray Elements = CTy.getTypeArray();
922 // A forward struct declared type may not have elements available.
923 if (Elements.isNull())
926 // Add elements to structure type.
927 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
928 DIDescriptor Element = Elements.getElement(i);
929 if (Element.isNull())
932 if (Element.getTag() == dwarf::DW_TAG_subprogram)
933 ElemDie = createSubprogramDIE(DISubprogram(Element.getNode()));
935 ElemDie = createMemberDIE(DIDerivedType(Element.getNode()));
936 Buffer.addChild(ElemDie);
939 if (CTy.isAppleBlockExtension())
940 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
942 unsigned RLang = CTy.getRunTimeLang();
944 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
945 dwarf::DW_FORM_data1, RLang);
952 // Add name if not anonymous or intermediate type.
954 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
956 if (Tag == dwarf::DW_TAG_enumeration_type ||
957 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
958 // Add size if non-zero (derived types might be zero-sized.)
960 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
962 // Add zero size if it is not a forward declaration.
963 if (CTy.isForwardDecl())
964 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
966 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
969 // Add source line info if available.
970 if (!CTy.isForwardDecl())
971 addSourceLine(&Buffer, &CTy);
975 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
976 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
977 int64_t L = SR.getLo();
978 int64_t H = SR.getHi();
979 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
981 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
983 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
984 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
986 Buffer.addChild(DW_Subrange);
989 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
990 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
991 DICompositeType *CTy) {
992 Buffer.setTag(dwarf::DW_TAG_array_type);
993 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
994 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
996 // Emit derived type.
997 addType(&Buffer, CTy->getTypeDerivedFrom());
998 DIArray Elements = CTy->getTypeArray();
1000 // Get an anonymous type for index type.
1001 DIE *IdxTy = ModuleCU->getIndexTyDie();
1003 // Construct an anonymous type for index type.
1004 IdxTy = new DIE(dwarf::DW_TAG_base_type);
1005 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1006 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1007 dwarf::DW_ATE_signed);
1008 ModuleCU->addDie(IdxTy);
1009 ModuleCU->setIndexTyDie(IdxTy);
1012 // Add subranges to array type.
1013 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1014 DIDescriptor Element = Elements.getElement(i);
1015 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1016 constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
1020 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1021 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator *ETy) {
1022 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1023 StringRef Name = ETy->getName();
1024 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1025 int64_t Value = ETy->getEnumValue();
1026 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1030 /// createGlobalVariableDIE - Create new DIE using GV.
1031 DIE *DwarfDebug::createGlobalVariableDIE(const DIGlobalVariable &GV) {
1032 // If the global variable was optmized out then no need to create debug info
1034 if (!GV.getGlobal()) return NULL;
1035 if (GV.getDisplayName().empty()) return NULL;
1037 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1038 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1039 GV.getDisplayName());
1041 StringRef LinkageName = GV.getLinkageName();
1042 if (!LinkageName.empty()) {
1043 // Skip special LLVM prefix that is used to inform the asm printer to not
1044 // emit usual symbol prefix before the symbol name. This happens for
1045 // Objective-C symbol names and symbol whose name is replaced using GCC's
1046 // __asm__ attribute.
1047 if (LinkageName[0] == 1)
1048 LinkageName = LinkageName.substr(1);
1049 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1052 addType(GVDie, GV.getType());
1053 if (!GV.isLocalToUnit())
1054 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1055 addSourceLine(GVDie, &GV);
1060 /// createMemberDIE - Create new member DIE.
1061 DIE *DwarfDebug::createMemberDIE(const DIDerivedType &DT) {
1062 DIE *MemberDie = new DIE(DT.getTag());
1063 StringRef Name = DT.getName();
1065 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1067 addType(MemberDie, DT.getTypeDerivedFrom());
1069 addSourceLine(MemberDie, &DT);
1071 DIEBlock *MemLocationDie = new DIEBlock();
1072 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1074 uint64_t Size = DT.getSizeInBits();
1075 uint64_t FieldSize = DT.getOriginalTypeSize();
1077 if (Size != FieldSize) {
1079 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1080 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1082 uint64_t Offset = DT.getOffsetInBits();
1083 uint64_t FieldOffset = Offset;
1084 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1085 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1086 FieldOffset = (HiMark - FieldSize);
1087 Offset -= FieldOffset;
1089 // Maybe we need to work from the other end.
1090 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1091 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1093 // Here WD_AT_data_member_location points to the anonymous
1094 // field that includes this bit field.
1095 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1098 // This is not a bitfield.
1099 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1101 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1103 if (DT.isProtected())
1104 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1105 dwarf::DW_ACCESS_protected);
1106 else if (DT.isPrivate())
1107 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1108 dwarf::DW_ACCESS_private);
1109 else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1110 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1111 dwarf::DW_ACCESS_public);
1113 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1114 dwarf::DW_VIRTUALITY_virtual);
1118 /// createSubprogramDIE - Create new DIE using SP.
1119 DIE *DwarfDebug::createSubprogramDIE(const DISubprogram &SP, bool MakeDecl) {
1120 DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1124 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1125 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1127 StringRef LinkageName = SP.getLinkageName();
1128 if (!LinkageName.empty()) {
1129 // Skip special LLVM prefix that is used to inform the asm printer to not
1130 // emit usual symbol prefix before the symbol name. This happens for
1131 // Objective-C symbol names and symbol whose name is replaced using GCC's
1132 // __asm__ attribute.
1133 if (LinkageName[0] == 1)
1134 LinkageName = LinkageName.substr(1);
1135 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1138 addSourceLine(SPDie, &SP);
1140 // Add prototyped tag, if C or ObjC.
1141 unsigned Lang = SP.getCompileUnit().getLanguage();
1142 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1143 Lang == dwarf::DW_LANG_ObjC)
1144 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1147 DICompositeType SPTy = SP.getType();
1148 DIArray Args = SPTy.getTypeArray();
1149 unsigned SPTag = SPTy.getTag();
1151 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
1152 addType(SPDie, SPTy);
1154 addType(SPDie, DIType(Args.getElement(0).getNode()));
1156 unsigned VK = SP.getVirtuality();
1158 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1159 DIEBlock *Block = new DIEBlock();
1160 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1161 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1162 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1163 ContainingTypeMap.insert(std::make_pair(SPDie, WeakVH(SP.getContainingType().getNode())));
1166 if (MakeDecl || !SP.isDefinition()) {
1167 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1169 // Add arguments. Do not add arguments for subprogram definition. They will
1170 // be handled while processing variables.
1171 DICompositeType SPTy = SP.getType();
1172 DIArray Args = SPTy.getTypeArray();
1173 unsigned SPTag = SPTy.getTag();
1175 if (SPTag == dwarf::DW_TAG_subroutine_type)
1176 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1177 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1178 addType(Arg, DIType(Args.getElement(i).getNode()));
1179 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1180 SPDie->addChild(Arg);
1184 // DW_TAG_inlined_subroutine may refer to this DIE.
1185 ModuleCU->insertDIE(SP.getNode(), SPDie);
1189 /// findCompileUnit - Get the compile unit for the given descriptor.
1191 CompileUnit *DwarfDebug::findCompileUnit(DICompileUnit Unit) {
1192 DenseMap<Value *, CompileUnit *>::const_iterator I =
1193 CompileUnitMap.find(Unit.getNode());
1194 if (I == CompileUnitMap.end())
1195 return constructCompileUnit(Unit.getNode());
1199 /// getUpdatedDbgScope - Find or create DbgScope assicated with the instruction.
1200 /// Initialize scope and update scope hierarchy.
1201 DbgScope *DwarfDebug::getUpdatedDbgScope(MDNode *N, const MachineInstr *MI,
1202 MDNode *InlinedAt) {
1203 assert (N && "Invalid Scope encoding!");
1204 assert (MI && "Missing machine instruction!");
1205 bool GetConcreteScope = (MI && InlinedAt);
1207 DbgScope *NScope = NULL;
1210 NScope = DbgScopeMap.lookup(InlinedAt);
1212 NScope = DbgScopeMap.lookup(N);
1213 assert (NScope && "Unable to find working scope!");
1215 if (NScope->getFirstInsn())
1218 DbgScope *Parent = NULL;
1219 if (GetConcreteScope) {
1220 DILocation IL(InlinedAt);
1221 Parent = getUpdatedDbgScope(IL.getScope().getNode(), MI,
1222 IL.getOrigLocation().getNode());
1223 assert (Parent && "Unable to find Parent scope!");
1224 NScope->setParent(Parent);
1225 Parent->addScope(NScope);
1226 } else if (DIDescriptor(N).isLexicalBlock()) {
1227 DILexicalBlock DB(N);
1228 if (!DB.getContext().isNull()) {
1229 Parent = getUpdatedDbgScope(DB.getContext().getNode(), MI, InlinedAt);
1230 NScope->setParent(Parent);
1231 Parent->addScope(NScope);
1235 NScope->setFirstInsn(MI);
1237 if (!Parent && !InlinedAt) {
1238 StringRef SPName = DISubprogram(N).getLinkageName();
1239 if (SPName == MF->getFunction()->getName())
1240 CurrentFnDbgScope = NScope;
1243 if (GetConcreteScope) {
1244 ConcreteScopes[InlinedAt] = NScope;
1245 getOrCreateAbstractScope(N);
1251 DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1252 assert (N && "Invalid Scope encoding!");
1254 DbgScope *AScope = AbstractScopes.lookup(N);
1258 DbgScope *Parent = NULL;
1260 DIDescriptor Scope(N);
1261 if (Scope.isLexicalBlock()) {
1262 DILexicalBlock DB(N);
1263 DIDescriptor ParentDesc = DB.getContext();
1264 if (!ParentDesc.isNull())
1265 Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1268 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1271 Parent->addScope(AScope);
1272 AScope->setAbstractScope();
1273 AbstractScopes[N] = AScope;
1274 if (DIDescriptor(N).isSubprogram())
1275 AbstractScopesList.push_back(AScope);
1279 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1280 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1281 /// If there are global variables in this scope then create and insert
1282 /// DIEs for these variables.
1283 DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
1285 DIE *SPDie = ModuleCU->getDIE(SPNode);
1286 assert (SPDie && "Unable to find subprogram DIE!");
1287 DISubprogram SP(SPNode);
1288 if (SP.isDefinition() && !SP.getContext().isCompileUnit()) {
1289 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1291 DICompositeType SPTy = SP.getType();
1292 DIArray Args = SPTy.getTypeArray();
1293 unsigned SPTag = SPTy.getTag();
1294 if (SPTag == dwarf::DW_TAG_subroutine_type)
1295 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1296 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1297 addType(Arg, DIType(Args.getElement(i).getNode()));
1298 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1299 SPDie->addChild(Arg);
1301 DIE *SPDeclDie = SPDie;
1302 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1303 addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1305 ModuleCU->addDie(SPDie);
1308 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1309 DWLabel("func_begin", SubprogramCount));
1310 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1311 DWLabel("func_end", SubprogramCount));
1312 MachineLocation Location(RI->getFrameRegister(*MF));
1313 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1315 if (!DISubprogram(SPNode).isLocalToUnit())
1316 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1321 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1322 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1323 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1324 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1325 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1327 // Ignore empty scopes.
1328 if (StartID == EndID && StartID != 0)
1331 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1332 if (Scope->isAbstractScope())
1335 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1337 DWLabel("label", StartID)
1338 : DWLabel("func_begin", SubprogramCount));
1339 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1341 DWLabel("label", EndID)
1342 : DWLabel("func_end", SubprogramCount));
1349 /// constructInlinedScopeDIE - This scope represents inlined body of
1350 /// a function. Construct DIE to represent this concrete inlined copy
1351 /// of the function.
1352 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1353 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1354 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1355 assert (StartID && "Invalid starting label for an inlined scope!");
1356 assert (EndID && "Invalid end label for an inlined scope!");
1357 // Ignore empty scopes.
1358 if (StartID == EndID && StartID != 0)
1361 DIScope DS(Scope->getScopeNode());
1364 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1366 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1367 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1368 assert (OriginDIE && "Unable to find Origin DIE!");
1369 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1370 dwarf::DW_FORM_ref4, OriginDIE);
1372 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1373 DWLabel("label", StartID));
1374 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1375 DWLabel("label", EndID));
1377 InlinedSubprogramDIEs.insert(OriginDIE);
1379 // Track the start label for this inlined function.
1380 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1381 I = InlineInfo.find(InlinedSP.getNode());
1383 if (I == InlineInfo.end()) {
1384 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartID,
1386 InlinedSPNodes.push_back(InlinedSP.getNode());
1388 I->second.push_back(std::make_pair(StartID, ScopeDIE));
1390 StringPool.insert(InlinedSP.getName());
1391 StringPool.insert(InlinedSP.getLinkageName());
1392 DILocation DL(Scope->getInlinedAt());
1393 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1394 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1400 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1401 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1402 // Get the descriptor.
1403 const DIVariable &VD = DV->getVariable();
1404 StringRef Name = VD.getName();
1408 // Translate tag to proper Dwarf tag. The result variable is dropped for
1411 switch (VD.getTag()) {
1412 case dwarf::DW_TAG_return_variable:
1414 case dwarf::DW_TAG_arg_variable:
1415 Tag = dwarf::DW_TAG_formal_parameter;
1417 case dwarf::DW_TAG_auto_variable: // fall thru
1419 Tag = dwarf::DW_TAG_variable;
1423 // Define variable debug information entry.
1424 DIE *VariableDie = new DIE(Tag);
1428 if (DbgVariable *AV = DV->getAbstractVariable())
1429 AbsDIE = AV->getDIE();
1432 DIScope DS(Scope->getScopeNode());
1433 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1434 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1436 assert (OriginSPDIE && "Unable to find Origin DIE for the SP!");
1437 DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1438 assert (AbsDIE && "Unable to find Origin DIE for the Variable!");
1439 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1440 dwarf::DW_FORM_ref4, AbsDIE);
1443 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1444 addSourceLine(VariableDie, &VD);
1446 // Add variable type.
1447 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1448 // addresses instead.
1449 if (VD.isBlockByrefVariable())
1450 addType(VariableDie, getBlockByrefType(VD.getType(), Name));
1452 addType(VariableDie, VD.getType());
1455 // Add variable address.
1456 if (!Scope->isAbstractScope()) {
1457 MachineLocation Location;
1459 int Offset = RI->getFrameIndexReference(*MF, DV->getFrameIndex(), FrameReg);
1460 Location.set(FrameReg, Offset);
1462 if (VD.hasComplexAddress())
1463 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1464 else if (VD.isBlockByrefVariable())
1465 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1467 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1469 DV->setDIE(VariableDie);
1474 void DwarfDebug::addPubTypes(DISubprogram SP) {
1475 DICompositeType SPTy = SP.getType();
1476 unsigned SPTag = SPTy.getTag();
1477 if (SPTag != dwarf::DW_TAG_subroutine_type)
1480 DIArray Args = SPTy.getTypeArray();
1484 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1485 DIType ATy(Args.getElement(i).getNode());
1488 DICompositeType CATy = getDICompositeType(ATy);
1489 if (!CATy.isNull() && !CATy.getName().empty()) {
1490 if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode()))
1491 ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry());
1496 /// constructScopeDIE - Construct a DIE for this scope.
1497 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1500 DIScope DS(Scope->getScopeNode());
1504 DIE *ScopeDIE = NULL;
1505 if (Scope->getInlinedAt())
1506 ScopeDIE = constructInlinedScopeDIE(Scope);
1507 else if (DS.isSubprogram()) {
1508 if (Scope->isAbstractScope())
1509 ScopeDIE = ModuleCU->getDIE(DS.getNode());
1511 ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
1514 ScopeDIE = constructLexicalScopeDIE(Scope);
1515 if (!ScopeDIE) return NULL;
1518 // Add variables to scope.
1519 SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1520 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1521 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1523 ScopeDIE->addChild(VariableDIE);
1526 // Add nested scopes.
1527 SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1528 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1529 // Define the Scope debug information entry.
1530 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1532 ScopeDIE->addChild(NestedDIE);
1535 if (DS.isSubprogram())
1536 addPubTypes(DISubprogram(DS.getNode()));
1541 /// GetOrCreateSourceID - Look up the source id with the given directory and
1542 /// source file names. If none currently exists, create a new id and insert it
1543 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1545 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName) {
1547 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1548 if (DI != DirectoryIdMap.end()) {
1549 DId = DI->getValue();
1551 DId = DirectoryNames.size() + 1;
1552 DirectoryIdMap[DirName] = DId;
1553 DirectoryNames.push_back(DirName);
1557 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1558 if (FI != SourceFileIdMap.end()) {
1559 FId = FI->getValue();
1561 FId = SourceFileNames.size() + 1;
1562 SourceFileIdMap[FileName] = FId;
1563 SourceFileNames.push_back(FileName);
1566 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1567 SourceIdMap.find(std::make_pair(DId, FId));
1568 if (SI != SourceIdMap.end())
1571 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1572 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1573 SourceIds.push_back(std::make_pair(DId, FId));
1578 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1579 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1580 DIE *NDie = ModuleCU->getDIE(NS.getNode());
1583 NDie = new DIE(dwarf::DW_TAG_namespace);
1584 ModuleCU->insertDIE(NS.getNode(), NDie);
1585 if (!NS.getName().empty())
1586 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1587 addSourceLine(NDie, &NS);
1588 addToContextOwner(NDie, NS.getContext());
1592 CompileUnit *DwarfDebug::constructCompileUnit(MDNode *N) {
1593 DICompileUnit DIUnit(N);
1594 StringRef FN = DIUnit.getFilename();
1595 StringRef Dir = DIUnit.getDirectory();
1596 unsigned ID = GetOrCreateSourceID(Dir, FN);
1598 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1599 addSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1600 DWLabel("section_line", 0), DWLabel("section_line", 0),
1602 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1603 DIUnit.getProducer());
1604 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1605 DIUnit.getLanguage());
1606 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1609 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1610 if (DIUnit.isOptimized())
1611 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1613 StringRef Flags = DIUnit.getFlags();
1615 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1617 unsigned RVer = DIUnit.getRunTimeVersion();
1619 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1620 dwarf::DW_FORM_data1, RVer);
1622 CompileUnit *Unit = new CompileUnit(ID, Die);
1623 if (!ModuleCU && DIUnit.isMain()) {
1624 // Use first compile unit marked as isMain as the compile unit
1629 CompileUnitMap[DIUnit.getNode()] = Unit;
1630 CompileUnits.push_back(Unit);
1634 void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
1635 DIGlobalVariable DI_GV(N);
1637 // If debug information is malformed then ignore it.
1638 if (DI_GV.Verify() == false)
1641 // Check for pre-existence.
1642 if (ModuleCU->getDIE(DI_GV.getNode()))
1645 DIE *VariableDie = createGlobalVariableDIE(DI_GV);
1650 ModuleCU->insertDIE(N, VariableDie);
1652 // Add to context owner.
1653 if (DI_GV.isDefinition()
1654 && !DI_GV.getContext().isCompileUnit()) {
1655 // Create specification DIE.
1656 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1657 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1658 dwarf::DW_FORM_ref4, VariableDie);
1659 DIEBlock *Block = new DIEBlock();
1660 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1661 addObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1662 Asm->Mang->getMangledName(DI_GV.getGlobal()));
1663 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1664 ModuleCU->addDie(VariableSpecDIE);
1666 DIEBlock *Block = new DIEBlock();
1667 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1668 addObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1669 Asm->Mang->getMangledName(DI_GV.getGlobal()));
1670 addBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1672 addToContextOwner(VariableDie, DI_GV.getContext());
1674 // Expose as global. FIXME - need to check external flag.
1675 ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1677 DIType GTy = DI_GV.getType();
1678 if (GTy.isCompositeType() && !GTy.getName().empty()) {
1679 DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode());
1680 assert (Entry && "Missing global type!");
1681 ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry());
1686 void DwarfDebug::constructSubprogramDIE(MDNode *N) {
1689 // Check for pre-existence.
1690 if (ModuleCU->getDIE(N))
1693 if (!SP.isDefinition())
1694 // This is a method declaration which will be handled while constructing
1698 DIE *SubprogramDie = createSubprogramDIE(SP);
1701 ModuleCU->insertDIE(N, SubprogramDie);
1703 // Add to context owner.
1704 addToContextOwner(SubprogramDie, SP.getContext());
1706 // Expose as global.
1707 ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1712 /// beginModule - Emit all Dwarf sections that should come prior to the
1713 /// content. Create global DIEs and emit initial debug info sections.
1714 /// This is inovked by the target AsmPrinter.
1715 void DwarfDebug::beginModule(Module *M, MachineModuleInfo *mmi) {
1718 if (TimePassesIsEnabled)
1719 DebugTimer->startTimer();
1721 if (!MAI->doesSupportDebugInformation())
1724 DebugInfoFinder DbgFinder;
1725 DbgFinder.processModule(*M);
1727 // Create all the compile unit DIEs.
1728 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1729 E = DbgFinder.compile_unit_end(); I != E; ++I)
1730 constructCompileUnit(*I);
1732 if (CompileUnits.empty()) {
1733 if (TimePassesIsEnabled)
1734 DebugTimer->stopTimer();
1739 // If main compile unit for this module is not seen than randomly
1740 // select first compile unit.
1742 ModuleCU = CompileUnits[0];
1744 // Create DIEs for each subprogram.
1745 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1746 E = DbgFinder.subprogram_end(); I != E; ++I)
1747 constructSubprogramDIE(*I);
1749 // Create DIEs for each global variable.
1750 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1751 E = DbgFinder.global_variable_end(); I != E; ++I)
1752 constructGlobalVariableDIE(*I);
1756 MMI->setDebugInfoAvailability(true);
1758 // Prime section data.
1759 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1761 // Print out .file directives to specify files for .loc directives. These are
1762 // printed out early so that they precede any .loc directives.
1763 if (MAI->hasDotLocAndDotFile()) {
1764 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1765 // Remember source id starts at 1.
1766 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1767 sys::Path FullPath(getSourceDirectoryName(Id.first));
1769 FullPath.appendComponent(getSourceFileName(Id.second));
1770 assert(AppendOk && "Could not append filename to directory!");
1772 Asm->EmitFile(i, FullPath.str());
1777 // Emit initial sections
1780 if (TimePassesIsEnabled)
1781 DebugTimer->stopTimer();
1784 /// endModule - Emit all Dwarf sections that should come after the content.
1786 void DwarfDebug::endModule() {
1790 if (TimePassesIsEnabled)
1791 DebugTimer->startTimer();
1793 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1794 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1795 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1797 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1800 // Insert top level DIEs.
1801 for (SmallVector<DIE *, 4>::iterator TI = TopLevelDIEsVector.begin(),
1802 TE = TopLevelDIEsVector.end(); TI != TE; ++TI)
1803 ModuleCU->getCUDie()->addChild(*TI);
1805 for (DenseMap<DIE *, WeakVH>::iterator CI = ContainingTypeMap.begin(),
1806 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1807 DIE *SPDie = CI->first;
1808 MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1810 DIE *NDie = ModuleCU->getDIE(N);
1811 if (!NDie) continue;
1812 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1813 addDIEEntry(NDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1816 // Standard sections final addresses.
1817 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1818 EmitLabel("text_end", 0);
1819 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1820 EmitLabel("data_end", 0);
1822 // End text sections.
1823 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1824 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1825 EmitLabel("section_end", i);
1828 // Emit common frame information.
1829 emitCommonDebugFrame();
1831 // Emit function debug frame information
1832 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1833 E = DebugFrames.end(); I != E; ++I)
1834 emitFunctionDebugFrame(*I);
1836 // Compute DIE offsets and sizes.
1837 computeSizeAndOffsets();
1839 // Emit all the DIEs into a debug info section
1842 // Corresponding abbreviations into a abbrev section.
1843 emitAbbreviations();
1845 // Emit source line correspondence into a debug line section.
1848 // Emit info into a debug pubnames section.
1849 emitDebugPubNames();
1851 // Emit info into a debug pubtypes section.
1852 emitDebugPubTypes();
1854 // Emit info into a debug str section.
1857 // Emit info into a debug loc section.
1860 // Emit info into a debug aranges section.
1863 // Emit info into a debug ranges section.
1866 // Emit info into a debug macinfo section.
1869 // Emit inline info.
1870 emitDebugInlineInfo();
1872 if (TimePassesIsEnabled)
1873 DebugTimer->stopTimer();
1876 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
1877 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
1879 DILocation &ScopeLoc) {
1881 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
1883 return AbsDbgVariable;
1885 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope().getNode());
1889 AbsDbgVariable = new DbgVariable(Var, FrameIdx);
1890 Scope->addVariable(AbsDbgVariable);
1891 AbstractVariables[Var.getNode()] = AbsDbgVariable;
1892 return AbsDbgVariable;
1895 /// collectVariableInfo - Populate DbgScope entries with variables' info.
1896 void DwarfDebug::collectVariableInfo() {
1899 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1900 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1901 VE = VMap.end(); VI != VE; ++VI) {
1902 MetadataBase *MB = VI->first;
1903 MDNode *Var = dyn_cast_or_null<MDNode>(MB);
1905 DIVariable DV (Var);
1906 std::pair< unsigned, MDNode *> VP = VI->second;
1907 DILocation ScopeLoc(VP.second);
1910 ConcreteScopes.lookup(ScopeLoc.getOrigLocation().getNode());
1912 Scope = DbgScopeMap.lookup(ScopeLoc.getScope().getNode());
1913 // If variable scope is not found then skip this variable.
1917 DbgVariable *RegVar = new DbgVariable(DV, VP.first);
1918 Scope->addVariable(RegVar);
1919 if (DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first,
1921 RegVar->setAbstractVariable(AbsDbgVariable);
1925 /// beginScope - Process beginning of a scope starting at Label.
1926 void DwarfDebug::beginScope(const MachineInstr *MI, unsigned Label) {
1927 InsnToDbgScopeMapTy::iterator I = DbgScopeBeginMap.find(MI);
1928 if (I == DbgScopeBeginMap.end())
1930 ScopeVector &SD = I->second;
1931 for (ScopeVector::iterator SDI = SD.begin(), SDE = SD.end();
1933 (*SDI)->setStartLabelID(Label);
1936 /// endScope - Process end of a scope.
1937 void DwarfDebug::endScope(const MachineInstr *MI) {
1938 InsnToDbgScopeMapTy::iterator I = DbgScopeEndMap.find(MI);
1939 if (I == DbgScopeEndMap.end())
1942 unsigned Label = MMI->NextLabelID();
1943 Asm->printLabel(Label);
1946 SmallVector<DbgScope *, 2> &SD = I->second;
1947 for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
1949 (*SDI)->setEndLabelID(Label);
1953 /// createDbgScope - Create DbgScope for the scope.
1954 void DwarfDebug::createDbgScope(MDNode *Scope, MDNode *InlinedAt) {
1957 DbgScope *WScope = DbgScopeMap.lookup(Scope);
1960 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
1961 DbgScopeMap.insert(std::make_pair(Scope, WScope));
1962 if (DIDescriptor(Scope).isLexicalBlock())
1963 createDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
1967 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
1971 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
1972 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
1973 DILocation DL(InlinedAt);
1974 createDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
1977 /// extractScopeInformation - Scan machine instructions in this function
1978 /// and collect DbgScopes. Return true, if atleast one scope was found.
1979 bool DwarfDebug::extractScopeInformation(MachineFunction *MF) {
1980 // If scope information was extracted using .dbg intrinsics then there is not
1981 // any need to extract these information by scanning each instruction.
1982 if (!DbgScopeMap.empty())
1985 // Scan each instruction and create scopes. First build working set of scopes.
1986 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1988 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1990 const MachineInstr *MInsn = II;
1991 DebugLoc DL = MInsn->getDebugLoc();
1992 if (DL.isUnknown()) continue;
1993 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
1994 if (!DLT.Scope) continue;
1995 // There is no need to create another DIE for compile unit. For all
1996 // other scopes, create one DbgScope now. This will be translated
1997 // into a scope DIE at the end.
1998 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
1999 createDbgScope(DLT.Scope, DLT.InlinedAtLoc);
2004 // Build scope hierarchy using working set of scopes.
2005 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2007 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2009 const MachineInstr *MInsn = II;
2010 DebugLoc DL = MInsn->getDebugLoc();
2011 if (DL.isUnknown()) continue;
2012 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
2013 if (!DLT.Scope) continue;
2014 // There is no need to create another DIE for compile unit. For all
2015 // other scopes, create one DbgScope now. This will be translated
2016 // into a scope DIE at the end.
2017 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
2018 DbgScope *Scope = getUpdatedDbgScope(DLT.Scope, MInsn, DLT.InlinedAtLoc);
2019 Scope->setLastInsn(MInsn);
2023 // If a scope's last instruction is not set then use its child scope's
2024 // last instruction as this scope's last instrunction.
2025 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
2026 DE = DbgScopeMap.end(); DI != DE; ++DI) {
2027 if (DI->second->isAbstractScope())
2029 assert (DI->second->getFirstInsn() && "Invalid first instruction!");
2030 DI->second->fixInstructionMarkers();
2031 assert (DI->second->getLastInsn() && "Invalid last instruction!");
2034 // Each scope has first instruction and last instruction to mark beginning
2035 // and end of a scope respectively. Create an inverse map that list scopes
2036 // starts (and ends) with an instruction. One instruction may start (or end)
2038 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
2039 DE = DbgScopeMap.end(); DI != DE; ++DI) {
2040 DbgScope *S = DI->second;
2041 if (S->isAbstractScope())
2043 const MachineInstr *MI = S->getFirstInsn();
2044 assert (MI && "DbgScope does not have first instruction!");
2046 InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI);
2047 if (IDI != DbgScopeBeginMap.end())
2048 IDI->second.push_back(S);
2050 DbgScopeBeginMap[MI].push_back(S);
2052 MI = S->getLastInsn();
2053 assert (MI && "DbgScope does not have last instruction!");
2054 IDI = DbgScopeEndMap.find(MI);
2055 if (IDI != DbgScopeEndMap.end())
2056 IDI->second.push_back(S);
2058 DbgScopeEndMap[MI].push_back(S);
2061 return !DbgScopeMap.empty();
2064 /// beginFunction - Gather pre-function debug information. Assumes being
2065 /// emitted immediately after the function entry point.
2066 void DwarfDebug::beginFunction(MachineFunction *MF) {
2069 if (!ShouldEmitDwarfDebug()) return;
2071 if (TimePassesIsEnabled)
2072 DebugTimer->startTimer();
2074 if (!extractScopeInformation(MF))
2077 collectVariableInfo();
2079 // Begin accumulating function debug information.
2080 MMI->BeginFunction(MF);
2082 // Assumes in correct section after the entry point.
2083 EmitLabel("func_begin", ++SubprogramCount);
2085 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2087 DebugLoc FDL = MF->getDefaultDebugLoc();
2088 if (!FDL.isUnknown()) {
2089 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
2090 unsigned LabelID = 0;
2091 DISubprogram SP = getDISubprogram(DLT.Scope);
2093 LabelID = recordSourceLine(SP.getLineNumber(), 0, DLT.Scope);
2095 LabelID = recordSourceLine(DLT.Line, DLT.Col, DLT.Scope);
2096 Asm->printLabel(LabelID);
2099 if (TimePassesIsEnabled)
2100 DebugTimer->stopTimer();
2103 /// endFunction - Gather and emit post-function debug information.
2105 void DwarfDebug::endFunction(MachineFunction *MF) {
2106 if (!ShouldEmitDwarfDebug()) return;
2108 if (TimePassesIsEnabled)
2109 DebugTimer->startTimer();
2111 if (DbgScopeMap.empty())
2114 // Define end label for subprogram.
2115 EmitLabel("func_end", SubprogramCount);
2117 // Get function line info.
2118 if (!Lines.empty()) {
2119 // Get section line info.
2120 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2121 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2122 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2123 // Append the function info to section info.
2124 SectionLineInfos.insert(SectionLineInfos.end(),
2125 Lines.begin(), Lines.end());
2128 // Construct abstract scopes.
2129 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2130 AE = AbstractScopesList.end(); AI != AE; ++AI)
2131 constructScopeDIE(*AI);
2133 constructScopeDIE(CurrentFnDbgScope);
2135 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2136 MMI->getFrameMoves()));
2139 CurrentFnDbgScope = NULL;
2140 DbgScopeMap.clear();
2141 DbgScopeBeginMap.clear();
2142 DbgScopeEndMap.clear();
2143 ConcreteScopes.clear();
2144 AbstractScopesList.clear();
2148 if (TimePassesIsEnabled)
2149 DebugTimer->stopTimer();
2152 /// recordSourceLine - Records location information and associates it with a
2153 /// label. Returns a unique label ID used to generate a label and provide
2154 /// correspondence to the source line list.
2155 unsigned DwarfDebug::recordSourceLine(unsigned Line, unsigned Col,
2160 if (TimePassesIsEnabled)
2161 DebugTimer->startTimer();
2166 DIDescriptor Scope(S);
2167 if (Scope.isCompileUnit()) {
2168 DICompileUnit CU(S);
2169 Dir = CU.getDirectory();
2170 Fn = CU.getFilename();
2171 } else if (Scope.isSubprogram()) {
2173 Dir = SP.getDirectory();
2174 Fn = SP.getFilename();
2175 } else if (Scope.isLexicalBlock()) {
2176 DILexicalBlock DB(S);
2177 Dir = DB.getDirectory();
2178 Fn = DB.getFilename();
2180 assert (0 && "Unexpected scope info");
2182 unsigned Src = GetOrCreateSourceID(Dir, Fn);
2183 unsigned ID = MMI->NextLabelID();
2184 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2186 if (TimePassesIsEnabled)
2187 DebugTimer->stopTimer();
2192 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2193 /// timed. Look up the source id with the given directory and source file
2194 /// names. If none currently exists, create a new id and insert it in the
2195 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2197 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2198 const std::string &FileName) {
2199 if (TimePassesIsEnabled)
2200 DebugTimer->startTimer();
2202 unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str());
2204 if (TimePassesIsEnabled)
2205 DebugTimer->stopTimer();
2210 //===----------------------------------------------------------------------===//
2212 //===----------------------------------------------------------------------===//
2214 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2217 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2218 // Get the children.
2219 const std::vector<DIE *> &Children = Die->getChildren();
2221 // If not last sibling and has children then add sibling offset attribute.
2222 if (!Last && !Children.empty()) Die->addSiblingOffset();
2224 // Record the abbreviation.
2225 assignAbbrevNumber(Die->getAbbrev());
2227 // Get the abbreviation for this DIE.
2228 unsigned AbbrevNumber = Die->getAbbrevNumber();
2229 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2232 Die->setOffset(Offset);
2234 // Start the size with the size of abbreviation code.
2235 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2237 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2238 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2240 // Size the DIE attribute values.
2241 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2242 // Size attribute value.
2243 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
2245 // Size the DIE children if any.
2246 if (!Children.empty()) {
2247 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2248 "Children flag not set");
2250 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2251 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2253 // End of children marker.
2254 Offset += sizeof(int8_t);
2257 Die->setSize(Offset - Die->getOffset());
2261 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2263 void DwarfDebug::computeSizeAndOffsets() {
2264 // Compute size of compile unit header.
2265 static unsigned Offset =
2266 sizeof(int32_t) + // Length of Compilation Unit Info
2267 sizeof(int16_t) + // DWARF version number
2268 sizeof(int32_t) + // Offset Into Abbrev. Section
2269 sizeof(int8_t); // Pointer Size (in bytes)
2271 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2272 CompileUnitOffsets[ModuleCU] = 0;
2275 /// emitInitial - Emit initial Dwarf declarations. This is necessary for cc
2276 /// tools to recognize the object file contains Dwarf information.
2277 void DwarfDebug::emitInitial() {
2278 // Check to see if we already emitted intial headers.
2279 if (didInitial) return;
2282 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2284 // Dwarf sections base addresses.
2285 if (MAI->doesDwarfRequireFrameSection()) {
2286 Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
2287 EmitLabel("section_debug_frame", 0);
2290 Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
2291 EmitLabel("section_info", 0);
2292 Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
2293 EmitLabel("section_abbrev", 0);
2294 Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
2295 EmitLabel("section_aranges", 0);
2297 if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
2298 Asm->OutStreamer.SwitchSection(LineInfoDirective);
2299 EmitLabel("section_macinfo", 0);
2302 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
2303 EmitLabel("section_line", 0);
2304 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
2305 EmitLabel("section_loc", 0);
2306 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
2307 EmitLabel("section_pubnames", 0);
2308 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubTypesSection());
2309 EmitLabel("section_pubtypes", 0);
2310 Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
2311 EmitLabel("section_str", 0);
2312 Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
2313 EmitLabel("section_ranges", 0);
2315 Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
2316 EmitLabel("text_begin", 0);
2317 Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
2318 EmitLabel("data_begin", 0);
2321 /// emitDIE - Recusively Emits a debug information entry.
2323 void DwarfDebug::emitDIE(DIE *Die) {
2324 // Get the abbreviation for this DIE.
2325 unsigned AbbrevNumber = Die->getAbbrevNumber();
2326 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2330 // Emit the code (index) for the abbreviation.
2331 Asm->EmitULEB128Bytes(AbbrevNumber);
2333 if (Asm->isVerbose())
2334 Asm->EOL(std::string("Abbrev [" +
2335 utostr(AbbrevNumber) +
2336 "] 0x" + utohexstr(Die->getOffset()) +
2337 ":0x" + utohexstr(Die->getSize()) + " " +
2338 dwarf::TagString(Abbrev->getTag())));
2342 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2343 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2345 // Emit the DIE attribute values.
2346 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2347 unsigned Attr = AbbrevData[i].getAttribute();
2348 unsigned Form = AbbrevData[i].getForm();
2349 assert(Form && "Too many attributes for DIE (check abbreviation)");
2352 case dwarf::DW_AT_sibling:
2353 Asm->EmitInt32(Die->getSiblingOffset());
2355 case dwarf::DW_AT_abstract_origin: {
2356 DIEEntry *E = cast<DIEEntry>(Values[i]);
2357 DIE *Origin = E->getEntry();
2358 unsigned Addr = Origin->getOffset();
2359 Asm->EmitInt32(Addr);
2363 // Emit an attribute using the defined form.
2364 Values[i]->EmitValue(this, Form);
2368 Asm->EOL(dwarf::AttributeString(Attr));
2371 // Emit the DIE children if any.
2372 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2373 const std::vector<DIE *> &Children = Die->getChildren();
2375 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2376 emitDIE(Children[j]);
2378 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2382 /// emitDebugInfo - Emit the debug info section.
2384 void DwarfDebug::emitDebugInfo() {
2385 // Start debug info section.
2386 Asm->OutStreamer.SwitchSection(
2387 Asm->getObjFileLowering().getDwarfInfoSection());
2388 DIE *Die = ModuleCU->getCUDie();
2390 // Emit the compile units header.
2391 EmitLabel("info_begin", ModuleCU->getID());
2393 // Emit size of content not including length itself
2394 unsigned ContentSize = Die->getSize() +
2395 sizeof(int16_t) + // DWARF version number
2396 sizeof(int32_t) + // Offset Into Abbrev. Section
2397 sizeof(int8_t) + // Pointer Size (in bytes)
2398 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2400 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2401 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2402 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2403 Asm->EOL("Offset Into Abbrev. Section");
2404 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2407 // FIXME - extra padding for gdb bug.
2408 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2409 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2410 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2411 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2412 EmitLabel("info_end", ModuleCU->getID());
2417 /// emitAbbreviations - Emit the abbreviation section.
2419 void DwarfDebug::emitAbbreviations() const {
2420 // Check to see if it is worth the effort.
2421 if (!Abbreviations.empty()) {
2422 // Start the debug abbrev section.
2423 Asm->OutStreamer.SwitchSection(
2424 Asm->getObjFileLowering().getDwarfAbbrevSection());
2426 EmitLabel("abbrev_begin", 0);
2428 // For each abbrevation.
2429 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2430 // Get abbreviation data
2431 const DIEAbbrev *Abbrev = Abbreviations[i];
2433 // Emit the abbrevations code (base 1 index.)
2434 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2435 Asm->EOL("Abbreviation Code");
2437 // Emit the abbreviations data.
2443 // Mark end of abbreviations.
2444 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2446 EmitLabel("abbrev_end", 0);
2451 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2452 /// the line matrix.
2454 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2455 // Define last address of section.
2456 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2457 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2458 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2459 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2461 // Mark end of matrix.
2462 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2463 Asm->EmitULEB128Bytes(1); Asm->EOL();
2464 Asm->EmitInt8(1); Asm->EOL();
2467 /// emitDebugLines - Emit source line information.
2469 void DwarfDebug::emitDebugLines() {
2470 // If the target is using .loc/.file, the assembler will be emitting the
2471 // .debug_line table automatically.
2472 if (MAI->hasDotLocAndDotFile())
2475 // Minimum line delta, thus ranging from -10..(255-10).
2476 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2477 // Maximum line delta, thus ranging from -10..(255-10).
2478 const int MaxLineDelta = 255 + MinLineDelta;
2480 // Start the dwarf line section.
2481 Asm->OutStreamer.SwitchSection(
2482 Asm->getObjFileLowering().getDwarfLineSection());
2484 // Construct the section header.
2485 EmitDifference("line_end", 0, "line_begin", 0, true);
2486 Asm->EOL("Length of Source Line Info");
2487 EmitLabel("line_begin", 0);
2489 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2491 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2492 Asm->EOL("Prolog Length");
2493 EmitLabel("line_prolog_begin", 0);
2495 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2497 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2499 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2501 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2503 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2505 // Line number standard opcode encodings argument count
2506 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2507 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2508 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2509 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2510 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2511 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2512 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2513 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2514 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2516 // Emit directories.
2517 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2518 Asm->EmitString(getSourceDirectoryName(DI));
2519 Asm->EOL("Directory");
2522 Asm->EmitInt8(0); Asm->EOL("End of directories");
2525 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2526 // Remember source id starts at 1.
2527 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2528 Asm->EmitString(getSourceFileName(Id.second));
2530 Asm->EmitULEB128Bytes(Id.first);
2531 Asm->EOL("Directory #");
2532 Asm->EmitULEB128Bytes(0);
2533 Asm->EOL("Mod date");
2534 Asm->EmitULEB128Bytes(0);
2535 Asm->EOL("File size");
2538 Asm->EmitInt8(0); Asm->EOL("End of files");
2540 EmitLabel("line_prolog_end", 0);
2542 // A sequence for each text section.
2543 unsigned SecSrcLinesSize = SectionSourceLines.size();
2545 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2546 // Isolate current sections line info.
2547 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2549 /*if (Asm->isVerbose()) {
2550 const MCSection *S = SectionMap[j + 1];
2551 O << '\t' << MAI->getCommentString() << " Section"
2552 << S->getName() << '\n';
2556 // Dwarf assumes we start with first line of first source file.
2557 unsigned Source = 1;
2560 // Construct rows of the address, source, line, column matrix.
2561 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2562 const SrcLineInfo &LineInfo = LineInfos[i];
2563 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2564 if (!LabelID) continue;
2566 if (LineInfo.getLine() == 0) continue;
2568 if (!Asm->isVerbose())
2571 std::pair<unsigned, unsigned> SourceID =
2572 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2573 O << '\t' << MAI->getCommentString() << ' '
2574 << getSourceDirectoryName(SourceID.first) << '/'
2575 << getSourceFileName(SourceID.second)
2576 << ':' << utostr_32(LineInfo.getLine()) << '\n';
2579 // Define the line address.
2580 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2581 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2582 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2583 EmitReference("label", LabelID); Asm->EOL("Location label");
2585 // If change of source, then switch to the new source.
2586 if (Source != LineInfo.getSourceID()) {
2587 Source = LineInfo.getSourceID();
2588 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2589 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2592 // If change of line.
2593 if (Line != LineInfo.getLine()) {
2594 // Determine offset.
2595 int Offset = LineInfo.getLine() - Line;
2596 int Delta = Offset - MinLineDelta;
2599 Line = LineInfo.getLine();
2601 // If delta is small enough and in range...
2602 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2603 // ... then use fast opcode.
2604 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2606 // ... otherwise use long hand.
2607 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2608 Asm->EOL("DW_LNS_advance_line");
2609 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2610 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2613 // Copy the previous row (different address or source)
2614 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2618 emitEndOfLineMatrix(j + 1);
2621 if (SecSrcLinesSize == 0)
2622 // Because we're emitting a debug_line section, we still need a line
2623 // table. The linker and friends expect it to exist. If there's nothing to
2624 // put into it, emit an empty table.
2625 emitEndOfLineMatrix(1);
2627 EmitLabel("line_end", 0);
2631 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
2633 void DwarfDebug::emitCommonDebugFrame() {
2634 if (!MAI->doesDwarfRequireFrameSection())
2638 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2639 TargetFrameInfo::StackGrowsUp ?
2640 TD->getPointerSize() : -TD->getPointerSize();
2642 // Start the dwarf frame section.
2643 Asm->OutStreamer.SwitchSection(
2644 Asm->getObjFileLowering().getDwarfFrameSection());
2646 EmitLabel("debug_frame_common", 0);
2647 EmitDifference("debug_frame_common_end", 0,
2648 "debug_frame_common_begin", 0, true);
2649 Asm->EOL("Length of Common Information Entry");
2651 EmitLabel("debug_frame_common_begin", 0);
2652 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2653 Asm->EOL("CIE Identifier Tag");
2654 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2655 Asm->EOL("CIE Version");
2656 Asm->EmitString("");
2657 Asm->EOL("CIE Augmentation");
2658 Asm->EmitULEB128Bytes(1);
2659 Asm->EOL("CIE Code Alignment Factor");
2660 Asm->EmitSLEB128Bytes(stackGrowth);
2661 Asm->EOL("CIE Data Alignment Factor");
2662 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2663 Asm->EOL("CIE RA Column");
2665 std::vector<MachineMove> Moves;
2666 RI->getInitialFrameState(Moves);
2668 EmitFrameMoves(NULL, 0, Moves, false);
2670 Asm->EmitAlignment(2, 0, 0, false);
2671 EmitLabel("debug_frame_common_end", 0);
2676 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
2679 DwarfDebug::emitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2680 if (!MAI->doesDwarfRequireFrameSection())
2683 // Start the dwarf frame section.
2684 Asm->OutStreamer.SwitchSection(
2685 Asm->getObjFileLowering().getDwarfFrameSection());
2687 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2688 "debug_frame_begin", DebugFrameInfo.Number, true);
2689 Asm->EOL("Length of Frame Information Entry");
2691 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2693 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2695 Asm->EOL("FDE CIE offset");
2697 EmitReference("func_begin", DebugFrameInfo.Number);
2698 Asm->EOL("FDE initial location");
2699 EmitDifference("func_end", DebugFrameInfo.Number,
2700 "func_begin", DebugFrameInfo.Number);
2701 Asm->EOL("FDE address range");
2703 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2706 Asm->EmitAlignment(2, 0, 0, false);
2707 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2712 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2714 void DwarfDebug::emitDebugPubNames() {
2715 // Start the dwarf pubnames section.
2716 Asm->OutStreamer.SwitchSection(
2717 Asm->getObjFileLowering().getDwarfPubNamesSection());
2719 EmitDifference("pubnames_end", ModuleCU->getID(),
2720 "pubnames_begin", ModuleCU->getID(), true);
2721 Asm->EOL("Length of Public Names Info");
2723 EmitLabel("pubnames_begin", ModuleCU->getID());
2725 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2727 EmitSectionOffset("info_begin", "section_info",
2728 ModuleCU->getID(), 0, true, false);
2729 Asm->EOL("Offset of Compilation Unit Info");
2731 EmitDifference("info_end", ModuleCU->getID(), "info_begin", ModuleCU->getID(),
2733 Asm->EOL("Compilation Unit Length");
2735 const StringMap<DIE*> &Globals = ModuleCU->getGlobals();
2736 for (StringMap<DIE*>::const_iterator
2737 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2738 const char *Name = GI->getKeyData();
2739 DIE * Entity = GI->second;
2741 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2742 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2745 Asm->EmitInt32(0); Asm->EOL("End Mark");
2746 EmitLabel("pubnames_end", ModuleCU->getID());
2751 void DwarfDebug::emitDebugPubTypes() {
2752 // Start the dwarf pubnames section.
2753 Asm->OutStreamer.SwitchSection(
2754 Asm->getObjFileLowering().getDwarfPubTypesSection());
2755 EmitDifference("pubtypes_end", ModuleCU->getID(),
2756 "pubtypes_begin", ModuleCU->getID(), true);
2757 Asm->EOL("Length of Public Types Info");
2759 EmitLabel("pubtypes_begin", ModuleCU->getID());
2761 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2763 EmitSectionOffset("info_begin", "section_info",
2764 ModuleCU->getID(), 0, true, false);
2765 Asm->EOL("Offset of Compilation ModuleCU Info");
2767 EmitDifference("info_end", ModuleCU->getID(), "info_begin", ModuleCU->getID(),
2769 Asm->EOL("Compilation ModuleCU Length");
2771 const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
2772 for (StringMap<DIE*>::const_iterator
2773 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2774 const char *Name = GI->getKeyData();
2775 DIE * Entity = GI->second;
2777 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2778 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2781 Asm->EmitInt32(0); Asm->EOL("End Mark");
2782 EmitLabel("pubtypes_end", ModuleCU->getID());
2787 /// emitDebugStr - Emit visible names into a debug str section.
2789 void DwarfDebug::emitDebugStr() {
2790 // Check to see if it is worth the effort.
2791 if (!StringPool.empty()) {
2792 // Start the dwarf str section.
2793 Asm->OutStreamer.SwitchSection(
2794 Asm->getObjFileLowering().getDwarfStrSection());
2796 // For each of strings in the string pool.
2797 for (unsigned StringID = 1, N = StringPool.size();
2798 StringID <= N; ++StringID) {
2799 // Emit a label for reference from debug information entries.
2800 EmitLabel("string", StringID);
2802 // Emit the string itself.
2803 const std::string &String = StringPool[StringID];
2804 Asm->EmitString(String); Asm->EOL();
2811 /// emitDebugLoc - Emit visible names into a debug loc section.
2813 void DwarfDebug::emitDebugLoc() {
2814 // Start the dwarf loc section.
2815 Asm->OutStreamer.SwitchSection(
2816 Asm->getObjFileLowering().getDwarfLocSection());
2820 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2822 void DwarfDebug::EmitDebugARanges() {
2823 // Start the dwarf aranges section.
2824 Asm->OutStreamer.SwitchSection(
2825 Asm->getObjFileLowering().getDwarfARangesSection());
2829 CompileUnit *Unit = GetBaseCompileUnit();
2831 // Don't include size of length
2832 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2834 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2836 EmitReference("info_begin", Unit->getID());
2837 Asm->EOL("Offset of Compilation Unit Info");
2839 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2841 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2843 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2844 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2847 EmitReference("text_begin", 0); Asm->EOL("Address");
2848 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2850 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2851 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2857 /// emitDebugRanges - Emit visible names into a debug ranges section.
2859 void DwarfDebug::emitDebugRanges() {
2860 // Start the dwarf ranges section.
2861 Asm->OutStreamer.SwitchSection(
2862 Asm->getObjFileLowering().getDwarfRangesSection());
2866 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2868 void DwarfDebug::emitDebugMacInfo() {
2869 if (const MCSection *LineInfo =
2870 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2871 // Start the dwarf macinfo section.
2872 Asm->OutStreamer.SwitchSection(LineInfo);
2877 /// emitDebugInlineInfo - Emit inline info using following format.
2879 /// 1. length of section
2880 /// 2. Dwarf version number
2881 /// 3. address size.
2883 /// Entries (one "entry" for each function that was inlined):
2885 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2886 /// otherwise offset into __debug_str for regular function name.
2887 /// 2. offset into __debug_str section for regular function name.
2888 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2889 /// instances for the function.
2891 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2892 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2893 /// __debug_info section, and the low_pc is the starting address for the
2894 /// inlining instance.
2895 void DwarfDebug::emitDebugInlineInfo() {
2896 if (!MAI->doesDwarfUsesInlineInfoSection())
2902 Asm->OutStreamer.SwitchSection(
2903 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2905 EmitDifference("debug_inlined_end", 1,
2906 "debug_inlined_begin", 1, true);
2907 Asm->EOL("Length of Debug Inlined Information Entry");
2909 EmitLabel("debug_inlined_begin", 1);
2911 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2912 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2914 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2915 E = InlinedSPNodes.end(); I != E; ++I) {
2917 // for (ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
2918 // I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2920 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2921 = InlineInfo.find(Node);
2922 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2923 DISubprogram SP(Node);
2924 StringRef LName = SP.getLinkageName();
2925 StringRef Name = SP.getName();
2928 Asm->EmitString(Name);
2930 // Skip special LLVM prefix that is used to inform the asm printer to not
2931 // emit usual symbol prefix before the symbol name. This happens for
2932 // Objective-C symbol names and symbol whose name is replaced using GCC's
2933 // __asm__ attribute.
2935 LName = LName.substr(1);
2936 // Asm->EmitString(LName);
2937 EmitSectionOffset("string", "section_str",
2938 StringPool.idFor(LName), false, true);
2941 Asm->EOL("MIPS linkage name");
2942 // Asm->EmitString(Name);
2943 EmitSectionOffset("string", "section_str",
2944 StringPool.idFor(Name), false, true);
2945 Asm->EOL("Function name");
2946 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2948 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2949 LE = Labels.end(); LI != LE; ++LI) {
2950 DIE *SP = LI->second;
2951 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2953 if (TD->getPointerSize() == sizeof(int32_t))
2954 O << MAI->getData32bitsDirective();
2956 O << MAI->getData64bitsDirective();
2958 PrintLabelName("label", LI->first); Asm->EOL("low_pc");
2962 EmitLabel("debug_inlined_end", 1);