1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "DwarfDebug.h"
16 #include "llvm/Module.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineModuleInfo.h"
19 #include "llvm/MC/MCSection.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/Target/Mangler.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetFrameInfo.h"
25 #include "llvm/Target/TargetLoweringObjectFile.h"
26 #include "llvm/Target/TargetRegisterInfo.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/ValueHandle.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/Timer.h"
33 #include "llvm/System/Path.h"
36 //===----------------------------------------------------------------------===//
38 /// Configuration values for initial hash set sizes (log2).
40 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
44 //===----------------------------------------------------------------------===//
45 /// CompileUnit - This dwarf writer support class manages information associate
46 /// with a source file.
48 /// ID - File identifier for source.
52 /// Die - Compile unit debug information entry.
56 /// IndexTyDie - An anonymous type for index type.
59 /// GVToDieMap - Tracks the mapping of unit level debug informaton
60 /// variables to debug information entries.
61 /// FIXME : Rename GVToDieMap -> NodeToDieMap
62 DenseMap<MDNode *, DIE *> GVToDieMap;
64 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
65 /// descriptors to debug information entries using a DIEEntry proxy.
67 DenseMap<MDNode *, DIEEntry *> GVToDIEEntryMap;
69 /// Globals - A map of globally visible named entities for this unit.
71 StringMap<DIE*> Globals;
73 /// GlobalTypes - A map of globally visible types for this unit.
75 StringMap<DIE*> GlobalTypes;
78 CompileUnit(unsigned I, DIE *D)
79 : ID(I), CUDie(D), IndexTyDie(0) {}
80 ~CompileUnit() { delete CUDie; delete IndexTyDie; }
83 unsigned getID() const { return ID; }
84 DIE* getCUDie() const { return CUDie; }
85 const StringMap<DIE*> &getGlobals() const { return Globals; }
86 const StringMap<DIE*> &getGlobalTypes() const { return GlobalTypes; }
88 /// hasContent - Return true if this compile unit has something to write out.
90 bool hasContent() const { return !CUDie->getChildren().empty(); }
92 /// addGlobal - Add a new global entity to the compile unit.
94 void addGlobal(const std::string &Name, DIE *Die) { Globals[Name] = Die; }
96 /// addGlobalType - Add a new global type to the compile unit.
98 void addGlobalType(const std::string &Name, DIE *Die) {
99 GlobalTypes[Name] = Die;
102 /// getDIE - Returns the debug information entry map slot for the
103 /// specified debug variable.
104 DIE *getDIE(MDNode *N) { return GVToDieMap.lookup(N); }
106 /// insertDIE - Insert DIE into the map.
107 void insertDIE(MDNode *N, DIE *D) {
108 GVToDieMap.insert(std::make_pair(N, D));
111 /// getDIEEntry - Returns the debug information entry for the speciefied
113 DIEEntry *getDIEEntry(MDNode *N) {
114 DenseMap<MDNode *, DIEEntry *>::iterator I = GVToDIEEntryMap.find(N);
115 if (I == GVToDIEEntryMap.end())
120 /// insertDIEEntry - Insert debug information entry into the map.
121 void insertDIEEntry(MDNode *N, DIEEntry *E) {
122 GVToDIEEntryMap.insert(std::make_pair(N, E));
125 /// addDie - Adds or interns the DIE to the compile unit.
127 void addDie(DIE *Buffer) {
128 this->CUDie->addChild(Buffer);
131 // getIndexTyDie - Get an anonymous type for index type.
132 DIE *getIndexTyDie() {
136 // setIndexTyDie - Set D as anonymous type for index which can be reused
138 void setIndexTyDie(DIE *D) {
144 //===----------------------------------------------------------------------===//
145 /// DbgVariable - This class is used to track local variable information.
148 DIVariable Var; // Variable Descriptor.
149 unsigned FrameIndex; // Variable frame index.
150 DbgVariable *AbstractVar; // Abstract variable for this variable.
153 DbgVariable(DIVariable V, unsigned I)
154 : Var(V), FrameIndex(I), AbstractVar(0), TheDIE(0) {}
157 DIVariable getVariable() const { return Var; }
158 unsigned getFrameIndex() const { return FrameIndex; }
159 void setAbstractVariable(DbgVariable *V) { AbstractVar = V; }
160 DbgVariable *getAbstractVariable() const { return AbstractVar; }
161 void setDIE(DIE *D) { TheDIE = D; }
162 DIE *getDIE() const { return TheDIE; }
165 //===----------------------------------------------------------------------===//
166 /// DbgScope - This class is used to track scope information.
169 DbgScope *Parent; // Parent to this scope.
170 DIDescriptor Desc; // Debug info descriptor for scope.
171 // Location at which this scope is inlined.
172 AssertingVH<MDNode> InlinedAtLocation;
173 bool AbstractScope; // Abstract Scope
174 unsigned StartLabelID; // Label ID of the beginning of scope.
175 unsigned EndLabelID; // Label ID of the end of scope.
176 const MachineInstr *LastInsn; // Last instruction of this scope.
177 const MachineInstr *FirstInsn; // First instruction of this scope.
178 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
179 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
181 // Private state for dump()
182 mutable unsigned IndentLevel;
184 DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0)
185 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
186 StartLabelID(0), EndLabelID(0),
187 LastInsn(0), FirstInsn(0), IndentLevel(0) {}
191 DbgScope *getParent() const { return Parent; }
192 void setParent(DbgScope *P) { Parent = P; }
193 DIDescriptor getDesc() const { return Desc; }
194 MDNode *getInlinedAt() const {
195 return InlinedAtLocation;
197 MDNode *getScopeNode() const { return Desc.getNode(); }
198 unsigned getStartLabelID() const { return StartLabelID; }
199 unsigned getEndLabelID() const { return EndLabelID; }
200 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
201 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
202 void setStartLabelID(unsigned S) { StartLabelID = S; }
203 void setEndLabelID(unsigned E) { EndLabelID = E; }
204 void setLastInsn(const MachineInstr *MI) { LastInsn = MI; }
205 const MachineInstr *getLastInsn() { return LastInsn; }
206 void setFirstInsn(const MachineInstr *MI) { FirstInsn = MI; }
207 void setAbstractScope() { AbstractScope = true; }
208 bool isAbstractScope() const { return AbstractScope; }
209 const MachineInstr *getFirstInsn() { return FirstInsn; }
211 /// addScope - Add a scope to the scope.
213 void addScope(DbgScope *S) { Scopes.push_back(S); }
215 /// addVariable - Add a variable to the scope.
217 void addVariable(DbgVariable *V) { Variables.push_back(V); }
219 void fixInstructionMarkers(DenseMap<const MachineInstr *,
220 unsigned> &MIIndexMap) {
221 assert (getFirstInsn() && "First instruction is missing!");
223 // Use the end of last child scope as end of this scope.
224 SmallVector<DbgScope *, 4> &Scopes = getScopes();
225 const MachineInstr *LastInsn = getFirstInsn();
227 if (Scopes.empty()) {
228 assert (getLastInsn() && "Inner most scope does not have last insn!");
231 for (SmallVector<DbgScope *, 4>::iterator SI = Scopes.begin(),
232 SE = Scopes.end(); SI != SE; ++SI) {
234 DS->fixInstructionMarkers(MIIndexMap);
235 const MachineInstr *DSLastInsn = DS->getLastInsn();
236 unsigned DSI = MIIndexMap[DSLastInsn];
238 LastInsn = DSLastInsn;
243 unsigned CurrentLastInsnIndex = 0;
244 if (const MachineInstr *CL = getLastInsn())
245 CurrentLastInsnIndex = MIIndexMap[CL];
246 unsigned FIndex = MIIndexMap[getFirstInsn()];
248 // Set LastInsn as the last instruction for this scope only if
250 // 1) this scope's first instruction and
251 // 2) current last instruction for this scope, if any.
252 if (LIndex >= CurrentLastInsnIndex && LIndex >= FIndex)
253 setLastInsn(LastInsn);
262 void DbgScope::dump() const {
263 raw_ostream &err = dbgs();
264 err.indent(IndentLevel);
265 MDNode *N = Desc.getNode();
267 err << " [" << StartLabelID << ", " << EndLabelID << "]\n";
269 err << "Abstract Scope\n";
273 err << "Children ...\n";
274 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
275 if (Scopes[i] != this)
282 DbgScope::~DbgScope() {
283 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
285 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
289 } // end llvm namespace
291 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T)
292 : DwarfPrinter(OS, A, T), ModuleCU(0),
293 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
294 DIEValues(), StringPool(),
295 SectionSourceLines(), didInitial(false), shouldEmit(false),
296 CurrentFnDbgScope(0), DebugTimer(0) {
297 if (TimePassesIsEnabled)
298 DebugTimer = new Timer("Dwarf Debug Writer");
300 DwarfDebug::~DwarfDebug() {
301 for (unsigned j = 0, M = DIEValues.size(); j < M; ++j)
307 /// assignAbbrevNumber - Define a unique number for the abbreviation.
309 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
310 // Profile the node so that we can make it unique.
314 // Check the set for priors.
315 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
317 // If it's newly added.
318 if (InSet == &Abbrev) {
319 // Add to abbreviation list.
320 Abbreviations.push_back(&Abbrev);
322 // Assign the vector position + 1 as its number.
323 Abbrev.setNumber(Abbreviations.size());
325 // Assign existing abbreviation number.
326 Abbrev.setNumber(InSet->getNumber());
330 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
331 /// information entry.
332 DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
333 DIEEntry *Value = new DIEEntry(Entry);
334 DIEValues.push_back(Value);
338 /// addUInt - Add an unsigned integer attribute data and value.
340 void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
341 unsigned Form, uint64_t Integer) {
342 if (!Form) Form = DIEInteger::BestForm(false, Integer);
343 DIEValue *Value = new DIEInteger(Integer);
344 DIEValues.push_back(Value);
345 Die->addValue(Attribute, Form, Value);
348 /// addSInt - Add an signed integer attribute data and value.
350 void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
351 unsigned Form, int64_t Integer) {
352 if (!Form) Form = DIEInteger::BestForm(true, Integer);
353 DIEValue *Value = new DIEInteger(Integer);
354 DIEValues.push_back(Value);
355 Die->addValue(Attribute, Form, Value);
358 /// addString - Add a string attribute data and value. DIEString only
359 /// keeps string reference.
360 void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
362 DIEValue *Value = new DIEString(String);
363 DIEValues.push_back(Value);
364 Die->addValue(Attribute, Form, Value);
367 /// addLabel - Add a Dwarf label attribute data and value.
369 void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
370 const MCSymbol *Label) {
371 DIEValue *Value = new DIELabel(Label);
372 DIEValues.push_back(Value);
373 Die->addValue(Attribute, Form, Value);
376 /// addSectionOffset - Add a section offset label attribute data and value.
378 void DwarfDebug::addSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
379 const MCSymbol *Label,const MCSymbol *Section,
381 DIEValue *Value = new DIESectionOffset(Label, Section, isEH);
382 DIEValues.push_back(Value);
383 Die->addValue(Attribute, Form, Value);
386 /// addDelta - Add a label delta attribute data and value.
388 void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
389 const MCSymbol *Hi, const MCSymbol *Lo) {
390 DIEValue *Value = new DIEDelta(Hi, Lo);
391 DIEValues.push_back(Value);
392 Die->addValue(Attribute, Form, Value);
395 /// addBlock - Add block data.
397 void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
399 Block->ComputeSize(TD);
400 DIEValues.push_back(Block);
401 Die->addValue(Attribute, Block->BestForm(), Block);
404 /// addSourceLine - Add location information to specified debug information
406 void DwarfDebug::addSourceLine(DIE *Die, const DIVariable *V) {
407 // If there is no compile unit specified, don't add a line #.
408 if (!V->getCompileUnit().Verify())
411 unsigned Line = V->getLineNumber();
412 unsigned FileID = GetOrCreateSourceID(V->getContext().getDirectory(),
413 V->getContext().getFilename());
414 assert(FileID && "Invalid file id");
415 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
416 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
419 /// addSourceLine - Add location information to specified debug information
421 void DwarfDebug::addSourceLine(DIE *Die, const DIGlobal *G) {
422 // If there is no compile unit specified, don't add a line #.
423 if (!G->getCompileUnit().Verify())
426 unsigned Line = G->getLineNumber();
427 unsigned FileID = GetOrCreateSourceID(G->getContext().getDirectory(),
428 G->getContext().getFilename());
429 assert(FileID && "Invalid file id");
430 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
431 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
434 /// addSourceLine - Add location information to specified debug information
436 void DwarfDebug::addSourceLine(DIE *Die, const DISubprogram *SP) {
437 // If there is no compile unit specified, don't add a line #.
438 if (!SP->getCompileUnit().Verify())
440 // If the line number is 0, don't add it.
441 if (SP->getLineNumber() == 0)
444 unsigned Line = SP->getLineNumber();
445 if (!SP->getContext().Verify())
447 unsigned FileID = GetOrCreateSourceID(SP->getContext().getDirectory(),
448 SP->getContext().getFilename());
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 DIType *Ty) {
457 // If there is no compile unit specified, don't add a line #.
458 DICompileUnit CU = Ty->getCompileUnit();
462 unsigned Line = Ty->getLineNumber();
463 if (!Ty->getContext().Verify())
465 unsigned FileID = GetOrCreateSourceID(Ty->getContext().getDirectory(),
466 Ty->getContext().getFilename());
467 assert(FileID && "Invalid file id");
468 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
469 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
472 /// addSourceLine - Add location information to specified debug information
474 void DwarfDebug::addSourceLine(DIE *Die, const DINameSpace *NS) {
475 // If there is no compile unit specified, don't add a line #.
476 if (!NS->getCompileUnit().Verify())
479 unsigned Line = NS->getLineNumber();
480 StringRef FN = NS->getFilename();
481 StringRef Dir = NS->getDirectory();
483 unsigned FileID = GetOrCreateSourceID(Dir, FN);
484 assert(FileID && "Invalid file id");
485 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
486 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
489 /* Byref variables, in Blocks, are declared by the programmer as
490 "SomeType VarName;", but the compiler creates a
491 __Block_byref_x_VarName struct, and gives the variable VarName
492 either the struct, or a pointer to the struct, as its type. This
493 is necessary for various behind-the-scenes things the compiler
494 needs to do with by-reference variables in blocks.
496 However, as far as the original *programmer* is concerned, the
497 variable should still have type 'SomeType', as originally declared.
499 The following function dives into the __Block_byref_x_VarName
500 struct to find the original type of the variable. This will be
501 passed back to the code generating the type for the Debug
502 Information Entry for the variable 'VarName'. 'VarName' will then
503 have the original type 'SomeType' in its debug information.
505 The original type 'SomeType' will be the type of the field named
506 'VarName' inside the __Block_byref_x_VarName struct.
508 NOTE: In order for this to not completely fail on the debugger
509 side, the Debug Information Entry for the variable VarName needs to
510 have a DW_AT_location that tells the debugger how to unwind through
511 the pointers and __Block_byref_x_VarName struct to find the actual
512 value of the variable. The function addBlockByrefType does this. */
514 /// Find the type the programmer originally declared the variable to be
515 /// and return that type.
517 DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) {
520 unsigned tag = Ty.getTag();
522 if (tag == dwarf::DW_TAG_pointer_type) {
523 DIDerivedType DTy = DIDerivedType(Ty.getNode());
524 subType = DTy.getTypeDerivedFrom();
527 DICompositeType blockStruct = DICompositeType(subType.getNode());
528 DIArray Elements = blockStruct.getTypeArray();
530 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
531 DIDescriptor Element = Elements.getElement(i);
532 DIDerivedType DT = DIDerivedType(Element.getNode());
533 if (Name == DT.getName())
534 return (DT.getTypeDerivedFrom());
540 /// addComplexAddress - Start with the address based on the location provided,
541 /// and generate the DWARF information necessary to find the actual variable
542 /// given the extra address information encoded in the DIVariable, starting from
543 /// the starting location. Add the DWARF information to the die.
545 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
547 const MachineLocation &Location) {
548 const DIVariable &VD = DV->getVariable();
549 DIType Ty = VD.getType();
551 // Decode the original location, and use that as the start of the byref
552 // variable's location.
553 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
554 DIEBlock *Block = new DIEBlock();
556 if (Location.isReg()) {
558 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
560 Reg = Reg - dwarf::DW_OP_reg0;
561 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
562 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
566 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
568 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
569 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
572 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
575 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
576 uint64_t Element = VD.getAddrElement(i);
578 if (Element == DIFactory::OpPlus) {
579 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
580 addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
581 } else if (Element == DIFactory::OpDeref) {
582 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
583 } else llvm_unreachable("unknown DIFactory Opcode");
586 // Now attach the location information to the DIE.
587 addBlock(Die, Attribute, 0, Block);
590 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
591 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
592 gives the variable VarName either the struct, or a pointer to the struct, as
593 its type. This is necessary for various behind-the-scenes things the
594 compiler needs to do with by-reference variables in Blocks.
596 However, as far as the original *programmer* is concerned, the variable
597 should still have type 'SomeType', as originally declared.
599 The function getBlockByrefType dives into the __Block_byref_x_VarName
600 struct to find the original type of the variable, which is then assigned to
601 the variable's Debug Information Entry as its real type. So far, so good.
602 However now the debugger will expect the variable VarName to have the type
603 SomeType. So we need the location attribute for the variable to be an
604 expression that explains to the debugger how to navigate through the
605 pointers and struct to find the actual variable of type SomeType.
607 The following function does just that. We start by getting
608 the "normal" location for the variable. This will be the location
609 of either the struct __Block_byref_x_VarName or the pointer to the
610 struct __Block_byref_x_VarName.
612 The struct will look something like:
614 struct __Block_byref_x_VarName {
616 struct __Block_byref_x_VarName *forwarding;
617 ... <various other fields>
619 ... <maybe more fields>
622 If we are given the struct directly (as our starting point) we
623 need to tell the debugger to:
625 1). Add the offset of the forwarding field.
627 2). Follow that pointer to get the real __Block_byref_x_VarName
628 struct to use (the real one may have been copied onto the heap).
630 3). Add the offset for the field VarName, to find the actual variable.
632 If we started with a pointer to the struct, then we need to
633 dereference that pointer first, before the other steps.
634 Translating this into DWARF ops, we will need to append the following
635 to the current location description for the variable:
637 DW_OP_deref -- optional, if we start with a pointer
638 DW_OP_plus_uconst <forward_fld_offset>
640 DW_OP_plus_uconst <varName_fld_offset>
642 That is what this function does. */
644 /// addBlockByrefAddress - Start with the address based on the location
645 /// provided, and generate the DWARF information necessary to find the
646 /// actual Block variable (navigating the Block struct) based on the
647 /// starting location. Add the DWARF information to the die. For
648 /// more information, read large comment just above here.
650 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
652 const MachineLocation &Location) {
653 const DIVariable &VD = DV->getVariable();
654 DIType Ty = VD.getType();
656 unsigned Tag = Ty.getTag();
657 bool isPointer = false;
659 StringRef varName = VD.getName();
661 if (Tag == dwarf::DW_TAG_pointer_type) {
662 DIDerivedType DTy = DIDerivedType(Ty.getNode());
663 TmpTy = DTy.getTypeDerivedFrom();
667 DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
669 // Find the __forwarding field and the variable field in the __Block_byref
671 DIArray Fields = blockStruct.getTypeArray();
672 DIDescriptor varField = DIDescriptor();
673 DIDescriptor forwardingField = DIDescriptor();
675 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
676 DIDescriptor Element = Fields.getElement(i);
677 DIDerivedType DT = DIDerivedType(Element.getNode());
678 StringRef fieldName = DT.getName();
679 if (fieldName == "__forwarding")
680 forwardingField = Element;
681 else if (fieldName == varName)
685 // Get the offsets for the forwarding field and the variable field.
686 unsigned int forwardingFieldOffset =
687 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
688 unsigned int varFieldOffset =
689 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
691 // Decode the original location, and use that as the start of the byref
692 // variable's location.
693 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
694 DIEBlock *Block = new DIEBlock();
696 if (Location.isReg()) {
698 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
700 Reg = Reg - dwarf::DW_OP_reg0;
701 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
702 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
706 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
708 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
709 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
712 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
715 // If we started with a pointer to the __Block_byref... struct, then
716 // the first thing we need to do is dereference the pointer (DW_OP_deref).
718 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
720 // Next add the offset for the '__forwarding' field:
721 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
722 // adding the offset if it's 0.
723 if (forwardingFieldOffset > 0) {
724 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
725 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
728 // Now dereference the __forwarding field to get to the real __Block_byref
729 // struct: DW_OP_deref.
730 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
732 // Now that we've got the real __Block_byref... struct, add the offset
733 // for the variable's field to get to the location of the actual variable:
734 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
735 if (varFieldOffset > 0) {
736 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
737 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
740 // Now attach the location information to the DIE.
741 addBlock(Die, Attribute, 0, Block);
744 /// addAddress - Add an address attribute to a die based on the location
746 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
747 const MachineLocation &Location) {
748 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
749 DIEBlock *Block = new DIEBlock();
751 if (Location.isReg()) {
753 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
755 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
756 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
760 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
762 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
763 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
766 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
769 addBlock(Die, Attribute, 0, Block);
772 /// addToContextOwner - Add Die into the list of its context owner's children.
773 void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
774 if (Context.isType()) {
775 DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context.getNode()));
776 ContextDIE->addChild(Die);
777 } else if (Context.isNameSpace()) {
778 DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context.getNode()));
779 ContextDIE->addChild(Die);
780 } else if (DIE *ContextDIE = ModuleCU->getDIE(Context.getNode()))
781 ContextDIE->addChild(Die);
783 ModuleCU->addDie(Die);
786 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
788 DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
789 DIE *TyDIE = ModuleCU->getDIE(Ty.getNode());
794 TyDIE = new DIE(dwarf::DW_TAG_base_type);
795 ModuleCU->insertDIE(Ty.getNode(), TyDIE);
796 if (Ty.isBasicType())
797 constructTypeDIE(*TyDIE, DIBasicType(Ty.getNode()));
798 else if (Ty.isCompositeType())
799 constructTypeDIE(*TyDIE, DICompositeType(Ty.getNode()));
801 assert(Ty.isDerivedType() && "Unknown kind of DIType");
802 constructTypeDIE(*TyDIE, DIDerivedType(Ty.getNode()));
805 addToContextOwner(TyDIE, Ty.getContext());
809 /// addType - Add a new type attribute to the specified entity.
810 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
814 // Check for pre-existence.
815 DIEEntry *Entry = ModuleCU->getDIEEntry(Ty.getNode());
816 // If it exists then use the existing value.
818 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
823 Entry = createDIEEntry();
824 ModuleCU->insertDIEEntry(Ty.getNode(), Entry);
827 DIE *Buffer = getOrCreateTypeDIE(Ty);
829 Entry->setEntry(Buffer);
830 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
833 /// constructTypeDIE - Construct basic type die from DIBasicType.
834 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
835 // Get core information.
836 StringRef Name = BTy.getName();
837 Buffer.setTag(dwarf::DW_TAG_base_type);
838 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
841 // Add name if not anonymous or intermediate type.
843 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
844 uint64_t Size = BTy.getSizeInBits() >> 3;
845 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
848 /// constructTypeDIE - Construct derived type die from DIDerivedType.
849 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
850 // Get core information.
851 StringRef Name = DTy.getName();
852 uint64_t Size = DTy.getSizeInBits() >> 3;
853 unsigned Tag = DTy.getTag();
855 // FIXME - Workaround for templates.
856 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
860 // Map to main type, void will not have a type.
861 DIType FromTy = DTy.getTypeDerivedFrom();
862 addType(&Buffer, FromTy);
864 // Add name if not anonymous or intermediate type.
866 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
868 // Add size if non-zero (derived types might be zero-sized.)
870 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
872 // Add source line info if available and TyDesc is not a forward declaration.
873 if (!DTy.isForwardDecl())
874 addSourceLine(&Buffer, &DTy);
877 /// constructTypeDIE - Construct type DIE from DICompositeType.
878 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
879 // Get core information.
880 StringRef Name = CTy.getName();
882 uint64_t Size = CTy.getSizeInBits() >> 3;
883 unsigned Tag = CTy.getTag();
887 case dwarf::DW_TAG_vector_type:
888 case dwarf::DW_TAG_array_type:
889 constructArrayTypeDIE(Buffer, &CTy);
891 case dwarf::DW_TAG_enumeration_type: {
892 DIArray Elements = CTy.getTypeArray();
894 // Add enumerators to enumeration type.
895 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
897 DIDescriptor Enum(Elements.getElement(i).getNode());
898 if (Enum.isEnumerator()) {
899 ElemDie = constructEnumTypeDIE(DIEnumerator(Enum.getNode()));
900 Buffer.addChild(ElemDie);
905 case dwarf::DW_TAG_subroutine_type: {
907 DIArray Elements = CTy.getTypeArray();
908 DIDescriptor RTy = Elements.getElement(0);
909 addType(&Buffer, DIType(RTy.getNode()));
911 // Add prototype flag.
912 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
915 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
916 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
917 DIDescriptor Ty = Elements.getElement(i);
918 addType(Arg, DIType(Ty.getNode()));
919 Buffer.addChild(Arg);
923 case dwarf::DW_TAG_structure_type:
924 case dwarf::DW_TAG_union_type:
925 case dwarf::DW_TAG_class_type: {
926 // Add elements to structure type.
927 DIArray Elements = CTy.getTypeArray();
929 // A forward struct declared type may not have elements available.
930 unsigned N = Elements.getNumElements();
934 // Add elements to structure type.
935 for (unsigned i = 0; i < N; ++i) {
936 DIDescriptor Element = Elements.getElement(i);
938 if (Element.isSubprogram())
939 ElemDie = createSubprogramDIE(DISubprogram(Element.getNode()));
940 else if (Element.isVariable()) {
941 DIVariable DV(Element.getNode());
942 ElemDie = new DIE(dwarf::DW_TAG_variable);
943 addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
945 addType(ElemDie, DV.getType());
946 addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
947 addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
948 addSourceLine(ElemDie, &DV);
949 } else if (Element.isDerivedType())
950 ElemDie = createMemberDIE(DIDerivedType(Element.getNode()));
953 Buffer.addChild(ElemDie);
956 if (CTy.isAppleBlockExtension())
957 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
959 unsigned RLang = CTy.getRunTimeLang();
961 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
962 dwarf::DW_FORM_data1, RLang);
964 DICompositeType ContainingType = CTy.getContainingType();
965 if (DIDescriptor(ContainingType.getNode()).isCompositeType())
966 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
967 getOrCreateTypeDIE(DIType(ContainingType.getNode())));
974 // Add name if not anonymous or intermediate type.
976 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
978 if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type ||
979 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
980 // Add size if non-zero (derived types might be zero-sized.)
982 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
984 // Add zero size if it is not a forward declaration.
985 if (CTy.isForwardDecl())
986 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
988 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
991 // Add source line info if available.
992 if (!CTy.isForwardDecl())
993 addSourceLine(&Buffer, &CTy);
997 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
998 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
999 int64_t L = SR.getLo();
1000 int64_t H = SR.getHi();
1001 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1003 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1005 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1006 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1008 Buffer.addChild(DW_Subrange);
1011 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1012 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1013 DICompositeType *CTy) {
1014 Buffer.setTag(dwarf::DW_TAG_array_type);
1015 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1016 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1018 // Emit derived type.
1019 addType(&Buffer, CTy->getTypeDerivedFrom());
1020 DIArray Elements = CTy->getTypeArray();
1022 // Get an anonymous type for index type.
1023 DIE *IdxTy = ModuleCU->getIndexTyDie();
1025 // Construct an anonymous type for index type.
1026 IdxTy = new DIE(dwarf::DW_TAG_base_type);
1027 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1028 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1029 dwarf::DW_ATE_signed);
1030 ModuleCU->addDie(IdxTy);
1031 ModuleCU->setIndexTyDie(IdxTy);
1034 // Add subranges to array type.
1035 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1036 DIDescriptor Element = Elements.getElement(i);
1037 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1038 constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
1042 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1043 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1044 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1045 StringRef Name = ETy.getName();
1046 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1047 int64_t Value = ETy.getEnumValue();
1048 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1052 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1053 /// printer to not emit usual symbol prefix before the symbol name is used then
1054 /// return linkage name after skipping this special LLVM prefix.
1055 static StringRef getRealLinkageName(StringRef LinkageName) {
1057 if (LinkageName.startswith(StringRef(&One, 1)))
1058 return LinkageName.substr(1);
1062 /// createGlobalVariableDIE - Create new DIE using GV.
1063 DIE *DwarfDebug::createGlobalVariableDIE(const DIGlobalVariable &GV) {
1064 // If the global variable was optmized out then no need to create debug info
1066 if (!GV.getGlobal()) return NULL;
1067 if (GV.getDisplayName().empty()) return NULL;
1069 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1070 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1071 GV.getDisplayName());
1073 StringRef LinkageName = GV.getLinkageName();
1074 if (!LinkageName.empty())
1075 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1076 getRealLinkageName(LinkageName));
1078 addType(GVDie, GV.getType());
1079 if (!GV.isLocalToUnit())
1080 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1081 addSourceLine(GVDie, &GV);
1086 /// createMemberDIE - Create new member DIE.
1087 DIE *DwarfDebug::createMemberDIE(const DIDerivedType &DT) {
1088 DIE *MemberDie = new DIE(DT.getTag());
1089 StringRef Name = DT.getName();
1091 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1093 addType(MemberDie, DT.getTypeDerivedFrom());
1095 addSourceLine(MemberDie, &DT);
1097 DIEBlock *MemLocationDie = new DIEBlock();
1098 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1100 uint64_t Size = DT.getSizeInBits();
1101 uint64_t FieldSize = DT.getOriginalTypeSize();
1103 if (Size != FieldSize) {
1105 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1106 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1108 uint64_t Offset = DT.getOffsetInBits();
1109 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1110 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1111 uint64_t FieldOffset = (HiMark - FieldSize);
1112 Offset -= FieldOffset;
1114 // Maybe we need to work from the other end.
1115 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1116 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1118 // Here WD_AT_data_member_location points to the anonymous
1119 // field that includes this bit field.
1120 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1123 // This is not a bitfield.
1124 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1126 if (DT.getTag() == dwarf::DW_TAG_inheritance
1127 && DT.isVirtual()) {
1129 // For C++, virtual base classes are not at fixed offset. Use following
1130 // expression to extract appropriate offset from vtable.
1131 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1133 DIEBlock *VBaseLocationDie = new DIEBlock();
1134 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1135 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1136 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1137 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1138 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1139 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1140 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1142 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1145 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1147 if (DT.isProtected())
1148 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1149 dwarf::DW_ACCESS_protected);
1150 else if (DT.isPrivate())
1151 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1152 dwarf::DW_ACCESS_private);
1153 else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1154 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1155 dwarf::DW_ACCESS_public);
1157 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1158 dwarf::DW_VIRTUALITY_virtual);
1162 /// createSubprogramDIE - Create new DIE using SP.
1163 DIE *DwarfDebug::createSubprogramDIE(const DISubprogram &SP, bool MakeDecl) {
1164 DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1168 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1169 // Constructors and operators for anonymous aggregates do not have names.
1170 if (!SP.getName().empty())
1171 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1173 StringRef LinkageName = SP.getLinkageName();
1174 if (!LinkageName.empty())
1175 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1176 getRealLinkageName(LinkageName));
1178 addSourceLine(SPDie, &SP);
1180 // Add prototyped tag, if C or ObjC.
1181 unsigned Lang = SP.getCompileUnit().getLanguage();
1182 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1183 Lang == dwarf::DW_LANG_ObjC)
1184 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1187 DICompositeType SPTy = SP.getType();
1188 DIArray Args = SPTy.getTypeArray();
1189 unsigned SPTag = SPTy.getTag();
1191 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1192 addType(SPDie, SPTy);
1194 addType(SPDie, DIType(Args.getElement(0).getNode()));
1196 unsigned VK = SP.getVirtuality();
1198 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1199 DIEBlock *Block = new DIEBlock();
1200 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1201 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1202 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1203 ContainingTypeMap.insert(std::make_pair(SPDie,
1204 SP.getContainingType().getNode()));
1207 if (MakeDecl || !SP.isDefinition()) {
1208 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1210 // Add arguments. Do not add arguments for subprogram definition. They will
1211 // be handled while processing variables.
1212 DICompositeType SPTy = SP.getType();
1213 DIArray Args = SPTy.getTypeArray();
1214 unsigned SPTag = SPTy.getTag();
1216 if (SPTag == dwarf::DW_TAG_subroutine_type)
1217 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1218 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1219 DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1221 if (ATy.isArtificial())
1222 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1223 SPDie->addChild(Arg);
1227 if (SP.isArtificial())
1228 addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1230 // DW_TAG_inlined_subroutine may refer to this DIE.
1231 ModuleCU->insertDIE(SP.getNode(), SPDie);
1235 /// getUpdatedDbgScope - Find or create DbgScope assicated with the instruction.
1236 /// Initialize scope and update scope hierarchy.
1237 DbgScope *DwarfDebug::getUpdatedDbgScope(MDNode *N, const MachineInstr *MI,
1238 MDNode *InlinedAt) {
1239 assert (N && "Invalid Scope encoding!");
1240 assert (MI && "Missing machine instruction!");
1241 bool GetConcreteScope = (MI && InlinedAt);
1243 DbgScope *NScope = NULL;
1246 NScope = DbgScopeMap.lookup(InlinedAt);
1248 NScope = DbgScopeMap.lookup(N);
1249 assert (NScope && "Unable to find working scope!");
1251 if (NScope->getFirstInsn())
1254 DbgScope *Parent = NULL;
1255 if (GetConcreteScope) {
1256 DILocation IL(InlinedAt);
1257 Parent = getUpdatedDbgScope(IL.getScope().getNode(), MI,
1258 IL.getOrigLocation().getNode());
1259 assert (Parent && "Unable to find Parent scope!");
1260 NScope->setParent(Parent);
1261 Parent->addScope(NScope);
1262 } else if (DIDescriptor(N).isLexicalBlock()) {
1263 DILexicalBlock DB(N);
1264 Parent = getUpdatedDbgScope(DB.getContext().getNode(), MI, InlinedAt);
1265 NScope->setParent(Parent);
1266 Parent->addScope(NScope);
1269 NScope->setFirstInsn(MI);
1271 if (!Parent && !InlinedAt) {
1272 StringRef SPName = DISubprogram(N).getLinkageName();
1273 if (SPName == MF->getFunction()->getName())
1274 CurrentFnDbgScope = NScope;
1277 if (GetConcreteScope) {
1278 ConcreteScopes[InlinedAt] = NScope;
1279 getOrCreateAbstractScope(N);
1285 DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1286 assert (N && "Invalid Scope encoding!");
1288 DbgScope *AScope = AbstractScopes.lookup(N);
1292 DbgScope *Parent = NULL;
1294 DIDescriptor Scope(N);
1295 if (Scope.isLexicalBlock()) {
1296 DILexicalBlock DB(N);
1297 DIDescriptor ParentDesc = DB.getContext();
1298 Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1301 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1304 Parent->addScope(AScope);
1305 AScope->setAbstractScope();
1306 AbstractScopes[N] = AScope;
1307 if (DIDescriptor(N).isSubprogram())
1308 AbstractScopesList.push_back(AScope);
1312 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1313 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1314 /// If there are global variables in this scope then create and insert
1315 /// DIEs for these variables.
1316 DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
1318 DIE *SPDie = ModuleCU->getDIE(SPNode);
1319 assert (SPDie && "Unable to find subprogram DIE!");
1320 DISubprogram SP(SPNode);
1321 // There is not any need to generate specification DIE for a function
1322 // defined at compile unit level. If a function is defined inside another
1323 // function then gdb prefers the definition at top level and but does not
1324 // expect specification DIE in parent function. So avoid creating
1325 // specification DIE for a function defined inside a function.
1326 if (SP.isDefinition() && !SP.getContext().isCompileUnit()
1327 && !SP.getContext().isSubprogram()) {
1328 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1330 DICompositeType SPTy = SP.getType();
1331 DIArray Args = SPTy.getTypeArray();
1332 unsigned SPTag = SPTy.getTag();
1333 if (SPTag == dwarf::DW_TAG_subroutine_type)
1334 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1335 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1336 DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1338 if (ATy.isArtificial())
1339 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1340 SPDie->addChild(Arg);
1342 DIE *SPDeclDie = SPDie;
1343 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1344 addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1346 ModuleCU->addDie(SPDie);
1349 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1350 getDWLabel("func_begin", SubprogramCount));
1351 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1352 getDWLabel("func_end", SubprogramCount));
1353 MachineLocation Location(RI->getFrameRegister(*MF));
1354 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1356 if (!DISubprogram(SPNode).isLocalToUnit())
1357 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1362 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1363 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1364 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1365 unsigned StartID = Scope->getStartLabelID();
1366 unsigned EndID = Scope->getEndLabelID();
1368 assert(!MMI->isLabelDeleted(StartID) &&
1369 "Invalid starting label for an inlined scope!");
1370 assert(!MMI->isLabelDeleted(EndID) &&
1371 "Invalid end label for an inlined scope!");
1373 // Ignore empty scopes.
1374 if (StartID == EndID && StartID != 0)
1377 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1378 if (Scope->isAbstractScope())
1381 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1382 StartID ? getDWLabel("label", StartID)
1383 : getDWLabel("func_begin", SubprogramCount));
1384 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1385 EndID ? getDWLabel("label", EndID)
1386 : getDWLabel("func_end", SubprogramCount));
1391 /// constructInlinedScopeDIE - This scope represents inlined body of
1392 /// a function. Construct DIE to represent this concrete inlined copy
1393 /// of the function.
1394 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1395 unsigned StartID = Scope->getStartLabelID();
1396 unsigned EndID = Scope->getEndLabelID();
1397 assert(!MMI->isLabelDeleted(StartID) &&
1398 "Invalid starting label for an inlined scope!");
1399 assert(!MMI->isLabelDeleted(EndID) &&
1400 "Invalid end label for an inlined scope!");
1401 // Ignore empty scopes.
1402 if (StartID == EndID)
1404 if (!Scope->getScopeNode())
1406 DIScope DS(Scope->getScopeNode());
1407 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1409 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1410 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1411 assert (OriginDIE && "Unable to find Origin DIE!");
1412 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1413 dwarf::DW_FORM_ref4, OriginDIE);
1415 MCSymbol *StartLabel = getDWLabel("label", StartID);
1417 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1418 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1419 getDWLabel("label", EndID));
1421 InlinedSubprogramDIEs.insert(OriginDIE);
1423 // Track the start label for this inlined function.
1424 DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1425 I = InlineInfo.find(InlinedSP.getNode());
1427 if (I == InlineInfo.end()) {
1428 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartLabel,
1430 InlinedSPNodes.push_back(InlinedSP.getNode());
1432 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1434 StringPool.insert(InlinedSP.getName());
1435 StringPool.insert(getRealLinkageName(InlinedSP.getLinkageName()));
1437 DILocation DL(Scope->getInlinedAt());
1438 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1439 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1445 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1446 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1447 // Get the descriptor.
1448 const DIVariable &VD = DV->getVariable();
1449 StringRef Name = VD.getName();
1453 // Translate tag to proper Dwarf tag. The result variable is dropped for
1456 switch (VD.getTag()) {
1457 case dwarf::DW_TAG_return_variable:
1459 case dwarf::DW_TAG_arg_variable:
1460 Tag = dwarf::DW_TAG_formal_parameter;
1462 case dwarf::DW_TAG_auto_variable: // fall thru
1464 Tag = dwarf::DW_TAG_variable;
1468 // Define variable debug information entry.
1469 DIE *VariableDie = new DIE(Tag);
1473 if (DbgVariable *AV = DV->getAbstractVariable())
1474 AbsDIE = AV->getDIE();
1477 DIScope DS(Scope->getScopeNode());
1478 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1479 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1481 assert (OriginSPDIE && "Unable to find Origin DIE for the SP!");
1482 DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1483 assert (AbsDIE && "Unable to find Origin DIE for the Variable!");
1484 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1485 dwarf::DW_FORM_ref4, AbsDIE);
1488 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1489 addSourceLine(VariableDie, &VD);
1491 // Add variable type.
1492 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1493 // addresses instead.
1494 if (VD.isBlockByrefVariable())
1495 addType(VariableDie, getBlockByrefType(VD.getType(), Name));
1497 addType(VariableDie, VD.getType());
1500 // Add variable address.
1501 if (!Scope->isAbstractScope()) {
1502 MachineLocation Location;
1504 int Offset = RI->getFrameIndexReference(*MF, DV->getFrameIndex(), FrameReg);
1505 Location.set(FrameReg, Offset);
1507 if (VD.hasComplexAddress())
1508 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1509 else if (VD.isBlockByrefVariable())
1510 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1512 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1515 if (Tag == dwarf::DW_TAG_formal_parameter && VD.getType().isArtificial())
1516 addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1517 DV->setDIE(VariableDie);
1522 void DwarfDebug::addPubTypes(DISubprogram SP) {
1523 DICompositeType SPTy = SP.getType();
1524 unsigned SPTag = SPTy.getTag();
1525 if (SPTag != dwarf::DW_TAG_subroutine_type)
1528 DIArray Args = SPTy.getTypeArray();
1529 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1530 DIType ATy(Args.getElement(i).getNode());
1533 DICompositeType CATy = getDICompositeType(ATy);
1534 if (DIDescriptor(CATy.getNode()).Verify() && !CATy.getName().empty()) {
1535 if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode()))
1536 ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry());
1541 /// constructScopeDIE - Construct a DIE for this scope.
1542 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1543 if (!Scope || !Scope->getScopeNode())
1546 DIScope DS(Scope->getScopeNode());
1547 DIE *ScopeDIE = NULL;
1548 if (Scope->getInlinedAt())
1549 ScopeDIE = constructInlinedScopeDIE(Scope);
1550 else if (DS.isSubprogram()) {
1551 if (Scope->isAbstractScope())
1552 ScopeDIE = ModuleCU->getDIE(DS.getNode());
1554 ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
1557 ScopeDIE = constructLexicalScopeDIE(Scope);
1558 if (!ScopeDIE) return NULL;
1561 // Add variables to scope.
1562 SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1563 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1564 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1566 ScopeDIE->addChild(VariableDIE);
1569 // Add nested scopes.
1570 SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1571 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1572 // Define the Scope debug information entry.
1573 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1575 ScopeDIE->addChild(NestedDIE);
1578 if (DS.isSubprogram())
1579 addPubTypes(DISubprogram(DS.getNode()));
1584 /// GetOrCreateSourceID - Look up the source id with the given directory and
1585 /// source file names. If none currently exists, create a new id and insert it
1586 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1588 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName) {
1590 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1591 if (DI != DirectoryIdMap.end()) {
1592 DId = DI->getValue();
1594 DId = DirectoryNames.size() + 1;
1595 DirectoryIdMap[DirName] = DId;
1596 DirectoryNames.push_back(DirName);
1600 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1601 if (FI != SourceFileIdMap.end()) {
1602 FId = FI->getValue();
1604 FId = SourceFileNames.size() + 1;
1605 SourceFileIdMap[FileName] = FId;
1606 SourceFileNames.push_back(FileName);
1609 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1610 SourceIdMap.find(std::make_pair(DId, FId));
1611 if (SI != SourceIdMap.end())
1614 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1615 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1616 SourceIds.push_back(std::make_pair(DId, FId));
1621 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1622 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1623 DIE *NDie = ModuleCU->getDIE(NS.getNode());
1626 NDie = new DIE(dwarf::DW_TAG_namespace);
1627 ModuleCU->insertDIE(NS.getNode(), NDie);
1628 if (!NS.getName().empty())
1629 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1630 addSourceLine(NDie, &NS);
1631 addToContextOwner(NDie, NS.getContext());
1635 CompileUnit *DwarfDebug::constructCompileUnit(MDNode *N) {
1636 DICompileUnit DIUnit(N);
1637 StringRef FN = DIUnit.getFilename();
1638 StringRef Dir = DIUnit.getDirectory();
1639 unsigned ID = GetOrCreateSourceID(Dir, FN);
1641 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1642 // FIXME: Why getting the delta between two identical labels??
1643 addSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1644 getTempLabel("section_line"), getTempLabel("section_line"),
1646 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1647 DIUnit.getProducer());
1648 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1649 DIUnit.getLanguage());
1650 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1653 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1654 if (DIUnit.isOptimized())
1655 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1657 StringRef Flags = DIUnit.getFlags();
1659 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1661 unsigned RVer = DIUnit.getRunTimeVersion();
1663 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1664 dwarf::DW_FORM_data1, RVer);
1666 CompileUnit *Unit = new CompileUnit(ID, Die);
1667 if (!ModuleCU && DIUnit.isMain()) {
1668 // Use first compile unit marked as isMain as the compile unit
1676 void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
1677 DIGlobalVariable DI_GV(N);
1679 // If debug information is malformed then ignore it.
1680 if (DI_GV.Verify() == false)
1683 // Check for pre-existence.
1684 if (ModuleCU->getDIE(DI_GV.getNode()))
1687 DIE *VariableDie = createGlobalVariableDIE(DI_GV);
1692 ModuleCU->insertDIE(N, VariableDie);
1694 // Add to context owner.
1695 DIDescriptor GVContext = DI_GV.getContext();
1696 // Do not create specification DIE if context is either compile unit
1698 if (DI_GV.isDefinition() && !GVContext.isCompileUnit()
1699 && !GVContext.isSubprogram()) {
1700 // Create specification DIE.
1701 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1702 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1703 dwarf::DW_FORM_ref4, VariableDie);
1704 DIEBlock *Block = new DIEBlock();
1705 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1706 addLabel(Block, 0, dwarf::DW_FORM_udata,
1707 Asm->GetGlobalValueSymbol(DI_GV.getGlobal()));
1708 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1709 addUInt(VariableDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1710 ModuleCU->addDie(VariableSpecDIE);
1712 DIEBlock *Block = new DIEBlock();
1713 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1714 addLabel(Block, 0, dwarf::DW_FORM_udata,
1715 Asm->GetGlobalValueSymbol(DI_GV.getGlobal()));
1716 addBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1718 addToContextOwner(VariableDie, GVContext);
1720 // Expose as global. FIXME - need to check external flag.
1721 ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1723 DIType GTy = DI_GV.getType();
1724 if (GTy.isCompositeType() && !GTy.getName().empty()) {
1725 DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode());
1726 assert (Entry && "Missing global type!");
1727 ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry());
1732 void DwarfDebug::constructSubprogramDIE(MDNode *N) {
1735 // Check for pre-existence.
1736 if (ModuleCU->getDIE(N))
1739 if (!SP.isDefinition())
1740 // This is a method declaration which will be handled while constructing
1744 DIE *SubprogramDie = createSubprogramDIE(SP);
1747 ModuleCU->insertDIE(N, SubprogramDie);
1749 // Add to context owner.
1750 addToContextOwner(SubprogramDie, SP.getContext());
1752 // Expose as global.
1753 ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1758 /// beginModule - Emit all Dwarf sections that should come prior to the
1759 /// content. Create global DIEs and emit initial debug info sections.
1760 /// This is inovked by the target AsmPrinter.
1761 void DwarfDebug::beginModule(Module *M, MachineModuleInfo *mmi) {
1764 if (TimePassesIsEnabled)
1765 DebugTimer->startTimer();
1767 if (!MAI->doesSupportDebugInformation())
1770 DebugInfoFinder DbgFinder;
1771 DbgFinder.processModule(*M);
1773 // Create all the compile unit DIEs.
1774 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1775 E = DbgFinder.compile_unit_end(); I != E; ++I)
1776 constructCompileUnit(*I);
1781 // Create DIEs for each subprogram.
1782 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1783 E = DbgFinder.subprogram_end(); I != E; ++I)
1784 constructSubprogramDIE(*I);
1786 // Create DIEs for each global variable.
1787 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1788 E = DbgFinder.global_variable_end(); I != E; ++I)
1789 constructGlobalVariableDIE(*I);
1793 MMI->setDebugInfoAvailability(true);
1795 // Prime section data.
1796 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1798 // Print out .file directives to specify files for .loc directives. These are
1799 // printed out early so that they precede any .loc directives.
1800 if (MAI->hasDotLocAndDotFile()) {
1801 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1802 // Remember source id starts at 1.
1803 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1804 // FIXME: don't use sys::path for this! This should not depend on the
1806 sys::Path FullPath(getSourceDirectoryName(Id.first));
1808 FullPath.appendComponent(getSourceFileName(Id.second));
1809 assert(AppendOk && "Could not append filename to directory!");
1811 Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
1815 // Emit initial sections
1818 if (TimePassesIsEnabled)
1819 DebugTimer->stopTimer();
1822 /// endModule - Emit all Dwarf sections that should come after the content.
1824 void DwarfDebug::endModule() {
1828 if (TimePassesIsEnabled)
1829 DebugTimer->startTimer();
1831 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1832 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1833 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1835 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1838 // Insert top level DIEs.
1839 for (SmallVector<DIE *, 4>::iterator TI = TopLevelDIEsVector.begin(),
1840 TE = TopLevelDIEsVector.end(); TI != TE; ++TI)
1841 ModuleCU->getCUDie()->addChild(*TI);
1843 for (DenseMap<DIE *, MDNode *>::iterator CI = ContainingTypeMap.begin(),
1844 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1845 DIE *SPDie = CI->first;
1846 MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1848 DIE *NDie = ModuleCU->getDIE(N);
1849 if (!NDie) continue;
1850 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1851 // FIXME - This is not the correct approach.
1852 // addDIEEntry(NDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1855 // Standard sections final addresses.
1856 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1857 Asm->OutStreamer.EmitLabel(getTempLabel("text_end"));
1858 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1859 Asm->OutStreamer.EmitLabel(getTempLabel("data_end"));
1861 // End text sections.
1862 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1863 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1864 Asm->OutStreamer.EmitLabel(getDWLabel("section_end", i));
1867 // Emit common frame information.
1868 emitCommonDebugFrame();
1870 // Emit function debug frame information
1871 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1872 E = DebugFrames.end(); I != E; ++I)
1873 emitFunctionDebugFrame(*I);
1875 // Compute DIE offsets and sizes.
1876 computeSizeAndOffsets();
1878 // Emit all the DIEs into a debug info section
1881 // Corresponding abbreviations into a abbrev section.
1882 emitAbbreviations();
1884 // Emit source line correspondence into a debug line section.
1887 // Emit info into a debug pubnames section.
1888 emitDebugPubNames();
1890 // Emit info into a debug pubtypes section.
1891 emitDebugPubTypes();
1893 // Emit info into a debug str section.
1896 // Emit info into a debug loc section.
1899 // Emit info into a debug aranges section.
1902 // Emit info into a debug ranges section.
1905 // Emit info into a debug macinfo section.
1908 // Emit inline info.
1909 emitDebugInlineInfo();
1911 if (TimePassesIsEnabled)
1912 DebugTimer->stopTimer();
1915 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
1916 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
1918 DILocation &ScopeLoc) {
1920 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
1922 return AbsDbgVariable;
1924 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope().getNode());
1928 AbsDbgVariable = new DbgVariable(Var, FrameIdx);
1929 Scope->addVariable(AbsDbgVariable);
1930 AbstractVariables[Var.getNode()] = AbsDbgVariable;
1931 return AbsDbgVariable;
1934 /// collectVariableInfo - Populate DbgScope entries with variables' info.
1935 void DwarfDebug::collectVariableInfo() {
1938 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1939 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1940 VE = VMap.end(); VI != VE; ++VI) {
1941 MDNode *Var = VI->first;
1943 DIVariable DV (Var);
1944 std::pair< unsigned, MDNode *> VP = VI->second;
1945 DILocation ScopeLoc(VP.second);
1948 ConcreteScopes.lookup(ScopeLoc.getOrigLocation().getNode());
1950 Scope = DbgScopeMap.lookup(ScopeLoc.getScope().getNode());
1951 // If variable scope is not found then skip this variable.
1955 DbgVariable *RegVar = new DbgVariable(DV, VP.first);
1956 Scope->addVariable(RegVar);
1957 if (DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first,
1959 RegVar->setAbstractVariable(AbsDbgVariable);
1963 /// beginScope - Process beginning of a scope starting at Label.
1964 void DwarfDebug::beginScope(const MachineInstr *MI, unsigned Label) {
1965 InsnToDbgScopeMapTy::iterator I = DbgScopeBeginMap.find(MI);
1966 if (I == DbgScopeBeginMap.end())
1968 ScopeVector &SD = I->second;
1969 for (ScopeVector::iterator SDI = SD.begin(), SDE = SD.end();
1971 (*SDI)->setStartLabelID(Label);
1974 /// endScope - Process end of a scope.
1975 void DwarfDebug::endScope(const MachineInstr *MI) {
1976 InsnToDbgScopeMapTy::iterator I = DbgScopeEndMap.find(MI);
1977 if (I == DbgScopeEndMap.end())
1980 unsigned Label = MMI->NextLabelID();
1981 Asm->printLabel(Label);
1983 SmallVector<DbgScope *, 2> &SD = I->second;
1984 for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
1986 (*SDI)->setEndLabelID(Label);
1990 /// createDbgScope - Create DbgScope for the scope.
1991 void DwarfDebug::createDbgScope(MDNode *Scope, MDNode *InlinedAt) {
1994 DbgScope *WScope = DbgScopeMap.lookup(Scope);
1997 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
1998 DbgScopeMap.insert(std::make_pair(Scope, WScope));
1999 if (DIDescriptor(Scope).isLexicalBlock())
2000 createDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
2004 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2008 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2009 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2010 DILocation DL(InlinedAt);
2011 createDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
2014 /// extractScopeInformation - Scan machine instructions in this function
2015 /// and collect DbgScopes. Return true, if atleast one scope was found.
2016 bool DwarfDebug::extractScopeInformation() {
2017 // If scope information was extracted using .dbg intrinsics then there is not
2018 // any need to extract these information by scanning each instruction.
2019 if (!DbgScopeMap.empty())
2022 DenseMap<const MachineInstr *, unsigned> MIIndexMap;
2023 unsigned MIIndex = 0;
2024 // Scan each instruction and create scopes. First build working set of scopes.
2025 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2027 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2029 const MachineInstr *MInsn = II;
2030 MIIndexMap[MInsn] = MIIndex++;
2031 DebugLoc DL = MInsn->getDebugLoc();
2032 if (DL.isUnknown()) continue;
2033 DILocation DLT = MF->getDILocation(DL);
2034 DIScope DLTScope = DLT.getScope();
2035 // There is no need to create another DIE for compile unit. For all
2036 // other scopes, create one DbgScope now. This will be translated
2037 // into a scope DIE at the end.
2038 if (DLTScope.isCompileUnit()) continue;
2039 createDbgScope(DLTScope.getNode(), DLT.getOrigLocation().getNode());
2044 // Build scope hierarchy using working set of scopes.
2045 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2047 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2049 const MachineInstr *MInsn = II;
2050 DebugLoc DL = MInsn->getDebugLoc();
2051 if (DL.isUnknown()) continue;
2052 DILocation DLT = MF->getDILocation(DL);
2053 DIScope DLTScope = DLT.getScope();
2054 // There is no need to create another DIE for compile unit. For all
2055 // other scopes, create one DbgScope now. This will be translated
2056 // into a scope DIE at the end.
2057 if (DLTScope.isCompileUnit()) continue;
2058 DbgScope *Scope = getUpdatedDbgScope(DLTScope.getNode(), MInsn,
2059 DLT.getOrigLocation().getNode());
2060 Scope->setLastInsn(MInsn);
2064 if (!CurrentFnDbgScope)
2067 CurrentFnDbgScope->fixInstructionMarkers(MIIndexMap);
2069 // Each scope has first instruction and last instruction to mark beginning
2070 // and end of a scope respectively. Create an inverse map that list scopes
2071 // starts (and ends) with an instruction. One instruction may start (or end)
2072 // multiple scopes. Ignore scopes that are not reachable.
2073 SmallVector<DbgScope *, 4> WorkList;
2074 WorkList.push_back(CurrentFnDbgScope);
2075 while (!WorkList.empty()) {
2076 DbgScope *S = WorkList.back(); WorkList.pop_back();
2078 SmallVector<DbgScope *, 4> &Children = S->getScopes();
2079 if (!Children.empty())
2080 for (SmallVector<DbgScope *, 4>::iterator SI = Children.begin(),
2081 SE = Children.end(); SI != SE; ++SI)
2082 WorkList.push_back(*SI);
2084 if (S->isAbstractScope())
2086 const MachineInstr *MI = S->getFirstInsn();
2087 assert (MI && "DbgScope does not have first instruction!");
2089 InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI);
2090 if (IDI != DbgScopeBeginMap.end())
2091 IDI->second.push_back(S);
2093 DbgScopeBeginMap[MI].push_back(S);
2095 MI = S->getLastInsn();
2096 assert (MI && "DbgScope does not have last instruction!");
2097 IDI = DbgScopeEndMap.find(MI);
2098 if (IDI != DbgScopeEndMap.end())
2099 IDI->second.push_back(S);
2101 DbgScopeEndMap[MI].push_back(S);
2104 return !DbgScopeMap.empty();
2107 /// beginFunction - Gather pre-function debug information. Assumes being
2108 /// emitted immediately after the function entry point.
2109 void DwarfDebug::beginFunction(const MachineFunction *MF) {
2112 if (!ShouldEmitDwarfDebug()) return;
2114 if (TimePassesIsEnabled)
2115 DebugTimer->startTimer();
2117 if (!extractScopeInformation())
2120 collectVariableInfo();
2122 // Assumes in correct section after the entry point.
2123 Asm->OutStreamer.EmitLabel(getDWLabel("func_begin", ++SubprogramCount));
2125 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2127 DebugLoc FDL = MF->getDefaultDebugLoc();
2128 if (!FDL.isUnknown()) {
2129 DILocation DLT = MF->getDILocation(FDL);
2130 unsigned LabelID = 0;
2131 DISubprogram SP = getDISubprogram(DLT.getScope().getNode());
2133 LabelID = recordSourceLine(SP.getLineNumber(), 0,
2134 DLT.getScope().getNode());
2136 LabelID = recordSourceLine(DLT.getLineNumber(),
2137 DLT.getColumnNumber(),
2138 DLT.getScope().getNode());
2139 Asm->printLabel(LabelID);
2141 if (TimePassesIsEnabled)
2142 DebugTimer->stopTimer();
2145 /// endFunction - Gather and emit post-function debug information.
2147 void DwarfDebug::endFunction(const MachineFunction *MF) {
2148 if (!ShouldEmitDwarfDebug()) return;
2150 if (TimePassesIsEnabled)
2151 DebugTimer->startTimer();
2153 if (DbgScopeMap.empty())
2156 if (CurrentFnDbgScope) {
2157 // Define end label for subprogram.
2158 Asm->OutStreamer.EmitLabel(getDWLabel("func_end", SubprogramCount));
2160 // Get function line info.
2161 if (!Lines.empty()) {
2162 // Get section line info.
2163 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2164 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2165 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2166 // Append the function info to section info.
2167 SectionLineInfos.insert(SectionLineInfos.end(),
2168 Lines.begin(), Lines.end());
2171 // Construct abstract scopes.
2172 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2173 AE = AbstractScopesList.end(); AI != AE; ++AI)
2174 constructScopeDIE(*AI);
2176 constructScopeDIE(CurrentFnDbgScope);
2178 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2179 MMI->getFrameMoves()));
2183 CurrentFnDbgScope = NULL;
2184 DbgScopeMap.clear();
2185 DbgScopeBeginMap.clear();
2186 DbgScopeEndMap.clear();
2187 ConcreteScopes.clear();
2188 AbstractScopesList.clear();
2191 if (TimePassesIsEnabled)
2192 DebugTimer->stopTimer();
2195 /// recordSourceLine - Records location information and associates it with a
2196 /// label. Returns a unique label ID used to generate a label and provide
2197 /// correspondence to the source line list.
2198 unsigned DwarfDebug::recordSourceLine(unsigned Line, unsigned Col,
2203 if (TimePassesIsEnabled)
2204 DebugTimer->startTimer();
2209 DIDescriptor Scope(S);
2210 if (Scope.isCompileUnit()) {
2211 DICompileUnit CU(S);
2212 Dir = CU.getDirectory();
2213 Fn = CU.getFilename();
2214 } else if (Scope.isSubprogram()) {
2216 Dir = SP.getDirectory();
2217 Fn = SP.getFilename();
2218 } else if (Scope.isLexicalBlock()) {
2219 DILexicalBlock DB(S);
2220 Dir = DB.getDirectory();
2221 Fn = DB.getFilename();
2223 assert (0 && "Unexpected scope info");
2225 unsigned Src = GetOrCreateSourceID(Dir, Fn);
2226 unsigned ID = MMI->NextLabelID();
2227 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2229 if (TimePassesIsEnabled)
2230 DebugTimer->stopTimer();
2235 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2236 /// timed. Look up the source id with the given directory and source file
2237 /// names. If none currently exists, create a new id and insert it in the
2238 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2240 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2241 const std::string &FileName) {
2242 if (TimePassesIsEnabled)
2243 DebugTimer->startTimer();
2245 unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str());
2247 if (TimePassesIsEnabled)
2248 DebugTimer->stopTimer();
2253 //===----------------------------------------------------------------------===//
2255 //===----------------------------------------------------------------------===//
2257 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2260 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2261 // Get the children.
2262 const std::vector<DIE *> &Children = Die->getChildren();
2264 // If not last sibling and has children then add sibling offset attribute.
2265 if (!Last && !Children.empty()) Die->addSiblingOffset();
2267 // Record the abbreviation.
2268 assignAbbrevNumber(Die->getAbbrev());
2270 // Get the abbreviation for this DIE.
2271 unsigned AbbrevNumber = Die->getAbbrevNumber();
2272 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2275 Die->setOffset(Offset);
2277 // Start the size with the size of abbreviation code.
2278 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2280 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2281 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2283 // Size the DIE attribute values.
2284 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2285 // Size attribute value.
2286 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
2288 // Size the DIE children if any.
2289 if (!Children.empty()) {
2290 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2291 "Children flag not set");
2293 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2294 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2296 // End of children marker.
2297 Offset += sizeof(int8_t);
2300 Die->setSize(Offset - Die->getOffset());
2304 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2306 void DwarfDebug::computeSizeAndOffsets() {
2307 // Compute size of compile unit header.
2308 static unsigned Offset =
2309 sizeof(int32_t) + // Length of Compilation Unit Info
2310 sizeof(int16_t) + // DWARF version number
2311 sizeof(int32_t) + // Offset Into Abbrev. Section
2312 sizeof(int8_t); // Pointer Size (in bytes)
2314 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2315 CompileUnitOffsets[ModuleCU] = 0;
2318 /// emitInitial - Emit initial Dwarf declarations. This is necessary for cc
2319 /// tools to recognize the object file contains Dwarf information.
2320 void DwarfDebug::emitInitial() {
2321 // Check to see if we already emitted intial headers.
2322 if (didInitial) return;
2325 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2327 // Dwarf sections base addresses.
2328 if (MAI->doesDwarfRequireFrameSection()) {
2329 Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
2330 Asm->OutStreamer.EmitLabel(getTempLabel("section_debug_frame"));
2333 Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
2334 Asm->OutStreamer.EmitLabel(getTempLabel("section_info"));
2335 Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
2336 Asm->OutStreamer.EmitLabel(getTempLabel("section_abbrev"));
2337 Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
2338 Asm->OutStreamer.EmitLabel(getTempLabel("section_aranges"));
2340 if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
2341 Asm->OutStreamer.SwitchSection(LineInfoDirective);
2342 Asm->OutStreamer.EmitLabel(getTempLabel("section_macinfo"));
2345 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
2346 Asm->OutStreamer.EmitLabel(getTempLabel("section_line"));
2347 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
2348 Asm->OutStreamer.EmitLabel(getTempLabel("section_loc"));
2349 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
2350 Asm->OutStreamer.EmitLabel(getTempLabel("section_pubnames"));
2351 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubTypesSection());
2352 Asm->OutStreamer.EmitLabel(getTempLabel("section_pubtypes"));
2353 Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
2354 Asm->OutStreamer.EmitLabel(getTempLabel("section_str"));
2355 Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
2356 Asm->OutStreamer.EmitLabel(getTempLabel("section_ranges"));
2358 Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
2359 Asm->OutStreamer.EmitLabel(getTempLabel("text_begin"));
2360 Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
2361 Asm->OutStreamer.EmitLabel(getTempLabel("data_begin"));
2364 /// emitDIE - Recusively Emits a debug information entry.
2366 void DwarfDebug::emitDIE(DIE *Die) {
2367 // Get the abbreviation for this DIE.
2368 unsigned AbbrevNumber = Die->getAbbrevNumber();
2369 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2373 // Emit the code (index) for the abbreviation.
2374 if (Asm->VerboseAsm)
2375 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2376 Twine::utohexstr(Die->getOffset()) + ":0x" +
2377 Twine::utohexstr(Die->getSize()) + " " +
2378 dwarf::TagString(Abbrev->getTag()));
2379 EmitULEB128(AbbrevNumber);
2381 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2382 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2384 // Emit the DIE attribute values.
2385 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2386 unsigned Attr = AbbrevData[i].getAttribute();
2387 unsigned Form = AbbrevData[i].getForm();
2388 assert(Form && "Too many attributes for DIE (check abbreviation)");
2390 if (Asm->VerboseAsm)
2391 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2394 case dwarf::DW_AT_sibling:
2395 Asm->EmitInt32(Die->getSiblingOffset());
2397 case dwarf::DW_AT_abstract_origin: {
2398 DIEEntry *E = cast<DIEEntry>(Values[i]);
2399 DIE *Origin = E->getEntry();
2400 unsigned Addr = Origin->getOffset();
2401 Asm->EmitInt32(Addr);
2405 // Emit an attribute using the defined form.
2406 Values[i]->EmitValue(this, Form);
2407 O << "\n"; // REMOVE This once all EmitValue impls emit their own newline.
2412 // Emit the DIE children if any.
2413 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2414 const std::vector<DIE *> &Children = Die->getChildren();
2416 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2417 emitDIE(Children[j]);
2419 Asm->EmitInt8(0); EOL("End Of Children Mark");
2423 /// emitDebugInfo - Emit the debug info section.
2425 void DwarfDebug::emitDebugInfo() {
2426 // Start debug info section.
2427 Asm->OutStreamer.SwitchSection(
2428 Asm->getObjFileLowering().getDwarfInfoSection());
2429 DIE *Die = ModuleCU->getCUDie();
2431 // Emit the compile units header.
2432 Asm->OutStreamer.EmitLabel(getDWLabel("info_begin", ModuleCU->getID()));
2434 // Emit size of content not including length itself
2435 unsigned ContentSize = Die->getSize() +
2436 sizeof(int16_t) + // DWARF version number
2437 sizeof(int32_t) + // Offset Into Abbrev. Section
2438 sizeof(int8_t) + // Pointer Size (in bytes)
2439 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2441 Asm->EmitInt32(ContentSize); EOL("Length of Compilation Unit Info");
2442 Asm->EmitInt16(dwarf::DWARF_VERSION); EOL("DWARF version number");
2443 EmitSectionOffset(getTempLabel("abbrev_begin"),getTempLabel("section_abbrev"),
2445 EOL("Offset Into Abbrev. Section");
2446 Asm->EmitInt8(TD->getPointerSize()); EOL("Address Size (in bytes)");
2449 // FIXME - extra padding for gdb bug.
2450 Asm->EmitInt8(0); EOL("Extra Pad For GDB");
2451 Asm->EmitInt8(0); EOL("Extra Pad For GDB");
2452 Asm->EmitInt8(0); EOL("Extra Pad For GDB");
2453 Asm->EmitInt8(0); EOL("Extra Pad For GDB");
2454 Asm->OutStreamer.EmitLabel(getDWLabel("info_end", ModuleCU->getID()));
2458 /// emitAbbreviations - Emit the abbreviation section.
2460 void DwarfDebug::emitAbbreviations() const {
2461 // Check to see if it is worth the effort.
2462 if (!Abbreviations.empty()) {
2463 // Start the debug abbrev section.
2464 Asm->OutStreamer.SwitchSection(
2465 Asm->getObjFileLowering().getDwarfAbbrevSection());
2467 Asm->OutStreamer.EmitLabel(getTempLabel("abbrev_begin"));
2469 // For each abbrevation.
2470 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2471 // Get abbreviation data
2472 const DIEAbbrev *Abbrev = Abbreviations[i];
2474 // Emit the abbrevations code (base 1 index.)
2475 EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2477 // Emit the abbreviations data.
2482 // Mark end of abbreviations.
2483 EmitULEB128(0, "EOM(3)");
2485 Asm->OutStreamer.EmitLabel(getTempLabel("abbrev_end"));
2489 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2490 /// the line matrix.
2492 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2493 // Define last address of section.
2494 Asm->EmitInt8(0); EOL("Extended Op");
2495 Asm->EmitInt8(TD->getPointerSize() + 1); EOL("Op size");
2496 Asm->EmitInt8(dwarf::DW_LNE_set_address); EOL("DW_LNE_set_address");
2497 EmitReference(getDWLabel("section_end", SectionEnd));
2498 EOL("Section end label");
2500 // Mark end of matrix.
2501 Asm->EmitInt8(0); EOL("DW_LNE_end_sequence");
2506 /// emitDebugLines - Emit source line information.
2508 void DwarfDebug::emitDebugLines() {
2509 // If the target is using .loc/.file, the assembler will be emitting the
2510 // .debug_line table automatically.
2511 if (MAI->hasDotLocAndDotFile())
2514 // Minimum line delta, thus ranging from -10..(255-10).
2515 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2516 // Maximum line delta, thus ranging from -10..(255-10).
2517 const int MaxLineDelta = 255 + MinLineDelta;
2519 // Start the dwarf line section.
2520 Asm->OutStreamer.SwitchSection(
2521 Asm->getObjFileLowering().getDwarfLineSection());
2523 // Construct the section header.
2524 EmitDifference(getTempLabel("line_end"), getTempLabel("line_begin"), true);
2525 EOL("Length of Source Line Info");
2526 Asm->OutStreamer.EmitLabel(getTempLabel("line_begin"));
2528 Asm->EmitInt16(dwarf::DWARF_VERSION); EOL("DWARF version number");
2530 EmitDifference(getTempLabel("line_prolog_end"),
2531 getTempLabel("line_prolog_begin"), true);
2532 EOL("Prolog Length");
2533 Asm->OutStreamer.EmitLabel(getTempLabel("line_prolog_begin"));
2535 Asm->EmitInt8(1); EOL("Minimum Instruction Length");
2536 Asm->EmitInt8(1); EOL("Default is_stmt_start flag");
2537 Asm->EmitInt8(MinLineDelta); EOL("Line Base Value (Special Opcodes)");
2538 Asm->EmitInt8(MaxLineDelta); EOL("Line Range Value (Special Opcodes)");
2539 Asm->EmitInt8(-MinLineDelta); EOL("Special Opcode Base");
2541 // Line number standard opcode encodings argument count
2542 Asm->EmitInt8(0); EOL("DW_LNS_copy arg count");
2543 Asm->EmitInt8(1); EOL("DW_LNS_advance_pc arg count");
2544 Asm->EmitInt8(1); EOL("DW_LNS_advance_line arg count");
2545 Asm->EmitInt8(1); EOL("DW_LNS_set_file arg count");
2546 Asm->EmitInt8(1); EOL("DW_LNS_set_column arg count");
2547 Asm->EmitInt8(0); EOL("DW_LNS_negate_stmt arg count");
2548 Asm->EmitInt8(0); EOL("DW_LNS_set_basic_block arg count");
2549 Asm->EmitInt8(0); EOL("DW_LNS_const_add_pc arg count");
2550 Asm->EmitInt8(1); EOL("DW_LNS_fixed_advance_pc arg count");
2552 // Emit directories.
2553 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2554 const std::string &Dir = getSourceDirectoryName(DI);
2555 if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("Directory");
2556 Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
2559 Asm->EmitInt8(0); EOL("End of directories");
2562 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2563 // Remember source id starts at 1.
2564 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2565 const std::string &FN = getSourceFileName(Id.second);
2566 if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("Source");
2567 Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
2569 EmitULEB128(Id.first, "Directory #");
2570 EmitULEB128(0, "Mod date");
2571 EmitULEB128(0, "File size");
2574 Asm->EmitInt8(0); EOL("End of files");
2576 Asm->OutStreamer.EmitLabel(getTempLabel("line_prolog_end"));
2578 // A sequence for each text section.
2579 unsigned SecSrcLinesSize = SectionSourceLines.size();
2581 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2582 // Isolate current sections line info.
2583 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2585 /*if (Asm->isVerbose()) {
2586 const MCSection *S = SectionMap[j + 1];
2587 O << '\t' << MAI->getCommentString() << " Section"
2588 << S->getName() << '\n';
2592 // Dwarf assumes we start with first line of first source file.
2593 unsigned Source = 1;
2596 // Construct rows of the address, source, line, column matrix.
2597 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2598 const SrcLineInfo &LineInfo = LineInfos[i];
2599 unsigned LabelID = LineInfo.getLabelID();
2600 if (MMI->isLabelDeleted(LabelID)) continue;
2602 if (LineInfo.getLine() == 0) continue;
2604 if (!Asm->isVerbose())
2607 std::pair<unsigned, unsigned> SourceID =
2608 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2609 O << '\t' << MAI->getCommentString() << ' '
2610 << getSourceDirectoryName(SourceID.first) << '/'
2611 << getSourceFileName(SourceID.second)
2612 << ':' << utostr_32(LineInfo.getLine()) << '\n';
2615 // Define the line address.
2616 Asm->EmitInt8(0); EOL("Extended Op");
2617 Asm->EmitInt8(TD->getPointerSize() + 1); EOL("Op size");
2618 Asm->EmitInt8(dwarf::DW_LNE_set_address); EOL("DW_LNE_set_address");
2619 EmitReference(getDWLabel("label", LabelID)); EOL("Location label");
2621 // If change of source, then switch to the new source.
2622 if (Source != LineInfo.getSourceID()) {
2623 Source = LineInfo.getSourceID();
2624 Asm->EmitInt8(dwarf::DW_LNS_set_file); EOL("DW_LNS_set_file");
2625 EmitULEB128(Source, "New Source");
2628 // If change of line.
2629 if (Line != LineInfo.getLine()) {
2630 // Determine offset.
2631 int Offset = LineInfo.getLine() - Line;
2632 int Delta = Offset - MinLineDelta;
2635 Line = LineInfo.getLine();
2637 // If delta is small enough and in range...
2638 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2639 // ... then use fast opcode.
2640 Asm->EmitInt8(Delta - MinLineDelta); EOL("Line Delta");
2642 // ... otherwise use long hand.
2643 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2644 EOL("DW_LNS_advance_line");
2645 EmitSLEB128(Offset, "Line Offset");
2646 Asm->EmitInt8(dwarf::DW_LNS_copy); EOL("DW_LNS_copy");
2649 // Copy the previous row (different address or source)
2650 Asm->EmitInt8(dwarf::DW_LNS_copy); EOL("DW_LNS_copy");
2654 emitEndOfLineMatrix(j + 1);
2657 if (SecSrcLinesSize == 0)
2658 // Because we're emitting a debug_line section, we still need a line
2659 // table. The linker and friends expect it to exist. If there's nothing to
2660 // put into it, emit an empty table.
2661 emitEndOfLineMatrix(1);
2663 Asm->OutStreamer.EmitLabel(getTempLabel("line_end"));
2666 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
2668 void DwarfDebug::emitCommonDebugFrame() {
2669 if (!MAI->doesDwarfRequireFrameSection())
2673 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2674 TargetFrameInfo::StackGrowsUp ?
2675 TD->getPointerSize() : -TD->getPointerSize();
2677 // Start the dwarf frame section.
2678 Asm->OutStreamer.SwitchSection(
2679 Asm->getObjFileLowering().getDwarfFrameSection());
2681 Asm->OutStreamer.EmitLabel(getTempLabel("debug_frame_common"));
2682 EmitDifference(getTempLabel("debug_frame_common_end"),
2683 getTempLabel("debug_frame_common_begin"), true);
2684 EOL("Length of Common Information Entry");
2686 Asm->OutStreamer.EmitLabel(getTempLabel("debug_frame_common_begin"));
2687 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2688 EOL("CIE Identifier Tag");
2689 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2691 Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
2692 EOL("CIE Augmentation");
2693 EmitULEB128(1, "CIE Code Alignment Factor");
2694 EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
2695 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2696 EOL("CIE RA Column");
2698 std::vector<MachineMove> Moves;
2699 RI->getInitialFrameState(Moves);
2701 EmitFrameMoves(NULL, 0, Moves, false);
2703 Asm->EmitAlignment(2, 0, 0, false);
2704 Asm->OutStreamer.EmitLabel(getTempLabel("debug_frame_common_end"));
2707 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
2710 DwarfDebug::emitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2711 if (!MAI->doesDwarfRequireFrameSection())
2714 // Start the dwarf frame section.
2715 Asm->OutStreamer.SwitchSection(
2716 Asm->getObjFileLowering().getDwarfFrameSection());
2718 EmitDifference(getDWLabel("debug_frame_end", DebugFrameInfo.Number),
2719 getDWLabel("debug_frame_begin", DebugFrameInfo.Number), true);
2720 EOL("Length of Frame Information Entry");
2722 Asm->OutStreamer.EmitLabel(getDWLabel("debug_frame_begin",
2723 DebugFrameInfo.Number));
2725 EmitSectionOffset(getTempLabel("debug_frame_common"),
2726 getTempLabel("section_debug_frame"), true, false);
2727 EOL("FDE CIE offset");
2729 EmitReference(getDWLabel("func_begin", DebugFrameInfo.Number));
2730 EOL("FDE initial location");
2731 EmitDifference(getDWLabel("func_end", DebugFrameInfo.Number),
2732 getDWLabel("func_begin", DebugFrameInfo.Number));
2733 EOL("FDE address range");
2735 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2738 Asm->EmitAlignment(2, 0, 0, false);
2739 Asm->OutStreamer.EmitLabel(getDWLabel("debug_frame_end",
2740 DebugFrameInfo.Number));
2743 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2745 void DwarfDebug::emitDebugPubNames() {
2746 // Start the dwarf pubnames section.
2747 Asm->OutStreamer.SwitchSection(
2748 Asm->getObjFileLowering().getDwarfPubNamesSection());
2750 EmitDifference(getDWLabel("pubnames_end", ModuleCU->getID()),
2751 getDWLabel("pubnames_begin", ModuleCU->getID()), true);
2752 EOL("Length of Public Names Info");
2754 Asm->OutStreamer.EmitLabel(getDWLabel("pubnames_begin", ModuleCU->getID()));
2756 Asm->EmitInt16(dwarf::DWARF_VERSION); EOL("DWARF Version");
2758 EmitSectionOffset(getDWLabel("info_begin", ModuleCU->getID()),
2759 getTempLabel("section_info"),
2761 EOL("Offset of Compilation Unit Info");
2763 EmitDifference(getDWLabel("info_end", ModuleCU->getID()),
2764 getDWLabel("info_begin", ModuleCU->getID()),
2766 EOL("Compilation Unit Length");
2768 const StringMap<DIE*> &Globals = ModuleCU->getGlobals();
2769 for (StringMap<DIE*>::const_iterator
2770 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2771 const char *Name = GI->getKeyData();
2772 DIE * Entity = GI->second;
2774 Asm->EmitInt32(Entity->getOffset()); EOL("DIE offset");
2776 if (Asm->VerboseAsm)
2777 Asm->OutStreamer.AddComment("External Name");
2778 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
2781 Asm->EmitInt32(0); EOL("End Mark");
2782 Asm->OutStreamer.EmitLabel(getDWLabel("pubnames_end", ModuleCU->getID()));
2785 void DwarfDebug::emitDebugPubTypes() {
2786 // Start the dwarf pubnames section.
2787 Asm->OutStreamer.SwitchSection(
2788 Asm->getObjFileLowering().getDwarfPubTypesSection());
2789 EmitDifference(getDWLabel("pubtypes_end", ModuleCU->getID()),
2790 getDWLabel("pubtypes_begin", ModuleCU->getID()), true);
2791 EOL("Length of Public Types Info");
2793 Asm->OutStreamer.EmitLabel(getDWLabel("pubtypes_begin", ModuleCU->getID()));
2795 if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("DWARF Version");
2796 Asm->EmitInt16(dwarf::DWARF_VERSION);
2798 EmitSectionOffset(getDWLabel("info_begin", ModuleCU->getID()),
2799 getTempLabel("section_info"), true, false);
2800 EOL("Offset of Compilation ModuleCU Info");
2802 EmitDifference(getDWLabel("info_end", ModuleCU->getID()),
2803 getDWLabel("info_begin", ModuleCU->getID()),
2805 EOL("Compilation ModuleCU Length");
2807 const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
2808 for (StringMap<DIE*>::const_iterator
2809 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2810 const char *Name = GI->getKeyData();
2811 DIE * Entity = GI->second;
2813 if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("DIE offset");
2814 Asm->EmitInt32(Entity->getOffset());
2816 if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("External Name");
2817 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
2820 Asm->EmitInt32(0); EOL("End Mark");
2821 Asm->OutStreamer.EmitLabel(getDWLabel("pubtypes_end", ModuleCU->getID()));
2824 /// emitDebugStr - Emit visible names into a debug str section.
2826 void DwarfDebug::emitDebugStr() {
2827 // Check to see if it is worth the effort.
2828 if (!StringPool.empty()) {
2829 // Start the dwarf str section.
2830 Asm->OutStreamer.SwitchSection(
2831 Asm->getObjFileLowering().getDwarfStrSection());
2833 // For each of strings in the string pool.
2834 for (unsigned StringID = 1, N = StringPool.size();
2835 StringID <= N; ++StringID) {
2836 // Emit a label for reference from debug information entries.
2837 Asm->OutStreamer.EmitLabel(getDWLabel("string", StringID));
2839 // Emit the string itself.
2840 const std::string &String = StringPool[StringID];
2841 Asm->OutStreamer.EmitBytes(StringRef(String.c_str(), String.size()+1), 0);
2848 /// emitDebugLoc - Emit visible names into a debug loc section.
2850 void DwarfDebug::emitDebugLoc() {
2851 // Start the dwarf loc section.
2852 Asm->OutStreamer.SwitchSection(
2853 Asm->getObjFileLowering().getDwarfLocSection());
2856 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2858 void DwarfDebug::EmitDebugARanges() {
2859 // Start the dwarf aranges section.
2860 Asm->OutStreamer.SwitchSection(
2861 Asm->getObjFileLowering().getDwarfARangesSection());
2865 CompileUnit *Unit = GetBaseCompileUnit();
2867 // Don't include size of length
2868 Asm->EmitInt32(0x1c); EOL("Length of Address Ranges Info");
2870 Asm->EmitInt16(dwarf::DWARF_VERSION); EOL("Dwarf Version");
2872 EmitReference("info_begin", Unit->getID());
2873 EOL("Offset of Compilation Unit Info");
2875 Asm->EmitInt8(TD->getPointerSize()); EOL("Size of Address");
2877 Asm->EmitInt8(0); EOL("Size of Segment Descriptor");
2879 Asm->EmitInt16(0); EOL("Pad (1)");
2880 Asm->EmitInt16(0); EOL("Pad (2)");
2883 EmitReference("text_begin", 0); EOL("Address");
2884 EmitDifference(getTempLabel("text_end"), getTempLabel("text_begin"),
2885 true); EOL("Length");
2887 Asm->EmitInt32(0); EOL("EOM (1)");
2888 Asm->EmitInt32(0); EOL("EOM (2)");
2892 /// emitDebugRanges - Emit visible names into a debug ranges section.
2894 void DwarfDebug::emitDebugRanges() {
2895 // Start the dwarf ranges section.
2896 Asm->OutStreamer.SwitchSection(
2897 Asm->getObjFileLowering().getDwarfRangesSection());
2900 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2902 void DwarfDebug::emitDebugMacInfo() {
2903 if (const MCSection *LineInfo =
2904 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2905 // Start the dwarf macinfo section.
2906 Asm->OutStreamer.SwitchSection(LineInfo);
2910 /// emitDebugInlineInfo - Emit inline info using following format.
2912 /// 1. length of section
2913 /// 2. Dwarf version number
2914 /// 3. address size.
2916 /// Entries (one "entry" for each function that was inlined):
2918 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2919 /// otherwise offset into __debug_str for regular function name.
2920 /// 2. offset into __debug_str section for regular function name.
2921 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2922 /// instances for the function.
2924 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2925 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2926 /// __debug_info section, and the low_pc is the starting address for the
2927 /// inlining instance.
2928 void DwarfDebug::emitDebugInlineInfo() {
2929 if (!MAI->doesDwarfUsesInlineInfoSection())
2935 Asm->OutStreamer.SwitchSection(
2936 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2938 EmitDifference(getDWLabel("debug_inlined_end", 1),
2939 getDWLabel("debug_inlined_begin", 1), true);
2940 EOL("Length of Debug Inlined Information Entry");
2942 Asm->OutStreamer.EmitLabel(getDWLabel("debug_inlined_begin", 1));
2944 Asm->EmitInt16(dwarf::DWARF_VERSION); EOL("Dwarf Version");
2945 Asm->EmitInt8(TD->getPointerSize()); EOL("Address Size (in bytes)");
2947 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2948 E = InlinedSPNodes.end(); I != E; ++I) {
2951 DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2952 = InlineInfo.find(Node);
2953 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2954 DISubprogram SP(Node);
2955 StringRef LName = SP.getLinkageName();
2956 StringRef Name = SP.getName();
2958 if (LName.empty()) {
2959 Asm->OutStreamer.EmitBytes(Name, 0);
2960 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2962 EmitSectionOffset(getDWLabel("string",
2963 StringPool.idFor(getRealLinkageName(LName))),
2964 getTempLabel("section_str"), true);
2966 EOL("MIPS linkage name");
2967 EmitSectionOffset(getDWLabel("string", StringPool.idFor(Name)),
2968 getTempLabel("section_str"), false, true);
2969 EOL("Function name");
2970 EmitULEB128(Labels.size(), "Inline count");
2972 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2973 LE = Labels.end(); LI != LE; ++LI) {
2974 if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("DIE offset");
2975 Asm->EmitInt32(LI->second->getOffset());
2977 if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("low_pc");
2978 Asm->OutStreamer.EmitSymbolValue(LI->first, TD->getPointerSize(), 0);
2982 Asm->OutStreamer.EmitLabel(getDWLabel("debug_inlined_end", 1));