DwarfDebug.cpp revision 4063f6bcc775bb0429dea2276694c4cdc2d4dca1
1//===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file contains support for writing dwarf debug info into asm files. 11// 12//===----------------------------------------------------------------------===// 13#define DEBUG_TYPE "dwarfdebug" 14#include "DwarfDebug.h" 15#include "llvm/Module.h" 16#include "llvm/CodeGen/MachineFunction.h" 17#include "llvm/CodeGen/MachineModuleInfo.h" 18#include "llvm/MC/MCSection.h" 19#include "llvm/MC/MCStreamer.h" 20#include "llvm/MC/MCAsmInfo.h" 21#include "llvm/Target/TargetData.h" 22#include "llvm/Target/TargetFrameInfo.h" 23#include "llvm/Target/TargetLoweringObjectFile.h" 24#include "llvm/Target/TargetRegisterInfo.h" 25#include "llvm/ADT/StringExtras.h" 26#include "llvm/Support/Debug.h" 27#include "llvm/Support/ErrorHandling.h" 28#include "llvm/Support/Mangler.h" 29#include "llvm/Support/Timer.h" 30#include "llvm/System/Path.h" 31using namespace llvm; 32 33static TimerGroup &getDwarfTimerGroup() { 34 static TimerGroup DwarfTimerGroup("Dwarf Debugging"); 35 return DwarfTimerGroup; 36} 37 38//===----------------------------------------------------------------------===// 39 40/// Configuration values for initial hash set sizes (log2). 41/// 42static const unsigned InitAbbreviationsSetSize = 9; // log2(512) 43 44namespace llvm { 45 46//===----------------------------------------------------------------------===// 47/// CompileUnit - This dwarf writer support class manages information associate 48/// with a source file. 49class CompileUnit { 50 /// ID - File identifier for source. 51 /// 52 unsigned ID; 53 54 /// Die - Compile unit debug information entry. 55 /// 56 DIE *CUDie; 57 58 /// IndexTyDie - An anonymous type for index type. 59 DIE *IndexTyDie; 60 61 /// GVToDieMap - Tracks the mapping of unit level debug informaton 62 /// variables to debug information entries. 63 /// FIXME : Rename GVToDieMap -> NodeToDieMap 64 ValueMap<MDNode *, DIE *> GVToDieMap; 65 66 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton 67 /// descriptors to debug information entries using a DIEEntry proxy. 68 /// FIXME : Rename 69 ValueMap<MDNode *, DIEEntry *> GVToDIEEntryMap; 70 71 /// Globals - A map of globally visible named entities for this unit. 72 /// 73 StringMap<DIE*> Globals; 74 75 /// GlobalTypes - A map of globally visible types for this unit. 76 /// 77 StringMap<DIE*> GlobalTypes; 78 79public: 80 CompileUnit(unsigned I, DIE *D) 81 : ID(I), CUDie(D), IndexTyDie(0) {} 82 ~CompileUnit() { delete CUDie; delete IndexTyDie; } 83 84 // Accessors. 85 unsigned getID() const { return ID; } 86 DIE* getCUDie() const { return CUDie; } 87 const StringMap<DIE*> &getGlobals() const { return Globals; } 88 const StringMap<DIE*> &getGlobalTypes() const { return GlobalTypes; } 89 90 /// hasContent - Return true if this compile unit has something to write out. 91 /// 92 bool hasContent() const { return !CUDie->getChildren().empty(); } 93 94 /// addGlobal - Add a new global entity to the compile unit. 95 /// 96 void addGlobal(const std::string &Name, DIE *Die) { Globals[Name] = Die; } 97 98 /// addGlobalType - Add a new global type to the compile unit. 99 /// 100 void addGlobalType(const std::string &Name, DIE *Die) { 101 GlobalTypes[Name] = Die; 102 } 103 104 /// getDIE - Returns the debug information entry map slot for the 105 /// specified debug variable. 106 DIE *getDIE(MDNode *N) { return GVToDieMap.lookup(N); } 107 108 /// insertDIE - Insert DIE into the map. 109 void insertDIE(MDNode *N, DIE *D) { 110 GVToDieMap.insert(std::make_pair(N, D)); 111 } 112 113 /// getDIEEntry - Returns the debug information entry for the speciefied 114 /// debug variable. 115 DIEEntry *getDIEEntry(MDNode *N) { return GVToDIEEntryMap.lookup(N); } 116 117 /// insertDIEEntry - Insert debug information entry into the map. 118 void insertDIEEntry(MDNode *N, DIEEntry *E) { 119 GVToDIEEntryMap.insert(std::make_pair(N, E)); 120 } 121 122 /// addDie - Adds or interns the DIE to the compile unit. 123 /// 124 void addDie(DIE *Buffer) { 125 this->CUDie->addChild(Buffer); 126 } 127 128 // getIndexTyDie - Get an anonymous type for index type. 129 DIE *getIndexTyDie() { 130 return IndexTyDie; 131 } 132 133 // setIndexTyDie - Set D as anonymous type for index which can be reused 134 // later. 135 void setIndexTyDie(DIE *D) { 136 IndexTyDie = D; 137 } 138 139}; 140 141//===----------------------------------------------------------------------===// 142/// DbgVariable - This class is used to track local variable information. 143/// 144class DbgVariable { 145 DIVariable Var; // Variable Descriptor. 146 unsigned FrameIndex; // Variable frame index. 147 DbgVariable *AbstractVar; // Abstract variable for this variable. 148 DIE *TheDIE; 149public: 150 DbgVariable(DIVariable V, unsigned I) 151 : Var(V), FrameIndex(I), AbstractVar(0), TheDIE(0) {} 152 153 // Accessors. 154 DIVariable getVariable() const { return Var; } 155 unsigned getFrameIndex() const { return FrameIndex; } 156 void setAbstractVariable(DbgVariable *V) { AbstractVar = V; } 157 DbgVariable *getAbstractVariable() const { return AbstractVar; } 158 void setDIE(DIE *D) { TheDIE = D; } 159 DIE *getDIE() const { return TheDIE; } 160}; 161 162//===----------------------------------------------------------------------===// 163/// DbgScope - This class is used to track scope information. 164/// 165class DbgScope { 166 DbgScope *Parent; // Parent to this scope. 167 DIDescriptor Desc; // Debug info descriptor for scope. 168 WeakVH InlinedAtLocation; // Location at which scope is inlined. 169 bool AbstractScope; // Abstract Scope 170 unsigned StartLabelID; // Label ID of the beginning of scope. 171 unsigned EndLabelID; // Label ID of the end of scope. 172 const MachineInstr *LastInsn; // Last instruction of this scope. 173 const MachineInstr *FirstInsn; // First instruction of this scope. 174 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope. 175 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope. 176 177 // Private state for dump() 178 mutable unsigned IndentLevel; 179public: 180 DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0) 181 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false), 182 StartLabelID(0), EndLabelID(0), 183 LastInsn(0), FirstInsn(0), IndentLevel(0) {} 184 virtual ~DbgScope(); 185 186 // Accessors. 187 DbgScope *getParent() const { return Parent; } 188 void setParent(DbgScope *P) { Parent = P; } 189 DIDescriptor getDesc() const { return Desc; } 190 MDNode *getInlinedAt() const { 191 return dyn_cast_or_null<MDNode>(InlinedAtLocation); 192 } 193 MDNode *getScopeNode() const { return Desc.getNode(); } 194 unsigned getStartLabelID() const { return StartLabelID; } 195 unsigned getEndLabelID() const { return EndLabelID; } 196 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; } 197 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; } 198 void setStartLabelID(unsigned S) { StartLabelID = S; } 199 void setEndLabelID(unsigned E) { EndLabelID = E; } 200 void setLastInsn(const MachineInstr *MI) { LastInsn = MI; } 201 const MachineInstr *getLastInsn() { return LastInsn; } 202 void setFirstInsn(const MachineInstr *MI) { FirstInsn = MI; } 203 void setAbstractScope() { AbstractScope = true; } 204 bool isAbstractScope() const { return AbstractScope; } 205 const MachineInstr *getFirstInsn() { return FirstInsn; } 206 207 /// addScope - Add a scope to the scope. 208 /// 209 void addScope(DbgScope *S) { Scopes.push_back(S); } 210 211 /// addVariable - Add a variable to the scope. 212 /// 213 void addVariable(DbgVariable *V) { Variables.push_back(V); } 214 215 void fixInstructionMarkers() { 216 assert (getFirstInsn() && "First instruction is missing!"); 217 if (getLastInsn()) 218 return; 219 220 // If a scope does not have an instruction to mark an end then use 221 // the end of last child scope. 222 SmallVector<DbgScope *, 4> &Scopes = getScopes(); 223 assert (!Scopes.empty() && "Inner most scope does not have last insn!"); 224 DbgScope *L = Scopes.back(); 225 if (!L->getLastInsn()) 226 L->fixInstructionMarkers(); 227 setLastInsn(L->getLastInsn()); 228 } 229 230#ifndef NDEBUG 231 void dump() const; 232#endif 233}; 234 235#ifndef NDEBUG 236void DbgScope::dump() const { 237 raw_ostream &err = errs(); 238 err.indent(IndentLevel); 239 MDNode *N = Desc.getNode(); 240 N->dump(); 241 err << " [" << StartLabelID << ", " << EndLabelID << "]\n"; 242 if (AbstractScope) 243 err << "Abstract Scope\n"; 244 245 IndentLevel += 2; 246 if (!Scopes.empty()) 247 err << "Children ...\n"; 248 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) 249 if (Scopes[i] != this) 250 Scopes[i]->dump(); 251 252 IndentLevel -= 2; 253} 254#endif 255 256DbgScope::~DbgScope() { 257 for (unsigned i = 0, N = Scopes.size(); i < N; ++i) 258 delete Scopes[i]; 259 for (unsigned j = 0, M = Variables.size(); j < M; ++j) 260 delete Variables[j]; 261} 262 263} // end llvm namespace 264 265DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T) 266 : Dwarf(OS, A, T, "dbg"), ModuleCU(0), 267 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(), 268 DIEValues(), StringPool(), 269 SectionSourceLines(), didInitial(false), shouldEmit(false), 270 CurrentFnDbgScope(0), DebugTimer(0) { 271 if (TimePassesIsEnabled) 272 DebugTimer = new Timer("Dwarf Debug Writer", 273 getDwarfTimerGroup()); 274} 275DwarfDebug::~DwarfDebug() { 276 for (unsigned j = 0, M = DIEValues.size(); j < M; ++j) 277 delete DIEValues[j]; 278 279 delete DebugTimer; 280} 281 282/// assignAbbrevNumber - Define a unique number for the abbreviation. 283/// 284void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) { 285 // Profile the node so that we can make it unique. 286 FoldingSetNodeID ID; 287 Abbrev.Profile(ID); 288 289 // Check the set for priors. 290 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev); 291 292 // If it's newly added. 293 if (InSet == &Abbrev) { 294 // Add to abbreviation list. 295 Abbreviations.push_back(&Abbrev); 296 297 // Assign the vector position + 1 as its number. 298 Abbrev.setNumber(Abbreviations.size()); 299 } else { 300 // Assign existing abbreviation number. 301 Abbrev.setNumber(InSet->getNumber()); 302 } 303} 304 305/// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug 306/// information entry. 307DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) { 308 DIEEntry *Value = new DIEEntry(Entry); 309 DIEValues.push_back(Value); 310 return Value; 311} 312 313/// addUInt - Add an unsigned integer attribute data and value. 314/// 315void DwarfDebug::addUInt(DIE *Die, unsigned Attribute, 316 unsigned Form, uint64_t Integer) { 317 if (!Form) Form = DIEInteger::BestForm(false, Integer); 318 DIEValue *Value = new DIEInteger(Integer); 319 DIEValues.push_back(Value); 320 Die->addValue(Attribute, Form, Value); 321} 322 323/// addSInt - Add an signed integer attribute data and value. 324/// 325void DwarfDebug::addSInt(DIE *Die, unsigned Attribute, 326 unsigned Form, int64_t Integer) { 327 if (!Form) Form = DIEInteger::BestForm(true, Integer); 328 DIEValue *Value = new DIEInteger(Integer); 329 DIEValues.push_back(Value); 330 Die->addValue(Attribute, Form, Value); 331} 332 333/// addString - Add a string attribute data and value. DIEString only 334/// keeps string reference. 335void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form, 336 const StringRef String) { 337 DIEValue *Value = new DIEString(String); 338 DIEValues.push_back(Value); 339 Die->addValue(Attribute, Form, Value); 340} 341 342/// addLabel - Add a Dwarf label attribute data and value. 343/// 344void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form, 345 const DWLabel &Label) { 346 DIEValue *Value = new DIEDwarfLabel(Label); 347 DIEValues.push_back(Value); 348 Die->addValue(Attribute, Form, Value); 349} 350 351/// addObjectLabel - Add an non-Dwarf label attribute data and value. 352/// 353void DwarfDebug::addObjectLabel(DIE *Die, unsigned Attribute, unsigned Form, 354 const std::string &Label) { 355 DIEValue *Value = new DIEObjectLabel(Label); 356 DIEValues.push_back(Value); 357 Die->addValue(Attribute, Form, Value); 358} 359 360/// addSectionOffset - Add a section offset label attribute data and value. 361/// 362void DwarfDebug::addSectionOffset(DIE *Die, unsigned Attribute, unsigned Form, 363 const DWLabel &Label, const DWLabel &Section, 364 bool isEH, bool useSet) { 365 DIEValue *Value = new DIESectionOffset(Label, Section, isEH, useSet); 366 DIEValues.push_back(Value); 367 Die->addValue(Attribute, Form, Value); 368} 369 370/// addDelta - Add a label delta attribute data and value. 371/// 372void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form, 373 const DWLabel &Hi, const DWLabel &Lo) { 374 DIEValue *Value = new DIEDelta(Hi, Lo); 375 DIEValues.push_back(Value); 376 Die->addValue(Attribute, Form, Value); 377} 378 379/// addBlock - Add block data. 380/// 381void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form, 382 DIEBlock *Block) { 383 Block->ComputeSize(TD); 384 DIEValues.push_back(Block); 385 Die->addValue(Attribute, Block->BestForm(), Block); 386} 387 388/// addSourceLine - Add location information to specified debug information 389/// entry. 390void DwarfDebug::addSourceLine(DIE *Die, const DIVariable *V) { 391 // If there is no compile unit specified, don't add a line #. 392 if (V->getCompileUnit().isNull()) 393 return; 394 395 unsigned Line = V->getLineNumber(); 396 unsigned FileID = findCompileUnit(V->getCompileUnit()).getID(); 397 assert(FileID && "Invalid file id"); 398 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID); 399 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line); 400} 401 402/// addSourceLine - Add location information to specified debug information 403/// entry. 404void DwarfDebug::addSourceLine(DIE *Die, const DIGlobal *G) { 405 // If there is no compile unit specified, don't add a line #. 406 if (G->getCompileUnit().isNull()) 407 return; 408 409 unsigned Line = G->getLineNumber(); 410 unsigned FileID = findCompileUnit(G->getCompileUnit()).getID(); 411 assert(FileID && "Invalid file id"); 412 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID); 413 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line); 414} 415 416/// addSourceLine - Add location information to specified debug information 417/// entry. 418void DwarfDebug::addSourceLine(DIE *Die, const DISubprogram *SP) { 419 // If there is no compile unit specified, don't add a line #. 420 if (SP->getCompileUnit().isNull()) 421 return; 422 // If the line number is 0, don't add it. 423 if (SP->getLineNumber() == 0) 424 return; 425 426 427 unsigned Line = SP->getLineNumber(); 428 unsigned FileID = findCompileUnit(SP->getCompileUnit()).getID(); 429 assert(FileID && "Invalid file id"); 430 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID); 431 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line); 432} 433 434/// addSourceLine - Add location information to specified debug information 435/// entry. 436void DwarfDebug::addSourceLine(DIE *Die, const DIType *Ty) { 437 // If there is no compile unit specified, don't add a line #. 438 DICompileUnit CU = Ty->getCompileUnit(); 439 if (CU.isNull()) 440 return; 441 442 unsigned Line = Ty->getLineNumber(); 443 unsigned FileID = findCompileUnit(CU).getID(); 444 assert(FileID && "Invalid file id"); 445 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID); 446 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line); 447} 448 449/// addSourceLine - Add location information to specified debug information 450/// entry. 451void DwarfDebug::addSourceLine(DIE *Die, const DINameSpace *NS) { 452 // If there is no compile unit specified, don't add a line #. 453 if (NS->getCompileUnit().isNull()) 454 return; 455 456 unsigned Line = NS->getLineNumber(); 457 StringRef FN = NS->getFilename(); 458 StringRef Dir = NS->getDirectory(); 459 460 unsigned FileID = GetOrCreateSourceID(Dir, FN); 461 assert(FileID && "Invalid file id"); 462 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID); 463 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line); 464} 465 466/* Byref variables, in Blocks, are declared by the programmer as 467 "SomeType VarName;", but the compiler creates a 468 __Block_byref_x_VarName struct, and gives the variable VarName 469 either the struct, or a pointer to the struct, as its type. This 470 is necessary for various behind-the-scenes things the compiler 471 needs to do with by-reference variables in blocks. 472 473 However, as far as the original *programmer* is concerned, the 474 variable should still have type 'SomeType', as originally declared. 475 476 The following function dives into the __Block_byref_x_VarName 477 struct to find the original type of the variable. This will be 478 passed back to the code generating the type for the Debug 479 Information Entry for the variable 'VarName'. 'VarName' will then 480 have the original type 'SomeType' in its debug information. 481 482 The original type 'SomeType' will be the type of the field named 483 'VarName' inside the __Block_byref_x_VarName struct. 484 485 NOTE: In order for this to not completely fail on the debugger 486 side, the Debug Information Entry for the variable VarName needs to 487 have a DW_AT_location that tells the debugger how to unwind through 488 the pointers and __Block_byref_x_VarName struct to find the actual 489 value of the variable. The function addBlockByrefType does this. */ 490 491/// Find the type the programmer originally declared the variable to be 492/// and return that type. 493/// 494DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) { 495 496 DIType subType = Ty; 497 unsigned tag = Ty.getTag(); 498 499 if (tag == dwarf::DW_TAG_pointer_type) { 500 DIDerivedType DTy = DIDerivedType(Ty.getNode()); 501 subType = DTy.getTypeDerivedFrom(); 502 } 503 504 DICompositeType blockStruct = DICompositeType(subType.getNode()); 505 506 DIArray Elements = blockStruct.getTypeArray(); 507 508 if (Elements.isNull()) 509 return Ty; 510 511 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) { 512 DIDescriptor Element = Elements.getElement(i); 513 DIDerivedType DT = DIDerivedType(Element.getNode()); 514 if (Name == DT.getName()) 515 return (DT.getTypeDerivedFrom()); 516 } 517 518 return Ty; 519} 520 521/// addComplexAddress - Start with the address based on the location provided, 522/// and generate the DWARF information necessary to find the actual variable 523/// given the extra address information encoded in the DIVariable, starting from 524/// the starting location. Add the DWARF information to the die. 525/// 526void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die, 527 unsigned Attribute, 528 const MachineLocation &Location) { 529 const DIVariable &VD = DV->getVariable(); 530 DIType Ty = VD.getType(); 531 532 // Decode the original location, and use that as the start of the byref 533 // variable's location. 534 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false); 535 DIEBlock *Block = new DIEBlock(); 536 537 if (Location.isReg()) { 538 if (Reg < 32) { 539 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg); 540 } else { 541 Reg = Reg - dwarf::DW_OP_reg0; 542 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg); 543 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg); 544 } 545 } else { 546 if (Reg < 32) 547 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg); 548 else { 549 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx); 550 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg); 551 } 552 553 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset()); 554 } 555 556 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) { 557 uint64_t Element = VD.getAddrElement(i); 558 559 if (Element == DIFactory::OpPlus) { 560 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 561 addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i)); 562 } else if (Element == DIFactory::OpDeref) { 563 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 564 } else llvm_unreachable("unknown DIFactory Opcode"); 565 } 566 567 // Now attach the location information to the DIE. 568 addBlock(Die, Attribute, 0, Block); 569} 570 571/* Byref variables, in Blocks, are declared by the programmer as "SomeType 572 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and 573 gives the variable VarName either the struct, or a pointer to the struct, as 574 its type. This is necessary for various behind-the-scenes things the 575 compiler needs to do with by-reference variables in Blocks. 576 577 However, as far as the original *programmer* is concerned, the variable 578 should still have type 'SomeType', as originally declared. 579 580 The function getBlockByrefType dives into the __Block_byref_x_VarName 581 struct to find the original type of the variable, which is then assigned to 582 the variable's Debug Information Entry as its real type. So far, so good. 583 However now the debugger will expect the variable VarName to have the type 584 SomeType. So we need the location attribute for the variable to be an 585 expression that explains to the debugger how to navigate through the 586 pointers and struct to find the actual variable of type SomeType. 587 588 The following function does just that. We start by getting 589 the "normal" location for the variable. This will be the location 590 of either the struct __Block_byref_x_VarName or the pointer to the 591 struct __Block_byref_x_VarName. 592 593 The struct will look something like: 594 595 struct __Block_byref_x_VarName { 596 ... <various fields> 597 struct __Block_byref_x_VarName *forwarding; 598 ... <various other fields> 599 SomeType VarName; 600 ... <maybe more fields> 601 }; 602 603 If we are given the struct directly (as our starting point) we 604 need to tell the debugger to: 605 606 1). Add the offset of the forwarding field. 607 608 2). Follow that pointer to get the the real __Block_byref_x_VarName 609 struct to use (the real one may have been copied onto the heap). 610 611 3). Add the offset for the field VarName, to find the actual variable. 612 613 If we started with a pointer to the struct, then we need to 614 dereference that pointer first, before the other steps. 615 Translating this into DWARF ops, we will need to append the following 616 to the current location description for the variable: 617 618 DW_OP_deref -- optional, if we start with a pointer 619 DW_OP_plus_uconst <forward_fld_offset> 620 DW_OP_deref 621 DW_OP_plus_uconst <varName_fld_offset> 622 623 That is what this function does. */ 624 625/// addBlockByrefAddress - Start with the address based on the location 626/// provided, and generate the DWARF information necessary to find the 627/// actual Block variable (navigating the Block struct) based on the 628/// starting location. Add the DWARF information to the die. For 629/// more information, read large comment just above here. 630/// 631void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die, 632 unsigned Attribute, 633 const MachineLocation &Location) { 634 const DIVariable &VD = DV->getVariable(); 635 DIType Ty = VD.getType(); 636 DIType TmpTy = Ty; 637 unsigned Tag = Ty.getTag(); 638 bool isPointer = false; 639 640 StringRef varName = VD.getName(); 641 642 if (Tag == dwarf::DW_TAG_pointer_type) { 643 DIDerivedType DTy = DIDerivedType(Ty.getNode()); 644 TmpTy = DTy.getTypeDerivedFrom(); 645 isPointer = true; 646 } 647 648 DICompositeType blockStruct = DICompositeType(TmpTy.getNode()); 649 650 // Find the __forwarding field and the variable field in the __Block_byref 651 // struct. 652 DIArray Fields = blockStruct.getTypeArray(); 653 DIDescriptor varField = DIDescriptor(); 654 DIDescriptor forwardingField = DIDescriptor(); 655 656 657 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) { 658 DIDescriptor Element = Fields.getElement(i); 659 DIDerivedType DT = DIDerivedType(Element.getNode()); 660 StringRef fieldName = DT.getName(); 661 if (fieldName == "__forwarding") 662 forwardingField = Element; 663 else if (fieldName == varName) 664 varField = Element; 665 } 666 667 assert(!varField.isNull() && "Can't find byref variable in Block struct"); 668 assert(!forwardingField.isNull() 669 && "Can't find forwarding field in Block struct"); 670 671 // Get the offsets for the forwarding field and the variable field. 672 unsigned int forwardingFieldOffset = 673 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3; 674 unsigned int varFieldOffset = 675 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3; 676 677 // Decode the original location, and use that as the start of the byref 678 // variable's location. 679 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false); 680 DIEBlock *Block = new DIEBlock(); 681 682 if (Location.isReg()) { 683 if (Reg < 32) 684 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg); 685 else { 686 Reg = Reg - dwarf::DW_OP_reg0; 687 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg); 688 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg); 689 } 690 } else { 691 if (Reg < 32) 692 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg); 693 else { 694 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx); 695 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg); 696 } 697 698 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset()); 699 } 700 701 // If we started with a pointer to the __Block_byref... struct, then 702 // the first thing we need to do is dereference the pointer (DW_OP_deref). 703 if (isPointer) 704 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 705 706 // Next add the offset for the '__forwarding' field: 707 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in 708 // adding the offset if it's 0. 709 if (forwardingFieldOffset > 0) { 710 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 711 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset); 712 } 713 714 // Now dereference the __forwarding field to get to the real __Block_byref 715 // struct: DW_OP_deref. 716 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 717 718 // Now that we've got the real __Block_byref... struct, add the offset 719 // for the variable's field to get to the location of the actual variable: 720 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0. 721 if (varFieldOffset > 0) { 722 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 723 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset); 724 } 725 726 // Now attach the location information to the DIE. 727 addBlock(Die, Attribute, 0, Block); 728} 729 730/// addAddress - Add an address attribute to a die based on the location 731/// provided. 732void DwarfDebug::addAddress(DIE *Die, unsigned Attribute, 733 const MachineLocation &Location) { 734 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false); 735 DIEBlock *Block = new DIEBlock(); 736 737 if (Location.isReg()) { 738 if (Reg < 32) { 739 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg); 740 } else { 741 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx); 742 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg); 743 } 744 } else { 745 if (Reg < 32) { 746 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg); 747 } else { 748 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx); 749 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg); 750 } 751 752 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset()); 753 } 754 755 addBlock(Die, Attribute, 0, Block); 756} 757 758/// addType - Add a new type attribute to the specified entity. 759void DwarfDebug::addType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) { 760 if (Ty.isNull()) 761 return; 762 763 // Check for pre-existence. 764 DIEEntry *Entry = DW_Unit->getDIEEntry(Ty.getNode()); 765 766 // If it exists then use the existing value. 767 if (Entry) { 768 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry); 769 return; 770 } 771 772 // Set up proxy. 773 Entry = createDIEEntry(); 774 DW_Unit->insertDIEEntry(Ty.getNode(), Entry); 775 776 // Construct type. 777 DIE *Buffer = new DIE(dwarf::DW_TAG_base_type); 778 ModuleCU->insertDIE(Ty.getNode(), Buffer); 779 if (Ty.isBasicType()) 780 constructTypeDIE(DW_Unit, *Buffer, DIBasicType(Ty.getNode())); 781 else if (Ty.isCompositeType()) 782 constructTypeDIE(DW_Unit, *Buffer, DICompositeType(Ty.getNode())); 783 else { 784 assert(Ty.isDerivedType() && "Unknown kind of DIType"); 785 constructTypeDIE(DW_Unit, *Buffer, DIDerivedType(Ty.getNode())); 786 } 787 788 // Add debug information entry to entity and appropriate context. 789 DIE *Die = NULL; 790 DIDescriptor Context = Ty.getContext(); 791 if (!Context.isNull()) { 792 if (Context.isNameSpace()) { 793 DINameSpace NS(Context.getNode()); 794 Die = getOrCreateNameSpace(NS); 795 } else 796 Die = DW_Unit->getDIE(Context.getNode()); 797 } 798 if (Die) 799 Die->addChild(Buffer); 800 else 801 DW_Unit->addDie(Buffer); 802 Entry->setEntry(Buffer); 803 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry); 804} 805 806/// constructTypeDIE - Construct basic type die from DIBasicType. 807void DwarfDebug::constructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer, 808 DIBasicType BTy) { 809 // Get core information. 810 StringRef Name = BTy.getName(); 811 Buffer.setTag(dwarf::DW_TAG_base_type); 812 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, 813 BTy.getEncoding()); 814 815 // Add name if not anonymous or intermediate type. 816 if (!Name.empty()) 817 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name); 818 uint64_t Size = BTy.getSizeInBits() >> 3; 819 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size); 820} 821 822/// constructTypeDIE - Construct derived type die from DIDerivedType. 823void DwarfDebug::constructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer, 824 DIDerivedType DTy) { 825 // Get core information. 826 StringRef Name = DTy.getName(); 827 uint64_t Size = DTy.getSizeInBits() >> 3; 828 unsigned Tag = DTy.getTag(); 829 830 // FIXME - Workaround for templates. 831 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type; 832 833 Buffer.setTag(Tag); 834 835 // Map to main type, void will not have a type. 836 DIType FromTy = DTy.getTypeDerivedFrom(); 837 addType(DW_Unit, &Buffer, FromTy); 838 839 // Add name if not anonymous or intermediate type. 840 if (!Name.empty()) 841 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name); 842 843 // Add size if non-zero (derived types might be zero-sized.) 844 if (Size) 845 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size); 846 847 // Add source line info if available and TyDesc is not a forward declaration. 848 if (!DTy.isForwardDecl()) 849 addSourceLine(&Buffer, &DTy); 850} 851 852/// constructTypeDIE - Construct type DIE from DICompositeType. 853void DwarfDebug::constructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer, 854 DICompositeType CTy) { 855 // Get core information. 856 StringRef Name = CTy.getName(); 857 858 uint64_t Size = CTy.getSizeInBits() >> 3; 859 unsigned Tag = CTy.getTag(); 860 Buffer.setTag(Tag); 861 862 switch (Tag) { 863 case dwarf::DW_TAG_vector_type: 864 case dwarf::DW_TAG_array_type: 865 constructArrayTypeDIE(DW_Unit, Buffer, &CTy); 866 break; 867 case dwarf::DW_TAG_enumeration_type: { 868 DIArray Elements = CTy.getTypeArray(); 869 870 // Add enumerators to enumeration type. 871 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) { 872 DIE *ElemDie = NULL; 873 DIEnumerator Enum(Elements.getElement(i).getNode()); 874 if (!Enum.isNull()) { 875 ElemDie = constructEnumTypeDIE(DW_Unit, &Enum); 876 Buffer.addChild(ElemDie); 877 } 878 } 879 } 880 break; 881 case dwarf::DW_TAG_subroutine_type: { 882 // Add return type. 883 DIArray Elements = CTy.getTypeArray(); 884 DIDescriptor RTy = Elements.getElement(0); 885 addType(DW_Unit, &Buffer, DIType(RTy.getNode())); 886 887 // Add prototype flag. 888 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1); 889 890 // Add arguments. 891 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) { 892 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter); 893 DIDescriptor Ty = Elements.getElement(i); 894 addType(DW_Unit, Arg, DIType(Ty.getNode())); 895 Buffer.addChild(Arg); 896 } 897 } 898 break; 899 case dwarf::DW_TAG_structure_type: 900 case dwarf::DW_TAG_union_type: 901 case dwarf::DW_TAG_class_type: { 902 // Add elements to structure type. 903 DIArray Elements = CTy.getTypeArray(); 904 905 // A forward struct declared type may not have elements available. 906 if (Elements.isNull()) 907 break; 908 909 // Add elements to structure type. 910 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) { 911 DIDescriptor Element = Elements.getElement(i); 912 if (Element.isNull()) 913 continue; 914 DIE *ElemDie = NULL; 915 if (Element.getTag() == dwarf::DW_TAG_subprogram) 916 ElemDie = createMemberSubprogramDIE(DW_Unit, 917 DISubprogram(Element.getNode())); 918 else 919 ElemDie = createMemberDIE(DW_Unit, 920 DIDerivedType(Element.getNode())); 921 Buffer.addChild(ElemDie); 922 } 923 924 if (CTy.isAppleBlockExtension()) 925 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1); 926 927 unsigned RLang = CTy.getRunTimeLang(); 928 if (RLang) 929 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, 930 dwarf::DW_FORM_data1, RLang); 931 break; 932 } 933 default: 934 break; 935 } 936 937 // Add name if not anonymous or intermediate type. 938 if (!Name.empty()) 939 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name); 940 941 if (Tag == dwarf::DW_TAG_enumeration_type || 942 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) { 943 // Add size if non-zero (derived types might be zero-sized.) 944 if (Size) 945 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size); 946 else { 947 // Add zero size if it is not a forward declaration. 948 if (CTy.isForwardDecl()) 949 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1); 950 else 951 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0); 952 } 953 954 // Add source line info if available. 955 if (!CTy.isForwardDecl()) 956 addSourceLine(&Buffer, &CTy); 957 } 958} 959 960/// constructSubrangeDIE - Construct subrange DIE from DISubrange. 961void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){ 962 int64_t L = SR.getLo(); 963 int64_t H = SR.getHi(); 964 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type); 965 966 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy); 967 if (L) 968 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L); 969 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H); 970 971 Buffer.addChild(DW_Subrange); 972} 973 974/// constructArrayTypeDIE - Construct array type DIE from DICompositeType. 975void DwarfDebug::constructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer, 976 DICompositeType *CTy) { 977 Buffer.setTag(dwarf::DW_TAG_array_type); 978 if (CTy->getTag() == dwarf::DW_TAG_vector_type) 979 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1); 980 981 // Emit derived type. 982 addType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom()); 983 DIArray Elements = CTy->getTypeArray(); 984 985 // Get an anonymous type for index type. 986 DIE *IdxTy = DW_Unit->getIndexTyDie(); 987 if (!IdxTy) { 988 // Construct an anonymous type for index type. 989 IdxTy = new DIE(dwarf::DW_TAG_base_type); 990 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t)); 991 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, 992 dwarf::DW_ATE_signed); 993 DW_Unit->addDie(IdxTy); 994 DW_Unit->setIndexTyDie(IdxTy); 995 } 996 997 // Add subranges to array type. 998 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) { 999 DIDescriptor Element = Elements.getElement(i); 1000 if (Element.getTag() == dwarf::DW_TAG_subrange_type) 1001 constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy); 1002 } 1003} 1004 1005/// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator. 1006DIE *DwarfDebug::constructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) { 1007 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator); 1008 StringRef Name = ETy->getName(); 1009 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name); 1010 int64_t Value = ETy->getEnumValue(); 1011 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value); 1012 return Enumerator; 1013} 1014 1015/// createGlobalVariableDIE - Create new DIE using GV. 1016DIE *DwarfDebug::createGlobalVariableDIE(CompileUnit *DW_Unit, 1017 const DIGlobalVariable &GV) { 1018 // If the global variable was optmized out then no need to create debug info 1019 // entry. 1020 if (!GV.getGlobal()) return NULL; 1021 if (GV.getDisplayName().empty()) return NULL; 1022 1023 DIE *GVDie = new DIE(dwarf::DW_TAG_variable); 1024 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, 1025 GV.getDisplayName()); 1026 1027 StringRef LinkageName = GV.getLinkageName(); 1028 if (!LinkageName.empty()) { 1029 // Skip special LLVM prefix that is used to inform the asm printer to not 1030 // emit usual symbol prefix before the symbol name. This happens for 1031 // Objective-C symbol names and symbol whose name is replaced using GCC's 1032 // __asm__ attribute. 1033 if (LinkageName[0] == 1) 1034 LinkageName = LinkageName.substr(1); 1035 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string, 1036 LinkageName); 1037 } 1038 addType(DW_Unit, GVDie, GV.getType()); 1039 if (!GV.isLocalToUnit()) 1040 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1); 1041 addSourceLine(GVDie, &GV); 1042 1043 // Add address. 1044 DIEBlock *Block = new DIEBlock(); 1045 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr); 1046 addObjectLabel(Block, 0, dwarf::DW_FORM_udata, 1047 Asm->Mang->getMangledName(GV.getGlobal())); 1048 addBlock(GVDie, dwarf::DW_AT_location, 0, Block); 1049 1050 return GVDie; 1051} 1052 1053/// createMemberDIE - Create new member DIE. 1054DIE *DwarfDebug::createMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){ 1055 DIE *MemberDie = new DIE(DT.getTag()); 1056 StringRef Name = DT.getName(); 1057 if (!Name.empty()) 1058 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name); 1059 1060 addType(DW_Unit, MemberDie, DT.getTypeDerivedFrom()); 1061 1062 addSourceLine(MemberDie, &DT); 1063 1064 DIEBlock *MemLocationDie = new DIEBlock(); 1065 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 1066 1067 uint64_t Size = DT.getSizeInBits(); 1068 uint64_t FieldSize = DT.getOriginalTypeSize(); 1069 1070 if (Size != FieldSize) { 1071 // Handle bitfield. 1072 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3); 1073 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits()); 1074 1075 uint64_t Offset = DT.getOffsetInBits(); 1076 uint64_t FieldOffset = Offset; 1077 uint64_t AlignMask = ~(DT.getAlignInBits() - 1); 1078 uint64_t HiMark = (Offset + FieldSize) & AlignMask; 1079 FieldOffset = (HiMark - FieldSize); 1080 Offset -= FieldOffset; 1081 1082 // Maybe we need to work from the other end. 1083 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size); 1084 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset); 1085 1086 // Here WD_AT_data_member_location points to the anonymous 1087 // field that includes this bit field. 1088 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3); 1089 1090 } else 1091 // This is not a bitfield. 1092 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3); 1093 1094 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie); 1095 1096 if (DT.isProtected()) 1097 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag, 1098 dwarf::DW_ACCESS_protected); 1099 else if (DT.isPrivate()) 1100 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag, 1101 dwarf::DW_ACCESS_private); 1102 else if (DT.getTag() == dwarf::DW_TAG_inheritance) 1103 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag, 1104 dwarf::DW_ACCESS_public); 1105 if (DT.isVirtual()) 1106 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, 1107 dwarf::DW_VIRTUALITY_virtual); 1108 return MemberDie; 1109} 1110 1111/// createRawSubprogramDIE - Create new partially incomplete DIE. This is 1112/// a helper routine used by createMemberSubprogramDIE and 1113/// createSubprogramDIE. 1114DIE *DwarfDebug::createRawSubprogramDIE(CompileUnit *DW_Unit, 1115 const DISubprogram &SP) { 1116 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram); 1117 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName()); 1118 1119 StringRef LinkageName = SP.getLinkageName(); 1120 if (!LinkageName.empty()) { 1121 // Skip special LLVM prefix that is used to inform the asm printer to not 1122 // emit usual symbol prefix before the symbol name. This happens for 1123 // Objective-C symbol names and symbol whose name is replaced using GCC's 1124 // __asm__ attribute. 1125 if (LinkageName[0] == 1) 1126 LinkageName = LinkageName.substr(1); 1127 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string, 1128 LinkageName); 1129 } 1130 addSourceLine(SPDie, &SP); 1131 1132 // Add prototyped tag, if C or ObjC. 1133 unsigned Lang = SP.getCompileUnit().getLanguage(); 1134 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 || 1135 Lang == dwarf::DW_LANG_ObjC) 1136 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1); 1137 1138 // Add Return Type. 1139 DICompositeType SPTy = SP.getType(); 1140 DIArray Args = SPTy.getTypeArray(); 1141 unsigned SPTag = SPTy.getTag(); 1142 1143 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type) 1144 addType(DW_Unit, SPDie, SPTy); 1145 else 1146 addType(DW_Unit, SPDie, DIType(Args.getElement(0).getNode())); 1147 1148 unsigned VK = SP.getVirtuality(); 1149 if (VK) { 1150 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK); 1151 DIEBlock *Block = new DIEBlock(); 1152 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 1153 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex()); 1154 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block); 1155 ContainingTypeMap.insert(std::make_pair(SPDie, WeakVH(SP.getContainingType().getNode()))); 1156 } 1157 1158 return SPDie; 1159} 1160 1161/// createMemberSubprogramDIE - Create new member DIE using SP. This routine 1162/// always returns a die with DW_AT_declaration attribute. 1163DIE *DwarfDebug::createMemberSubprogramDIE(CompileUnit *DW_Unit, 1164 const DISubprogram &SP) { 1165 DIE *SPDie = ModuleCU->getDIE(SP.getNode()); 1166 if (!SPDie) 1167 SPDie = createSubprogramDIE(DW_Unit, SP); 1168 1169 // If SPDie has DW_AT_declaration then reuse it. 1170 if (!SP.isDefinition()) 1171 return SPDie; 1172 1173 // Otherwise create new DIE for the declaration. First push definition 1174 // DIE at the top level. 1175 if (TopLevelDIEs.insert(SPDie)) 1176 TopLevelDIEsVector.push_back(SPDie); 1177 1178 SPDie = createRawSubprogramDIE(DW_Unit, SP); 1179 1180 // Add arguments. 1181 DICompositeType SPTy = SP.getType(); 1182 DIArray Args = SPTy.getTypeArray(); 1183 unsigned SPTag = SPTy.getTag(); 1184 if (SPTag == dwarf::DW_TAG_subroutine_type) 1185 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) { 1186 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter); 1187 addType(DW_Unit, Arg, DIType(Args.getElement(i).getNode())); 1188 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ?? 1189 SPDie->addChild(Arg); 1190 } 1191 1192 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1); 1193 return SPDie; 1194} 1195 1196/// createSubprogramDIE - Create new DIE using SP. 1197DIE *DwarfDebug::createSubprogramDIE(CompileUnit *DW_Unit, 1198 const DISubprogram &SP) { 1199 DIE *SPDie = ModuleCU->getDIE(SP.getNode()); 1200 if (SPDie) 1201 return SPDie; 1202 1203 SPDie = createRawSubprogramDIE(DW_Unit, SP); 1204 1205 if (!SP.isDefinition()) { 1206 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1); 1207 1208 // Add arguments. Do not add arguments for subprogram definition. They will 1209 // be handled while processing variables. 1210 DICompositeType SPTy = SP.getType(); 1211 DIArray Args = SPTy.getTypeArray(); 1212 unsigned SPTag = SPTy.getTag(); 1213 1214 if (SPTag == dwarf::DW_TAG_subroutine_type) 1215 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) { 1216 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter); 1217 addType(DW_Unit, Arg, DIType(Args.getElement(i).getNode())); 1218 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ?? 1219 SPDie->addChild(Arg); 1220 } 1221 } 1222 1223 // DW_TAG_inlined_subroutine may refer to this DIE. 1224 DW_Unit->insertDIE(SP.getNode(), SPDie); 1225 return SPDie; 1226} 1227 1228/// findCompileUnit - Get the compile unit for the given descriptor. 1229/// 1230CompileUnit &DwarfDebug::findCompileUnit(DICompileUnit Unit) const { 1231 DenseMap<Value *, CompileUnit *>::const_iterator I = 1232 CompileUnitMap.find(Unit.getNode()); 1233 assert(I != CompileUnitMap.end() && "Missing compile unit."); 1234 return *I->second; 1235} 1236 1237/// createDbgScopeVariable - Create a new scope variable. 1238/// 1239DIE *DwarfDebug::createDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) { 1240 // Get the descriptor. 1241 const DIVariable &VD = DV->getVariable(); 1242 StringRef Name = VD.getName(); 1243 if (Name.empty()) 1244 return NULL; 1245 1246 // Translate tag to proper Dwarf tag. The result variable is dropped for 1247 // now. 1248 unsigned Tag; 1249 switch (VD.getTag()) { 1250 case dwarf::DW_TAG_return_variable: 1251 return NULL; 1252 case dwarf::DW_TAG_arg_variable: 1253 Tag = dwarf::DW_TAG_formal_parameter; 1254 break; 1255 case dwarf::DW_TAG_auto_variable: // fall thru 1256 default: 1257 Tag = dwarf::DW_TAG_variable; 1258 break; 1259 } 1260 1261 // Define variable debug information entry. 1262 DIE *VariableDie = new DIE(Tag); 1263 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name); 1264 1265 // Add source line info if available. 1266 addSourceLine(VariableDie, &VD); 1267 1268 // Add variable type. 1269 // FIXME: isBlockByrefVariable should be reformulated in terms of complex 1270 // addresses instead. 1271 if (VD.isBlockByrefVariable()) 1272 addType(Unit, VariableDie, getBlockByrefType(VD.getType(), Name)); 1273 else 1274 addType(Unit, VariableDie, VD.getType()); 1275 1276 // Add variable address. 1277 // Variables for abstract instances of inlined functions don't get a 1278 // location. 1279 MachineLocation Location; 1280 unsigned FrameReg; 1281 int Offset = RI->getFrameIndexReference(*MF, DV->getFrameIndex(), FrameReg); 1282 Location.set(FrameReg, Offset); 1283 1284 1285 if (VD.hasComplexAddress()) 1286 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location); 1287 else if (VD.isBlockByrefVariable()) 1288 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location); 1289 else 1290 addAddress(VariableDie, dwarf::DW_AT_location, Location); 1291 1292 return VariableDie; 1293} 1294 1295/// getUpdatedDbgScope - Find or create DbgScope assicated with the instruction. 1296/// Initialize scope and update scope hierarchy. 1297DbgScope *DwarfDebug::getUpdatedDbgScope(MDNode *N, const MachineInstr *MI, 1298 MDNode *InlinedAt) { 1299 assert (N && "Invalid Scope encoding!"); 1300 assert (MI && "Missing machine instruction!"); 1301 bool GetConcreteScope = (MI && InlinedAt); 1302 1303 DbgScope *NScope = NULL; 1304 1305 if (InlinedAt) 1306 NScope = DbgScopeMap.lookup(InlinedAt); 1307 else 1308 NScope = DbgScopeMap.lookup(N); 1309 assert (NScope && "Unable to find working scope!"); 1310 1311 if (NScope->getFirstInsn()) 1312 return NScope; 1313 1314 DbgScope *Parent = NULL; 1315 if (GetConcreteScope) { 1316 DILocation IL(InlinedAt); 1317 Parent = getUpdatedDbgScope(IL.getScope().getNode(), MI, 1318 IL.getOrigLocation().getNode()); 1319 assert (Parent && "Unable to find Parent scope!"); 1320 NScope->setParent(Parent); 1321 Parent->addScope(NScope); 1322 } else if (DIDescriptor(N).isLexicalBlock()) { 1323 DILexicalBlock DB(N); 1324 if (!DB.getContext().isNull()) { 1325 Parent = getUpdatedDbgScope(DB.getContext().getNode(), MI, InlinedAt); 1326 NScope->setParent(Parent); 1327 Parent->addScope(NScope); 1328 } 1329 } 1330 1331 NScope->setFirstInsn(MI); 1332 1333 if (!Parent && !InlinedAt) { 1334 StringRef SPName = DISubprogram(N).getLinkageName(); 1335 if (SPName == MF->getFunction()->getName()) 1336 CurrentFnDbgScope = NScope; 1337 } 1338 1339 if (GetConcreteScope) { 1340 ConcreteScopes[InlinedAt] = NScope; 1341 getOrCreateAbstractScope(N); 1342 } 1343 1344 return NScope; 1345} 1346 1347DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) { 1348 assert (N && "Invalid Scope encoding!"); 1349 1350 DbgScope *AScope = AbstractScopes.lookup(N); 1351 if (AScope) 1352 return AScope; 1353 1354 DbgScope *Parent = NULL; 1355 1356 DIDescriptor Scope(N); 1357 if (Scope.isLexicalBlock()) { 1358 DILexicalBlock DB(N); 1359 DIDescriptor ParentDesc = DB.getContext(); 1360 if (!ParentDesc.isNull()) 1361 Parent = getOrCreateAbstractScope(ParentDesc.getNode()); 1362 } 1363 1364 AScope = new DbgScope(Parent, DIDescriptor(N), NULL); 1365 1366 if (Parent) 1367 Parent->addScope(AScope); 1368 AScope->setAbstractScope(); 1369 AbstractScopes[N] = AScope; 1370 if (DIDescriptor(N).isSubprogram()) 1371 AbstractScopesList.push_back(AScope); 1372 return AScope; 1373} 1374 1375/// updateSubprogramScopeDIE - Find DIE for the given subprogram and 1376/// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes. 1377/// If there are global variables in this scope then create and insert 1378/// DIEs for these variables. 1379DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) { 1380 1381 DIE *SPDie = ModuleCU->getDIE(SPNode); 1382 assert (SPDie && "Unable to find subprogram DIE!"); 1383 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 1384 DWLabel("func_begin", SubprogramCount)); 1385 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, 1386 DWLabel("func_end", SubprogramCount)); 1387 MachineLocation Location(RI->getFrameRegister(*MF)); 1388 addAddress(SPDie, dwarf::DW_AT_frame_base, Location); 1389 1390 if (!DISubprogram(SPNode).isLocalToUnit()) 1391 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1); 1392 1393 // If there are global variables at this scope then add their dies. 1394 for (SmallVector<WeakVH, 4>::iterator SGI = ScopedGVs.begin(), 1395 SGE = ScopedGVs.end(); SGI != SGE; ++SGI) { 1396 MDNode *N = dyn_cast_or_null<MDNode>(*SGI); 1397 if (!N) continue; 1398 DIGlobalVariable GV(N); 1399 if (GV.getContext().getNode() == SPNode) { 1400 DIE *ScopedGVDie = createGlobalVariableDIE(ModuleCU, GV); 1401 if (ScopedGVDie) 1402 SPDie->addChild(ScopedGVDie); 1403 } 1404 } 1405 1406 return SPDie; 1407} 1408 1409/// constructLexicalScope - Construct new DW_TAG_lexical_block 1410/// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels. 1411DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) { 1412 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID()); 1413 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID()); 1414 1415 // Ignore empty scopes. 1416 if (StartID == EndID && StartID != 0) 1417 return NULL; 1418 1419 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block); 1420 if (Scope->isAbstractScope()) 1421 return ScopeDIE; 1422 1423 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 1424 StartID ? 1425 DWLabel("label", StartID) 1426 : DWLabel("func_begin", SubprogramCount)); 1427 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, 1428 EndID ? 1429 DWLabel("label", EndID) 1430 : DWLabel("func_end", SubprogramCount)); 1431 1432 1433 1434 return ScopeDIE; 1435} 1436 1437/// constructInlinedScopeDIE - This scope represents inlined body of 1438/// a function. Construct DIE to represent this concrete inlined copy 1439/// of the function. 1440DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) { 1441 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID()); 1442 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID()); 1443 assert (StartID && "Invalid starting label for an inlined scope!"); 1444 assert (EndID && "Invalid end label for an inlined scope!"); 1445 // Ignore empty scopes. 1446 if (StartID == EndID && StartID != 0) 1447 return NULL; 1448 1449 DIScope DS(Scope->getScopeNode()); 1450 if (DS.isNull()) 1451 return NULL; 1452 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine); 1453 1454 DISubprogram InlinedSP = getDISubprogram(DS.getNode()); 1455 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode()); 1456 assert (OriginDIE && "Unable to find Origin DIE!"); 1457 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, 1458 dwarf::DW_FORM_ref4, OriginDIE); 1459 1460 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 1461 DWLabel("label", StartID)); 1462 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, 1463 DWLabel("label", EndID)); 1464 1465 InlinedSubprogramDIEs.insert(OriginDIE); 1466 1467 // Track the start label for this inlined function. 1468 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator 1469 I = InlineInfo.find(InlinedSP.getNode()); 1470 1471 if (I == InlineInfo.end()) { 1472 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartID, 1473 ScopeDIE)); 1474 InlinedSPNodes.push_back(InlinedSP.getNode()); 1475 } else 1476 I->second.push_back(std::make_pair(StartID, ScopeDIE)); 1477 1478 StringPool.insert(InlinedSP.getName()); 1479 StringPool.insert(InlinedSP.getLinkageName()); 1480 DILocation DL(Scope->getInlinedAt()); 1481 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID()); 1482 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber()); 1483 1484 return ScopeDIE; 1485} 1486 1487 1488/// constructVariableDIE - Construct a DIE for the given DbgVariable. 1489DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, 1490 DbgScope *Scope, CompileUnit *Unit) { 1491 // Get the descriptor. 1492 const DIVariable &VD = DV->getVariable(); 1493 StringRef Name = VD.getName(); 1494 if (Name.empty()) 1495 return NULL; 1496 1497 // Translate tag to proper Dwarf tag. The result variable is dropped for 1498 // now. 1499 unsigned Tag; 1500 switch (VD.getTag()) { 1501 case dwarf::DW_TAG_return_variable: 1502 return NULL; 1503 case dwarf::DW_TAG_arg_variable: 1504 Tag = dwarf::DW_TAG_formal_parameter; 1505 break; 1506 case dwarf::DW_TAG_auto_variable: // fall thru 1507 default: 1508 Tag = dwarf::DW_TAG_variable; 1509 break; 1510 } 1511 1512 // Define variable debug information entry. 1513 DIE *VariableDie = new DIE(Tag); 1514 1515 1516 DIE *AbsDIE = NULL; 1517 if (DbgVariable *AV = DV->getAbstractVariable()) 1518 AbsDIE = AV->getDIE(); 1519 1520 if (AbsDIE) { 1521 DIScope DS(Scope->getScopeNode()); 1522 DISubprogram InlinedSP = getDISubprogram(DS.getNode()); 1523 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode()); 1524 (void) OriginSPDIE; 1525 assert (OriginSPDIE && "Unable to find Origin DIE for the SP!"); 1526 DIE *AbsDIE = DV->getAbstractVariable()->getDIE(); 1527 assert (AbsDIE && "Unable to find Origin DIE for the Variable!"); 1528 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, 1529 dwarf::DW_FORM_ref4, AbsDIE); 1530 } 1531 else { 1532 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name); 1533 addSourceLine(VariableDie, &VD); 1534 1535 // Add variable type. 1536 // FIXME: isBlockByrefVariable should be reformulated in terms of complex 1537 // addresses instead. 1538 if (VD.isBlockByrefVariable()) 1539 addType(Unit, VariableDie, getBlockByrefType(VD.getType(), Name)); 1540 else 1541 addType(Unit, VariableDie, VD.getType()); 1542 } 1543 1544 // Add variable address. 1545 if (!Scope->isAbstractScope()) { 1546 MachineLocation Location; 1547 unsigned FrameReg; 1548 int Offset = RI->getFrameIndexReference(*MF, DV->getFrameIndex(), FrameReg); 1549 Location.set(FrameReg, Offset); 1550 1551 if (VD.hasComplexAddress()) 1552 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location); 1553 else if (VD.isBlockByrefVariable()) 1554 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location); 1555 else 1556 addAddress(VariableDie, dwarf::DW_AT_location, Location); 1557 } 1558 DV->setDIE(VariableDie); 1559 return VariableDie; 1560 1561} 1562 1563void DwarfDebug::addPubTypes(DISubprogram SP) { 1564 DICompositeType SPTy = SP.getType(); 1565 unsigned SPTag = SPTy.getTag(); 1566 if (SPTag != dwarf::DW_TAG_subroutine_type) 1567 return; 1568 1569 DIArray Args = SPTy.getTypeArray(); 1570 if (Args.isNull()) 1571 return; 1572 1573 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) { 1574 DIType ATy(Args.getElement(i).getNode()); 1575 if (ATy.isNull()) 1576 continue; 1577 DICompositeType CATy = getDICompositeType(ATy); 1578 if (!CATy.isNull() && !CATy.getName().empty()) { 1579 if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode())) 1580 ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry()); 1581 } 1582 } 1583} 1584 1585/// constructScopeDIE - Construct a DIE for this scope. 1586DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) { 1587 if (!Scope) 1588 return NULL; 1589 DIScope DS(Scope->getScopeNode()); 1590 if (DS.isNull()) 1591 return NULL; 1592 1593 DIE *ScopeDIE = NULL; 1594 if (Scope->getInlinedAt()) 1595 ScopeDIE = constructInlinedScopeDIE(Scope); 1596 else if (DS.isSubprogram()) { 1597 if (Scope->isAbstractScope()) 1598 ScopeDIE = ModuleCU->getDIE(DS.getNode()); 1599 else 1600 ScopeDIE = updateSubprogramScopeDIE(DS.getNode()); 1601 } 1602 else { 1603 ScopeDIE = constructLexicalScopeDIE(Scope); 1604 if (!ScopeDIE) return NULL; 1605 } 1606 1607 // Add variables to scope. 1608 SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables(); 1609 for (unsigned i = 0, N = Variables.size(); i < N; ++i) { 1610 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope, ModuleCU); 1611 if (VariableDIE) 1612 ScopeDIE->addChild(VariableDIE); 1613 } 1614 1615 // Add nested scopes. 1616 SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes(); 1617 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) { 1618 // Define the Scope debug information entry. 1619 DIE *NestedDIE = constructScopeDIE(Scopes[j]); 1620 if (NestedDIE) 1621 ScopeDIE->addChild(NestedDIE); 1622 } 1623 1624 if (DS.isSubprogram()) 1625 addPubTypes(DISubprogram(DS.getNode())); 1626 1627 return ScopeDIE; 1628} 1629 1630/// GetOrCreateSourceID - Look up the source id with the given directory and 1631/// source file names. If none currently exists, create a new id and insert it 1632/// in the SourceIds map. This can update DirectoryNames and SourceFileNames 1633/// maps as well. 1634unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName) { 1635 unsigned DId; 1636 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName); 1637 if (DI != DirectoryIdMap.end()) { 1638 DId = DI->getValue(); 1639 } else { 1640 DId = DirectoryNames.size() + 1; 1641 DirectoryIdMap[DirName] = DId; 1642 DirectoryNames.push_back(DirName); 1643 } 1644 1645 unsigned FId; 1646 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName); 1647 if (FI != SourceFileIdMap.end()) { 1648 FId = FI->getValue(); 1649 } else { 1650 FId = SourceFileNames.size() + 1; 1651 SourceFileIdMap[FileName] = FId; 1652 SourceFileNames.push_back(FileName); 1653 } 1654 1655 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI = 1656 SourceIdMap.find(std::make_pair(DId, FId)); 1657 if (SI != SourceIdMap.end()) 1658 return SI->second; 1659 1660 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0. 1661 SourceIdMap[std::make_pair(DId, FId)] = SrcId; 1662 SourceIds.push_back(std::make_pair(DId, FId)); 1663 1664 return SrcId; 1665} 1666 1667/// getOrCreateNameSpace - Create a DIE for DINameSpace. 1668DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace &NS) { 1669 DIE *NDie = ModuleCU->getDIE(NS.getNode()); 1670 if (NDie) 1671 return NDie; 1672 1673 NDie = new DIE(dwarf::DW_TAG_namespace); 1674 ModuleCU->insertDIE(NS.getNode(), NDie); 1675 if (!NS.getName().empty()) 1676 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName()); 1677 addSourceLine(NDie, &NS); 1678 DIDescriptor NSContext = NS.getContext(); 1679 DIE *Context = NULL; 1680 if (NSContext.isNameSpace()) { 1681 DINameSpace NS2(NSContext.getNode()); 1682 Context = getOrCreateNameSpace(NS2); 1683 } 1684 else 1685 Context = ModuleCU->getCUDie(); 1686 Context->addChild(NDie); 1687 return NDie; 1688} 1689 1690void DwarfDebug::constructCompileUnit(MDNode *N) { 1691 DICompileUnit DIUnit(N); 1692 StringRef FN = DIUnit.getFilename(); 1693 StringRef Dir = DIUnit.getDirectory(); 1694 unsigned ID = GetOrCreateSourceID(Dir, FN); 1695 1696 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit); 1697 addSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 1698 DWLabel("section_line", 0), DWLabel("section_line", 0), 1699 false); 1700 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string, 1701 DIUnit.getProducer()); 1702 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1, 1703 DIUnit.getLanguage()); 1704 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN); 1705 1706 if (!Dir.empty()) 1707 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir); 1708 if (DIUnit.isOptimized()) 1709 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1); 1710 1711 StringRef Flags = DIUnit.getFlags(); 1712 if (!Flags.empty()) 1713 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags); 1714 1715 unsigned RVer = DIUnit.getRunTimeVersion(); 1716 if (RVer) 1717 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers, 1718 dwarf::DW_FORM_data1, RVer); 1719 1720 CompileUnit *Unit = new CompileUnit(ID, Die); 1721 if (!ModuleCU && DIUnit.isMain()) { 1722 // Use first compile unit marked as isMain as the compile unit 1723 // for this module. 1724 ModuleCU = Unit; 1725 } 1726 1727 CompileUnitMap[DIUnit.getNode()] = Unit; 1728 CompileUnits.push_back(Unit); 1729} 1730 1731void DwarfDebug::constructGlobalVariableDIE(MDNode *N) { 1732 DIGlobalVariable DI_GV(N); 1733 1734 // If debug information is malformed then ignore it. 1735 if (DI_GV.Verify() == false) 1736 return; 1737 1738 // Check for pre-existence. 1739 if (ModuleCU->getDIE(DI_GV.getNode())) 1740 return; 1741 1742 DIE *VariableDie = createGlobalVariableDIE(ModuleCU, DI_GV); 1743 1744 // Add to map. 1745 ModuleCU->insertDIE(N, VariableDie); 1746 1747 // Add to context owner. 1748 if (TopLevelDIEs.insert(VariableDie)) 1749 TopLevelDIEsVector.push_back(VariableDie); 1750 1751 // Expose as global. FIXME - need to check external flag. 1752 ModuleCU->addGlobal(DI_GV.getName(), VariableDie); 1753 1754 DIType GTy = DI_GV.getType(); 1755 if (GTy.isCompositeType() && !GTy.getName().empty()) { 1756 DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode()); 1757 assert (Entry && "Missing global type!"); 1758 ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry()); 1759 } 1760 return; 1761} 1762 1763void DwarfDebug::constructSubprogramDIE(MDNode *N) { 1764 DISubprogram SP(N); 1765 1766 // Check for pre-existence. 1767 if (ModuleCU->getDIE(N)) 1768 return; 1769 1770 if (!SP.isDefinition()) 1771 // This is a method declaration which will be handled while constructing 1772 // class type. 1773 return; 1774 1775 DIE *SubprogramDie = createSubprogramDIE(ModuleCU, SP); 1776 1777 // Add to map. 1778 ModuleCU->insertDIE(N, SubprogramDie); 1779 1780 // Add to context owner. 1781 DIDescriptor SPContext = SP.getContext(); 1782 if (SPContext.isCompileUnit() 1783 && SPContext.getNode() == SP.getCompileUnit().getNode()) { 1784 if (TopLevelDIEs.insert(SubprogramDie)) 1785 TopLevelDIEsVector.push_back(SubprogramDie); 1786 } else if (SPContext.isNameSpace()) { 1787 DINameSpace NS(SPContext.getNode()); 1788 DIE *NDie = getOrCreateNameSpace(NS); 1789 NDie->addChild(SubprogramDie); 1790 } 1791 1792 // Expose as global. 1793 ModuleCU->addGlobal(SP.getName(), SubprogramDie); 1794 1795 return; 1796} 1797 1798/// beginModule - Emit all Dwarf sections that should come prior to the 1799/// content. Create global DIEs and emit initial debug info sections. 1800/// This is inovked by the target AsmPrinter. 1801void DwarfDebug::beginModule(Module *M, MachineModuleInfo *mmi) { 1802 this->M = M; 1803 1804 if (TimePassesIsEnabled) 1805 DebugTimer->startTimer(); 1806 1807 if (!MAI->doesSupportDebugInformation()) 1808 return; 1809 1810 DebugInfoFinder DbgFinder; 1811 DbgFinder.processModule(*M); 1812 1813 // Create all the compile unit DIEs. 1814 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(), 1815 E = DbgFinder.compile_unit_end(); I != E; ++I) 1816 constructCompileUnit(*I); 1817 1818 if (CompileUnits.empty()) { 1819 if (TimePassesIsEnabled) 1820 DebugTimer->stopTimer(); 1821 1822 return; 1823 } 1824 1825 // If main compile unit for this module is not seen than randomly 1826 // select first compile unit. 1827 if (!ModuleCU) 1828 ModuleCU = CompileUnits[0]; 1829 1830 // Create DIEs for each of the externally visible global variables. 1831 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(), 1832 E = DbgFinder.global_variable_end(); I != E; ++I) { 1833 DIGlobalVariable GV(*I); 1834 DIDescriptor GVContext = GV.getContext(); 1835 if (GVContext.isCompileUnit() 1836 && GVContext.getNode() == GV.getCompileUnit().getNode()) 1837 constructGlobalVariableDIE(*I); 1838 else if (GVContext.isNameSpace()) { 1839 DIE *GVDie = createGlobalVariableDIE(ModuleCU, GV); 1840 DINameSpace NS(GVContext.getNode()); 1841 DIE *NDie = getOrCreateNameSpace(NS); 1842 NDie->addChild(GVDie); 1843 } 1844 else 1845 ScopedGVs.push_back(*I); 1846 } 1847 1848 // Create DIEs for each subprogram. 1849 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(), 1850 E = DbgFinder.subprogram_end(); I != E; ++I) 1851 constructSubprogramDIE(*I); 1852 1853 MMI = mmi; 1854 shouldEmit = true; 1855 MMI->setDebugInfoAvailability(true); 1856 1857 // Prime section data. 1858 SectionMap.insert(Asm->getObjFileLowering().getTextSection()); 1859 1860 // Print out .file directives to specify files for .loc directives. These are 1861 // printed out early so that they precede any .loc directives. 1862 if (MAI->hasDotLocAndDotFile()) { 1863 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) { 1864 // Remember source id starts at 1. 1865 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i); 1866 sys::Path FullPath(getSourceDirectoryName(Id.first)); 1867 bool AppendOk = 1868 FullPath.appendComponent(getSourceFileName(Id.second)); 1869 assert(AppendOk && "Could not append filename to directory!"); 1870 AppendOk = false; 1871 Asm->EmitFile(i, FullPath.str()); 1872 Asm->EOL(); 1873 } 1874 } 1875 1876 // Emit initial sections 1877 emitInitial(); 1878 1879 if (TimePassesIsEnabled) 1880 DebugTimer->stopTimer(); 1881} 1882 1883/// endModule - Emit all Dwarf sections that should come after the content. 1884/// 1885void DwarfDebug::endModule() { 1886 if (!ModuleCU) 1887 return; 1888 1889 if (TimePassesIsEnabled) 1890 DebugTimer->startTimer(); 1891 1892 // Attach DW_AT_inline attribute with inlined subprogram DIEs. 1893 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(), 1894 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) { 1895 DIE *ISP = *AI; 1896 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined); 1897 } 1898 1899 // Insert top level DIEs. 1900 for (SmallVector<DIE *, 4>::iterator TI = TopLevelDIEsVector.begin(), 1901 TE = TopLevelDIEsVector.end(); TI != TE; ++TI) 1902 ModuleCU->getCUDie()->addChild(*TI); 1903 1904 for (DenseMap<DIE *, WeakVH>::iterator CI = ContainingTypeMap.begin(), 1905 CE = ContainingTypeMap.end(); CI != CE; ++CI) { 1906 DIE *SPDie = CI->first; 1907 MDNode *N = dyn_cast_or_null<MDNode>(CI->second); 1908 if (!N) continue; 1909 DIE *NDie = ModuleCU->getDIE(N); 1910 if (!NDie) continue; 1911 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie); 1912 addDIEEntry(NDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie); 1913 } 1914 1915 // Standard sections final addresses. 1916 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection()); 1917 EmitLabel("text_end", 0); 1918 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection()); 1919 EmitLabel("data_end", 0); 1920 1921 // End text sections. 1922 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) { 1923 Asm->OutStreamer.SwitchSection(SectionMap[i]); 1924 EmitLabel("section_end", i); 1925 } 1926 1927 // Emit common frame information. 1928 emitCommonDebugFrame(); 1929 1930 // Emit function debug frame information 1931 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(), 1932 E = DebugFrames.end(); I != E; ++I) 1933 emitFunctionDebugFrame(*I); 1934 1935 // Compute DIE offsets and sizes. 1936 computeSizeAndOffsets(); 1937 1938 // Emit all the DIEs into a debug info section 1939 emitDebugInfo(); 1940 1941 // Corresponding abbreviations into a abbrev section. 1942 emitAbbreviations(); 1943 1944 // Emit source line correspondence into a debug line section. 1945 emitDebugLines(); 1946 1947 // Emit info into a debug pubnames section. 1948 emitDebugPubNames(); 1949 1950 // Emit info into a debug pubtypes section. 1951 emitDebugPubTypes(); 1952 1953 // Emit info into a debug str section. 1954 emitDebugStr(); 1955 1956 // Emit info into a debug loc section. 1957 emitDebugLoc(); 1958 1959 // Emit info into a debug aranges section. 1960 EmitDebugARanges(); 1961 1962 // Emit info into a debug ranges section. 1963 emitDebugRanges(); 1964 1965 // Emit info into a debug macinfo section. 1966 emitDebugMacInfo(); 1967 1968 // Emit inline info. 1969 emitDebugInlineInfo(); 1970 1971 if (TimePassesIsEnabled) 1972 DebugTimer->stopTimer(); 1973} 1974 1975/// findAbstractVariable - Find abstract variable, if any, associated with Var. 1976DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var, 1977 unsigned FrameIdx, 1978 DILocation &ScopeLoc) { 1979 1980 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode()); 1981 if (AbsDbgVariable) 1982 return AbsDbgVariable; 1983 1984 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope().getNode()); 1985 if (!Scope) 1986 return NULL; 1987 1988 AbsDbgVariable = new DbgVariable(Var, FrameIdx); 1989 Scope->addVariable(AbsDbgVariable); 1990 AbstractVariables[Var.getNode()] = AbsDbgVariable; 1991 return AbsDbgVariable; 1992} 1993 1994/// collectVariableInfo - Populate DbgScope entries with variables' info. 1995void DwarfDebug::collectVariableInfo() { 1996 if (!MMI) return; 1997 1998 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo(); 1999 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(), 2000 VE = VMap.end(); VI != VE; ++VI) { 2001 MetadataBase *MB = VI->first; 2002 MDNode *Var = dyn_cast_or_null<MDNode>(MB); 2003 if (!Var) continue; 2004 DIVariable DV (Var); 2005 std::pair< unsigned, MDNode *> VP = VI->second; 2006 DILocation ScopeLoc(VP.second); 2007 2008 DbgScope *Scope = 2009 ConcreteScopes.lookup(ScopeLoc.getOrigLocation().getNode()); 2010 if (!Scope) 2011 Scope = DbgScopeMap.lookup(ScopeLoc.getScope().getNode()); 2012 // If variable scope is not found then skip this variable. 2013 if (!Scope) 2014 continue; 2015 2016 DbgVariable *RegVar = new DbgVariable(DV, VP.first); 2017 Scope->addVariable(RegVar); 2018 if (DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first, 2019 ScopeLoc)) 2020 RegVar->setAbstractVariable(AbsDbgVariable); 2021 } 2022} 2023 2024/// beginScope - Process beginning of a scope starting at Label. 2025void DwarfDebug::beginScope(const MachineInstr *MI, unsigned Label) { 2026 InsnToDbgScopeMapTy::iterator I = DbgScopeBeginMap.find(MI); 2027 if (I == DbgScopeBeginMap.end()) 2028 return; 2029 ScopeVector &SD = I->second; 2030 for (ScopeVector::iterator SDI = SD.begin(), SDE = SD.end(); 2031 SDI != SDE; ++SDI) 2032 (*SDI)->setStartLabelID(Label); 2033} 2034 2035/// endScope - Process end of a scope. 2036void DwarfDebug::endScope(const MachineInstr *MI) { 2037 InsnToDbgScopeMapTy::iterator I = DbgScopeEndMap.find(MI); 2038 if (I == DbgScopeEndMap.end()) 2039 return; 2040 2041 unsigned Label = MMI->NextLabelID(); 2042 Asm->printLabel(Label); 2043 O << '\n'; 2044 2045 SmallVector<DbgScope *, 2> &SD = I->second; 2046 for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end(); 2047 SDI != SDE; ++SDI) 2048 (*SDI)->setEndLabelID(Label); 2049 return; 2050} 2051 2052/// createDbgScope - Create DbgScope for the scope. 2053void DwarfDebug::createDbgScope(MDNode *Scope, MDNode *InlinedAt) { 2054 2055 if (!InlinedAt) { 2056 DbgScope *WScope = DbgScopeMap.lookup(Scope); 2057 if (WScope) 2058 return; 2059 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL); 2060 DbgScopeMap.insert(std::make_pair(Scope, WScope)); 2061 if (DIDescriptor(Scope).isLexicalBlock()) 2062 createDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL); 2063 return; 2064 } 2065 2066 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt); 2067 if (WScope) 2068 return; 2069 2070 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt); 2071 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope)); 2072 DILocation DL(InlinedAt); 2073 createDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode()); 2074} 2075 2076/// extractScopeInformation - Scan machine instructions in this function 2077/// and collect DbgScopes. Return true, if atleast one scope was found. 2078bool DwarfDebug::extractScopeInformation(MachineFunction *MF) { 2079 // If scope information was extracted using .dbg intrinsics then there is not 2080 // any need to extract these information by scanning each instruction. 2081 if (!DbgScopeMap.empty()) 2082 return false; 2083 2084 // Scan each instruction and create scopes. First build working set of scopes. 2085 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); 2086 I != E; ++I) { 2087 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end(); 2088 II != IE; ++II) { 2089 const MachineInstr *MInsn = II; 2090 DebugLoc DL = MInsn->getDebugLoc(); 2091 if (DL.isUnknown()) continue; 2092 DebugLocTuple DLT = MF->getDebugLocTuple(DL); 2093 if (!DLT.Scope) continue; 2094 // There is no need to create another DIE for compile unit. For all 2095 // other scopes, create one DbgScope now. This will be translated 2096 // into a scope DIE at the end. 2097 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue; 2098 createDbgScope(DLT.Scope, DLT.InlinedAtLoc); 2099 } 2100 } 2101 2102 2103 // Build scope hierarchy using working set of scopes. 2104 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); 2105 I != E; ++I) { 2106 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end(); 2107 II != IE; ++II) { 2108 const MachineInstr *MInsn = II; 2109 DebugLoc DL = MInsn->getDebugLoc(); 2110 if (DL.isUnknown()) continue; 2111 DebugLocTuple DLT = MF->getDebugLocTuple(DL); 2112 if (!DLT.Scope) continue; 2113 // There is no need to create another DIE for compile unit. For all 2114 // other scopes, create one DbgScope now. This will be translated 2115 // into a scope DIE at the end. 2116 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue; 2117 DbgScope *Scope = getUpdatedDbgScope(DLT.Scope, MInsn, DLT.InlinedAtLoc); 2118 Scope->setLastInsn(MInsn); 2119 } 2120 } 2121 2122 // If a scope's last instruction is not set then use its child scope's 2123 // last instruction as this scope's last instrunction. 2124 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(), 2125 DE = DbgScopeMap.end(); DI != DE; ++DI) { 2126 if (DI->second->isAbstractScope()) 2127 continue; 2128 assert (DI->second->getFirstInsn() && "Invalid first instruction!"); 2129 DI->second->fixInstructionMarkers(); 2130 assert (DI->second->getLastInsn() && "Invalid last instruction!"); 2131 } 2132 2133 // Each scope has first instruction and last instruction to mark beginning 2134 // and end of a scope respectively. Create an inverse map that list scopes 2135 // starts (and ends) with an instruction. One instruction may start (or end) 2136 // multiple scopes. 2137 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(), 2138 DE = DbgScopeMap.end(); DI != DE; ++DI) { 2139 DbgScope *S = DI->second; 2140 if (S->isAbstractScope()) 2141 continue; 2142 const MachineInstr *MI = S->getFirstInsn(); 2143 assert (MI && "DbgScope does not have first instruction!"); 2144 2145 InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI); 2146 if (IDI != DbgScopeBeginMap.end()) 2147 IDI->second.push_back(S); 2148 else 2149 DbgScopeBeginMap[MI].push_back(S); 2150 2151 MI = S->getLastInsn(); 2152 assert (MI && "DbgScope does not have last instruction!"); 2153 IDI = DbgScopeEndMap.find(MI); 2154 if (IDI != DbgScopeEndMap.end()) 2155 IDI->second.push_back(S); 2156 else 2157 DbgScopeEndMap[MI].push_back(S); 2158 } 2159 2160 return !DbgScopeMap.empty(); 2161} 2162 2163/// beginFunction - Gather pre-function debug information. Assumes being 2164/// emitted immediately after the function entry point. 2165void DwarfDebug::beginFunction(MachineFunction *MF) { 2166 this->MF = MF; 2167 2168 if (!ShouldEmitDwarfDebug()) return; 2169 2170 if (TimePassesIsEnabled) 2171 DebugTimer->startTimer(); 2172 2173 if (!extractScopeInformation(MF)) 2174 return; 2175 2176 collectVariableInfo(); 2177 2178 // Begin accumulating function debug information. 2179 MMI->BeginFunction(MF); 2180 2181 // Assumes in correct section after the entry point. 2182 EmitLabel("func_begin", ++SubprogramCount); 2183 2184 // Emit label for the implicitly defined dbg.stoppoint at the start of the 2185 // function. 2186 DebugLoc FDL = MF->getDefaultDebugLoc(); 2187 if (!FDL.isUnknown()) { 2188 DebugLocTuple DLT = MF->getDebugLocTuple(FDL); 2189 unsigned LabelID = 0; 2190 DISubprogram SP = getDISubprogram(DLT.Scope); 2191 if (!SP.isNull()) 2192 LabelID = recordSourceLine(SP.getLineNumber(), 0, DLT.Scope); 2193 else 2194 LabelID = recordSourceLine(DLT.Line, DLT.Col, DLT.Scope); 2195 Asm->printLabel(LabelID); 2196 O << '\n'; 2197 } 2198 if (TimePassesIsEnabled) 2199 DebugTimer->stopTimer(); 2200} 2201 2202/// endFunction - Gather and emit post-function debug information. 2203/// 2204void DwarfDebug::endFunction(MachineFunction *MF) { 2205 if (!ShouldEmitDwarfDebug()) return; 2206 2207 if (TimePassesIsEnabled) 2208 DebugTimer->startTimer(); 2209 2210 if (DbgScopeMap.empty()) 2211 return; 2212 2213 // Define end label for subprogram. 2214 EmitLabel("func_end", SubprogramCount); 2215 2216 // Get function line info. 2217 if (!Lines.empty()) { 2218 // Get section line info. 2219 unsigned ID = SectionMap.insert(Asm->getCurrentSection()); 2220 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID); 2221 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1]; 2222 // Append the function info to section info. 2223 SectionLineInfos.insert(SectionLineInfos.end(), 2224 Lines.begin(), Lines.end()); 2225 } 2226 2227 // Construct abstract scopes. 2228 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(), 2229 AE = AbstractScopesList.end(); AI != AE; ++AI) 2230 constructScopeDIE(*AI); 2231 2232 constructScopeDIE(CurrentFnDbgScope); 2233 2234 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount, 2235 MMI->getFrameMoves())); 2236 2237 // Clear debug info 2238 CurrentFnDbgScope = NULL; 2239 DbgScopeMap.clear(); 2240 DbgScopeBeginMap.clear(); 2241 DbgScopeEndMap.clear(); 2242 ConcreteScopes.clear(); 2243 AbstractScopesList.clear(); 2244 2245 Lines.clear(); 2246 2247 if (TimePassesIsEnabled) 2248 DebugTimer->stopTimer(); 2249} 2250 2251/// recordSourceLine - Records location information and associates it with a 2252/// label. Returns a unique label ID used to generate a label and provide 2253/// correspondence to the source line list. 2254unsigned DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, 2255 MDNode *S) { 2256 if (!MMI) 2257 return 0; 2258 2259 if (TimePassesIsEnabled) 2260 DebugTimer->startTimer(); 2261 2262 StringRef Dir; 2263 StringRef Fn; 2264 2265 DIDescriptor Scope(S); 2266 if (Scope.isCompileUnit()) { 2267 DICompileUnit CU(S); 2268 Dir = CU.getDirectory(); 2269 Fn = CU.getFilename(); 2270 } else if (Scope.isSubprogram()) { 2271 DISubprogram SP(S); 2272 Dir = SP.getDirectory(); 2273 Fn = SP.getFilename(); 2274 } else if (Scope.isLexicalBlock()) { 2275 DILexicalBlock DB(S); 2276 Dir = DB.getDirectory(); 2277 Fn = DB.getFilename(); 2278 } else 2279 assert (0 && "Unexpected scope info"); 2280 2281 unsigned Src = GetOrCreateSourceID(Dir, Fn); 2282 unsigned ID = MMI->NextLabelID(); 2283 Lines.push_back(SrcLineInfo(Line, Col, Src, ID)); 2284 2285 if (TimePassesIsEnabled) 2286 DebugTimer->stopTimer(); 2287 2288 return ID; 2289} 2290 2291/// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be 2292/// timed. Look up the source id with the given directory and source file 2293/// names. If none currently exists, create a new id and insert it in the 2294/// SourceIds map. This can update DirectoryNames and SourceFileNames maps as 2295/// well. 2296unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName, 2297 const std::string &FileName) { 2298 if (TimePassesIsEnabled) 2299 DebugTimer->startTimer(); 2300 2301 unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str()); 2302 2303 if (TimePassesIsEnabled) 2304 DebugTimer->stopTimer(); 2305 2306 return SrcId; 2307} 2308 2309//===----------------------------------------------------------------------===// 2310// Emit Methods 2311//===----------------------------------------------------------------------===// 2312 2313/// computeSizeAndOffset - Compute the size and offset of a DIE. 2314/// 2315unsigned 2316DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) { 2317 // Get the children. 2318 const std::vector<DIE *> &Children = Die->getChildren(); 2319 2320 // If not last sibling and has children then add sibling offset attribute. 2321 if (!Last && !Children.empty()) Die->addSiblingOffset(); 2322 2323 // Record the abbreviation. 2324 assignAbbrevNumber(Die->getAbbrev()); 2325 2326 // Get the abbreviation for this DIE. 2327 unsigned AbbrevNumber = Die->getAbbrevNumber(); 2328 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1]; 2329 2330 // Set DIE offset 2331 Die->setOffset(Offset); 2332 2333 // Start the size with the size of abbreviation code. 2334 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber); 2335 2336 const SmallVector<DIEValue*, 32> &Values = Die->getValues(); 2337 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData(); 2338 2339 // Size the DIE attribute values. 2340 for (unsigned i = 0, N = Values.size(); i < N; ++i) 2341 // Size attribute value. 2342 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm()); 2343 2344 // Size the DIE children if any. 2345 if (!Children.empty()) { 2346 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes && 2347 "Children flag not set"); 2348 2349 for (unsigned j = 0, M = Children.size(); j < M; ++j) 2350 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M); 2351 2352 // End of children marker. 2353 Offset += sizeof(int8_t); 2354 } 2355 2356 Die->setSize(Offset - Die->getOffset()); 2357 return Offset; 2358} 2359 2360/// computeSizeAndOffsets - Compute the size and offset of all the DIEs. 2361/// 2362void DwarfDebug::computeSizeAndOffsets() { 2363 // Compute size of compile unit header. 2364 static unsigned Offset = 2365 sizeof(int32_t) + // Length of Compilation Unit Info 2366 sizeof(int16_t) + // DWARF version number 2367 sizeof(int32_t) + // Offset Into Abbrev. Section 2368 sizeof(int8_t); // Pointer Size (in bytes) 2369 2370 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true); 2371 CompileUnitOffsets[ModuleCU] = 0; 2372} 2373 2374/// emitInitial - Emit initial Dwarf declarations. This is necessary for cc 2375/// tools to recognize the object file contains Dwarf information. 2376void DwarfDebug::emitInitial() { 2377 // Check to see if we already emitted intial headers. 2378 if (didInitial) return; 2379 didInitial = true; 2380 2381 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 2382 2383 // Dwarf sections base addresses. 2384 if (MAI->doesDwarfRequireFrameSection()) { 2385 Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection()); 2386 EmitLabel("section_debug_frame", 0); 2387 } 2388 2389 Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection()); 2390 EmitLabel("section_info", 0); 2391 Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection()); 2392 EmitLabel("section_abbrev", 0); 2393 Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection()); 2394 EmitLabel("section_aranges", 0); 2395 2396 if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) { 2397 Asm->OutStreamer.SwitchSection(LineInfoDirective); 2398 EmitLabel("section_macinfo", 0); 2399 } 2400 2401 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection()); 2402 EmitLabel("section_line", 0); 2403 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection()); 2404 EmitLabel("section_loc", 0); 2405 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection()); 2406 EmitLabel("section_pubnames", 0); 2407 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubTypesSection()); 2408 EmitLabel("section_pubtypes", 0); 2409 Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection()); 2410 EmitLabel("section_str", 0); 2411 Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection()); 2412 EmitLabel("section_ranges", 0); 2413 2414 Asm->OutStreamer.SwitchSection(TLOF.getTextSection()); 2415 EmitLabel("text_begin", 0); 2416 Asm->OutStreamer.SwitchSection(TLOF.getDataSection()); 2417 EmitLabel("data_begin", 0); 2418} 2419 2420/// emitDIE - Recusively Emits a debug information entry. 2421/// 2422void DwarfDebug::emitDIE(DIE *Die) { 2423 // Get the abbreviation for this DIE. 2424 unsigned AbbrevNumber = Die->getAbbrevNumber(); 2425 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1]; 2426 2427 Asm->EOL(); 2428 2429 // Emit the code (index) for the abbreviation. 2430 Asm->EmitULEB128Bytes(AbbrevNumber); 2431 2432 if (Asm->isVerbose()) 2433 Asm->EOL(std::string("Abbrev [" + 2434 utostr(AbbrevNumber) + 2435 "] 0x" + utohexstr(Die->getOffset()) + 2436 ":0x" + utohexstr(Die->getSize()) + " " + 2437 dwarf::TagString(Abbrev->getTag()))); 2438 else 2439 Asm->EOL(); 2440 2441 SmallVector<DIEValue*, 32> &Values = Die->getValues(); 2442 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData(); 2443 2444 // Emit the DIE attribute values. 2445 for (unsigned i = 0, N = Values.size(); i < N; ++i) { 2446 unsigned Attr = AbbrevData[i].getAttribute(); 2447 unsigned Form = AbbrevData[i].getForm(); 2448 assert(Form && "Too many attributes for DIE (check abbreviation)"); 2449 2450 switch (Attr) { 2451 case dwarf::DW_AT_sibling: 2452 Asm->EmitInt32(Die->getSiblingOffset()); 2453 break; 2454 case dwarf::DW_AT_abstract_origin: { 2455 DIEEntry *E = cast<DIEEntry>(Values[i]); 2456 DIE *Origin = E->getEntry(); 2457 unsigned Addr = Origin->getOffset(); 2458 Asm->EmitInt32(Addr); 2459 break; 2460 } 2461 default: 2462 // Emit an attribute using the defined form. 2463 Values[i]->EmitValue(this, Form); 2464 break; 2465 } 2466 2467 Asm->EOL(dwarf::AttributeString(Attr)); 2468 } 2469 2470 // Emit the DIE children if any. 2471 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) { 2472 const std::vector<DIE *> &Children = Die->getChildren(); 2473 2474 for (unsigned j = 0, M = Children.size(); j < M; ++j) 2475 emitDIE(Children[j]); 2476 2477 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark"); 2478 } 2479} 2480 2481/// emitDebugInfo / emitDebugInfoPerCU - Emit the debug info section. 2482/// 2483void DwarfDebug::emitDebugInfoPerCU(CompileUnit *Unit) { 2484 DIE *Die = Unit->getCUDie(); 2485 2486 // Emit the compile units header. 2487 EmitLabel("info_begin", Unit->getID()); 2488 2489 // Emit size of content not including length itself 2490 unsigned ContentSize = Die->getSize() + 2491 sizeof(int16_t) + // DWARF version number 2492 sizeof(int32_t) + // Offset Into Abbrev. Section 2493 sizeof(int8_t) + // Pointer Size (in bytes) 2494 sizeof(int32_t); // FIXME - extra pad for gdb bug. 2495 2496 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info"); 2497 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number"); 2498 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false); 2499 Asm->EOL("Offset Into Abbrev. Section"); 2500 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)"); 2501 2502 emitDIE(Die); 2503 // FIXME - extra padding for gdb bug. 2504 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB"); 2505 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB"); 2506 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB"); 2507 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB"); 2508 EmitLabel("info_end", Unit->getID()); 2509 2510 Asm->EOL(); 2511} 2512 2513void DwarfDebug::emitDebugInfo() { 2514 // Start debug info section. 2515 Asm->OutStreamer.SwitchSection( 2516 Asm->getObjFileLowering().getDwarfInfoSection()); 2517 2518 emitDebugInfoPerCU(ModuleCU); 2519} 2520 2521/// emitAbbreviations - Emit the abbreviation section. 2522/// 2523void DwarfDebug::emitAbbreviations() const { 2524 // Check to see if it is worth the effort. 2525 if (!Abbreviations.empty()) { 2526 // Start the debug abbrev section. 2527 Asm->OutStreamer.SwitchSection( 2528 Asm->getObjFileLowering().getDwarfAbbrevSection()); 2529 2530 EmitLabel("abbrev_begin", 0); 2531 2532 // For each abbrevation. 2533 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) { 2534 // Get abbreviation data 2535 const DIEAbbrev *Abbrev = Abbreviations[i]; 2536 2537 // Emit the abbrevations code (base 1 index.) 2538 Asm->EmitULEB128Bytes(Abbrev->getNumber()); 2539 Asm->EOL("Abbreviation Code"); 2540 2541 // Emit the abbreviations data. 2542 Abbrev->Emit(Asm); 2543 2544 Asm->EOL(); 2545 } 2546 2547 // Mark end of abbreviations. 2548 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)"); 2549 2550 EmitLabel("abbrev_end", 0); 2551 Asm->EOL(); 2552 } 2553} 2554 2555/// emitEndOfLineMatrix - Emit the last address of the section and the end of 2556/// the line matrix. 2557/// 2558void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) { 2559 // Define last address of section. 2560 Asm->EmitInt8(0); Asm->EOL("Extended Op"); 2561 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size"); 2562 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address"); 2563 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label"); 2564 2565 // Mark end of matrix. 2566 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence"); 2567 Asm->EmitULEB128Bytes(1); Asm->EOL(); 2568 Asm->EmitInt8(1); Asm->EOL(); 2569} 2570 2571/// emitDebugLines - Emit source line information. 2572/// 2573void DwarfDebug::emitDebugLines() { 2574 // If the target is using .loc/.file, the assembler will be emitting the 2575 // .debug_line table automatically. 2576 if (MAI->hasDotLocAndDotFile()) 2577 return; 2578 2579 // Minimum line delta, thus ranging from -10..(255-10). 2580 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1); 2581 // Maximum line delta, thus ranging from -10..(255-10). 2582 const int MaxLineDelta = 255 + MinLineDelta; 2583 2584 // Start the dwarf line section. 2585 Asm->OutStreamer.SwitchSection( 2586 Asm->getObjFileLowering().getDwarfLineSection()); 2587 2588 // Construct the section header. 2589 EmitDifference("line_end", 0, "line_begin", 0, true); 2590 Asm->EOL("Length of Source Line Info"); 2591 EmitLabel("line_begin", 0); 2592 2593 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number"); 2594 2595 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true); 2596 Asm->EOL("Prolog Length"); 2597 EmitLabel("line_prolog_begin", 0); 2598 2599 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length"); 2600 2601 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag"); 2602 2603 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)"); 2604 2605 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)"); 2606 2607 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base"); 2608 2609 // Line number standard opcode encodings argument count 2610 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count"); 2611 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count"); 2612 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count"); 2613 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count"); 2614 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count"); 2615 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count"); 2616 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count"); 2617 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count"); 2618 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count"); 2619 2620 // Emit directories. 2621 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) { 2622 Asm->EmitString(getSourceDirectoryName(DI)); 2623 Asm->EOL("Directory"); 2624 } 2625 2626 Asm->EmitInt8(0); Asm->EOL("End of directories"); 2627 2628 // Emit files. 2629 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) { 2630 // Remember source id starts at 1. 2631 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI); 2632 Asm->EmitString(getSourceFileName(Id.second)); 2633 Asm->EOL("Source"); 2634 Asm->EmitULEB128Bytes(Id.first); 2635 Asm->EOL("Directory #"); 2636 Asm->EmitULEB128Bytes(0); 2637 Asm->EOL("Mod date"); 2638 Asm->EmitULEB128Bytes(0); 2639 Asm->EOL("File size"); 2640 } 2641 2642 Asm->EmitInt8(0); Asm->EOL("End of files"); 2643 2644 EmitLabel("line_prolog_end", 0); 2645 2646 // A sequence for each text section. 2647 unsigned SecSrcLinesSize = SectionSourceLines.size(); 2648 2649 for (unsigned j = 0; j < SecSrcLinesSize; ++j) { 2650 // Isolate current sections line info. 2651 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j]; 2652 2653 /*if (Asm->isVerbose()) { 2654 const MCSection *S = SectionMap[j + 1]; 2655 O << '\t' << MAI->getCommentString() << " Section" 2656 << S->getName() << '\n'; 2657 }*/ 2658 Asm->EOL(); 2659 2660 // Dwarf assumes we start with first line of first source file. 2661 unsigned Source = 1; 2662 unsigned Line = 1; 2663 2664 // Construct rows of the address, source, line, column matrix. 2665 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) { 2666 const SrcLineInfo &LineInfo = LineInfos[i]; 2667 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID()); 2668 if (!LabelID) continue; 2669 2670 if (LineInfo.getLine() == 0) continue; 2671 2672 if (!Asm->isVerbose()) 2673 Asm->EOL(); 2674 else { 2675 std::pair<unsigned, unsigned> SourceID = 2676 getSourceDirectoryAndFileIds(LineInfo.getSourceID()); 2677 O << '\t' << MAI->getCommentString() << ' ' 2678 << getSourceDirectoryName(SourceID.first) << '/' 2679 << getSourceFileName(SourceID.second) 2680 << ':' << utostr_32(LineInfo.getLine()) << '\n'; 2681 } 2682 2683 // Define the line address. 2684 Asm->EmitInt8(0); Asm->EOL("Extended Op"); 2685 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size"); 2686 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address"); 2687 EmitReference("label", LabelID); Asm->EOL("Location label"); 2688 2689 // If change of source, then switch to the new source. 2690 if (Source != LineInfo.getSourceID()) { 2691 Source = LineInfo.getSourceID(); 2692 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file"); 2693 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source"); 2694 } 2695 2696 // If change of line. 2697 if (Line != LineInfo.getLine()) { 2698 // Determine offset. 2699 int Offset = LineInfo.getLine() - Line; 2700 int Delta = Offset - MinLineDelta; 2701 2702 // Update line. 2703 Line = LineInfo.getLine(); 2704 2705 // If delta is small enough and in range... 2706 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) { 2707 // ... then use fast opcode. 2708 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta"); 2709 } else { 2710 // ... otherwise use long hand. 2711 Asm->EmitInt8(dwarf::DW_LNS_advance_line); 2712 Asm->EOL("DW_LNS_advance_line"); 2713 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset"); 2714 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy"); 2715 } 2716 } else { 2717 // Copy the previous row (different address or source) 2718 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy"); 2719 } 2720 } 2721 2722 emitEndOfLineMatrix(j + 1); 2723 } 2724 2725 if (SecSrcLinesSize == 0) 2726 // Because we're emitting a debug_line section, we still need a line 2727 // table. The linker and friends expect it to exist. If there's nothing to 2728 // put into it, emit an empty table. 2729 emitEndOfLineMatrix(1); 2730 2731 EmitLabel("line_end", 0); 2732 Asm->EOL(); 2733} 2734 2735/// emitCommonDebugFrame - Emit common frame info into a debug frame section. 2736/// 2737void DwarfDebug::emitCommonDebugFrame() { 2738 if (!MAI->doesDwarfRequireFrameSection()) 2739 return; 2740 2741 int stackGrowth = 2742 Asm->TM.getFrameInfo()->getStackGrowthDirection() == 2743 TargetFrameInfo::StackGrowsUp ? 2744 TD->getPointerSize() : -TD->getPointerSize(); 2745 2746 // Start the dwarf frame section. 2747 Asm->OutStreamer.SwitchSection( 2748 Asm->getObjFileLowering().getDwarfFrameSection()); 2749 2750 EmitLabel("debug_frame_common", 0); 2751 EmitDifference("debug_frame_common_end", 0, 2752 "debug_frame_common_begin", 0, true); 2753 Asm->EOL("Length of Common Information Entry"); 2754 2755 EmitLabel("debug_frame_common_begin", 0); 2756 Asm->EmitInt32((int)dwarf::DW_CIE_ID); 2757 Asm->EOL("CIE Identifier Tag"); 2758 Asm->EmitInt8(dwarf::DW_CIE_VERSION); 2759 Asm->EOL("CIE Version"); 2760 Asm->EmitString(""); 2761 Asm->EOL("CIE Augmentation"); 2762 Asm->EmitULEB128Bytes(1); 2763 Asm->EOL("CIE Code Alignment Factor"); 2764 Asm->EmitSLEB128Bytes(stackGrowth); 2765 Asm->EOL("CIE Data Alignment Factor"); 2766 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false)); 2767 Asm->EOL("CIE RA Column"); 2768 2769 std::vector<MachineMove> Moves; 2770 RI->getInitialFrameState(Moves); 2771 2772 EmitFrameMoves(NULL, 0, Moves, false); 2773 2774 Asm->EmitAlignment(2, 0, 0, false); 2775 EmitLabel("debug_frame_common_end", 0); 2776 2777 Asm->EOL(); 2778} 2779 2780/// emitFunctionDebugFrame - Emit per function frame info into a debug frame 2781/// section. 2782void 2783DwarfDebug::emitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){ 2784 if (!MAI->doesDwarfRequireFrameSection()) 2785 return; 2786 2787 // Start the dwarf frame section. 2788 Asm->OutStreamer.SwitchSection( 2789 Asm->getObjFileLowering().getDwarfFrameSection()); 2790 2791 EmitDifference("debug_frame_end", DebugFrameInfo.Number, 2792 "debug_frame_begin", DebugFrameInfo.Number, true); 2793 Asm->EOL("Length of Frame Information Entry"); 2794 2795 EmitLabel("debug_frame_begin", DebugFrameInfo.Number); 2796 2797 EmitSectionOffset("debug_frame_common", "section_debug_frame", 2798 0, 0, true, false); 2799 Asm->EOL("FDE CIE offset"); 2800 2801 EmitReference("func_begin", DebugFrameInfo.Number); 2802 Asm->EOL("FDE initial location"); 2803 EmitDifference("func_end", DebugFrameInfo.Number, 2804 "func_begin", DebugFrameInfo.Number); 2805 Asm->EOL("FDE address range"); 2806 2807 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, 2808 false); 2809 2810 Asm->EmitAlignment(2, 0, 0, false); 2811 EmitLabel("debug_frame_end", DebugFrameInfo.Number); 2812 2813 Asm->EOL(); 2814} 2815 2816void DwarfDebug::emitDebugPubNamesPerCU(CompileUnit *Unit) { 2817 EmitDifference("pubnames_end", Unit->getID(), 2818 "pubnames_begin", Unit->getID(), true); 2819 Asm->EOL("Length of Public Names Info"); 2820 2821 EmitLabel("pubnames_begin", Unit->getID()); 2822 2823 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version"); 2824 2825 EmitSectionOffset("info_begin", "section_info", 2826 Unit->getID(), 0, true, false); 2827 Asm->EOL("Offset of Compilation Unit Info"); 2828 2829 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(), 2830 true); 2831 Asm->EOL("Compilation Unit Length"); 2832 2833 const StringMap<DIE*> &Globals = Unit->getGlobals(); 2834 for (StringMap<DIE*>::const_iterator 2835 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) { 2836 const char *Name = GI->getKeyData(); 2837 DIE * Entity = GI->second; 2838 2839 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset"); 2840 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name"); 2841 } 2842 2843 Asm->EmitInt32(0); Asm->EOL("End Mark"); 2844 EmitLabel("pubnames_end", Unit->getID()); 2845 2846 Asm->EOL(); 2847} 2848 2849/// emitDebugPubNames - Emit visible names into a debug pubnames section. 2850/// 2851void DwarfDebug::emitDebugPubNames() { 2852 // Start the dwarf pubnames section. 2853 Asm->OutStreamer.SwitchSection( 2854 Asm->getObjFileLowering().getDwarfPubNamesSection()); 2855 2856 emitDebugPubNamesPerCU(ModuleCU); 2857} 2858 2859void DwarfDebug::emitDebugPubTypes() { 2860 // Start the dwarf pubnames section. 2861 Asm->OutStreamer.SwitchSection( 2862 Asm->getObjFileLowering().getDwarfPubTypesSection()); 2863 EmitDifference("pubtypes_end", ModuleCU->getID(), 2864 "pubtypes_begin", ModuleCU->getID(), true); 2865 Asm->EOL("Length of Public Types Info"); 2866 2867 EmitLabel("pubtypes_begin", ModuleCU->getID()); 2868 2869 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version"); 2870 2871 EmitSectionOffset("info_begin", "section_info", 2872 ModuleCU->getID(), 0, true, false); 2873 Asm->EOL("Offset of Compilation ModuleCU Info"); 2874 2875 EmitDifference("info_end", ModuleCU->getID(), "info_begin", ModuleCU->getID(), 2876 true); 2877 Asm->EOL("Compilation ModuleCU Length"); 2878 2879 const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes(); 2880 for (StringMap<DIE*>::const_iterator 2881 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) { 2882 const char *Name = GI->getKeyData(); 2883 DIE * Entity = GI->second; 2884 2885 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset"); 2886 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name"); 2887 } 2888 2889 Asm->EmitInt32(0); Asm->EOL("End Mark"); 2890 EmitLabel("pubtypes_end", ModuleCU->getID()); 2891 2892 Asm->EOL(); 2893} 2894 2895/// emitDebugStr - Emit visible names into a debug str section. 2896/// 2897void DwarfDebug::emitDebugStr() { 2898 // Check to see if it is worth the effort. 2899 if (!StringPool.empty()) { 2900 // Start the dwarf str section. 2901 Asm->OutStreamer.SwitchSection( 2902 Asm->getObjFileLowering().getDwarfStrSection()); 2903 2904 // For each of strings in the string pool. 2905 for (unsigned StringID = 1, N = StringPool.size(); 2906 StringID <= N; ++StringID) { 2907 // Emit a label for reference from debug information entries. 2908 EmitLabel("string", StringID); 2909 2910 // Emit the string itself. 2911 const std::string &String = StringPool[StringID]; 2912 Asm->EmitString(String); Asm->EOL(); 2913 } 2914 2915 Asm->EOL(); 2916 } 2917} 2918 2919/// emitDebugLoc - Emit visible names into a debug loc section. 2920/// 2921void DwarfDebug::emitDebugLoc() { 2922 // Start the dwarf loc section. 2923 Asm->OutStreamer.SwitchSection( 2924 Asm->getObjFileLowering().getDwarfLocSection()); 2925 Asm->EOL(); 2926} 2927 2928/// EmitDebugARanges - Emit visible names into a debug aranges section. 2929/// 2930void DwarfDebug::EmitDebugARanges() { 2931 // Start the dwarf aranges section. 2932 Asm->OutStreamer.SwitchSection( 2933 Asm->getObjFileLowering().getDwarfARangesSection()); 2934 2935 // FIXME - Mock up 2936#if 0 2937 CompileUnit *Unit = GetBaseCompileUnit(); 2938 2939 // Don't include size of length 2940 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info"); 2941 2942 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version"); 2943 2944 EmitReference("info_begin", Unit->getID()); 2945 Asm->EOL("Offset of Compilation Unit Info"); 2946 2947 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address"); 2948 2949 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor"); 2950 2951 Asm->EmitInt16(0); Asm->EOL("Pad (1)"); 2952 Asm->EmitInt16(0); Asm->EOL("Pad (2)"); 2953 2954 // Range 1 2955 EmitReference("text_begin", 0); Asm->EOL("Address"); 2956 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length"); 2957 2958 Asm->EmitInt32(0); Asm->EOL("EOM (1)"); 2959 Asm->EmitInt32(0); Asm->EOL("EOM (2)"); 2960#endif 2961 2962 Asm->EOL(); 2963} 2964 2965/// emitDebugRanges - Emit visible names into a debug ranges section. 2966/// 2967void DwarfDebug::emitDebugRanges() { 2968 // Start the dwarf ranges section. 2969 Asm->OutStreamer.SwitchSection( 2970 Asm->getObjFileLowering().getDwarfRangesSection()); 2971 Asm->EOL(); 2972} 2973 2974/// emitDebugMacInfo - Emit visible names into a debug macinfo section. 2975/// 2976void DwarfDebug::emitDebugMacInfo() { 2977 if (const MCSection *LineInfo = 2978 Asm->getObjFileLowering().getDwarfMacroInfoSection()) { 2979 // Start the dwarf macinfo section. 2980 Asm->OutStreamer.SwitchSection(LineInfo); 2981 Asm->EOL(); 2982 } 2983} 2984 2985/// emitDebugInlineInfo - Emit inline info using following format. 2986/// Section Header: 2987/// 1. length of section 2988/// 2. Dwarf version number 2989/// 3. address size. 2990/// 2991/// Entries (one "entry" for each function that was inlined): 2992/// 2993/// 1. offset into __debug_str section for MIPS linkage name, if exists; 2994/// otherwise offset into __debug_str for regular function name. 2995/// 2. offset into __debug_str section for regular function name. 2996/// 3. an unsigned LEB128 number indicating the number of distinct inlining 2997/// instances for the function. 2998/// 2999/// The rest of the entry consists of a {die_offset, low_pc} pair for each 3000/// inlined instance; the die_offset points to the inlined_subroutine die in the 3001/// __debug_info section, and the low_pc is the starting address for the 3002/// inlining instance. 3003void DwarfDebug::emitDebugInlineInfo() { 3004 if (!MAI->doesDwarfUsesInlineInfoSection()) 3005 return; 3006 3007 if (!ModuleCU) 3008 return; 3009 3010 Asm->OutStreamer.SwitchSection( 3011 Asm->getObjFileLowering().getDwarfDebugInlineSection()); 3012 Asm->EOL(); 3013 EmitDifference("debug_inlined_end", 1, 3014 "debug_inlined_begin", 1, true); 3015 Asm->EOL("Length of Debug Inlined Information Entry"); 3016 3017 EmitLabel("debug_inlined_begin", 1); 3018 3019 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version"); 3020 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)"); 3021 3022 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(), 3023 E = InlinedSPNodes.end(); I != E; ++I) { 3024 3025// for (ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator 3026 // I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) { 3027 MDNode *Node = *I; 3028 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II 3029 = InlineInfo.find(Node); 3030 SmallVector<InlineInfoLabels, 4> &Labels = II->second; 3031 DISubprogram SP(Node); 3032 StringRef LName = SP.getLinkageName(); 3033 StringRef Name = SP.getName(); 3034 3035 if (LName.empty()) 3036 Asm->EmitString(Name); 3037 else { 3038 // Skip special LLVM prefix that is used to inform the asm printer to not 3039 // emit usual symbol prefix before the symbol name. This happens for 3040 // Objective-C symbol names and symbol whose name is replaced using GCC's 3041 // __asm__ attribute. 3042 if (LName[0] == 1) 3043 LName = LName.substr(1); 3044// Asm->EmitString(LName); 3045 EmitSectionOffset("string", "section_str", 3046 StringPool.idFor(LName), false, true); 3047 3048 } 3049 Asm->EOL("MIPS linkage name"); 3050// Asm->EmitString(Name); 3051 EmitSectionOffset("string", "section_str", 3052 StringPool.idFor(Name), false, true); 3053 Asm->EOL("Function name"); 3054 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count"); 3055 3056 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(), 3057 LE = Labels.end(); LI != LE; ++LI) { 3058 DIE *SP = LI->second; 3059 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset"); 3060 3061 if (TD->getPointerSize() == sizeof(int32_t)) 3062 O << MAI->getData32bitsDirective(); 3063 else 3064 O << MAI->getData64bitsDirective(); 3065 3066 PrintLabelName("label", LI->first); Asm->EOL("low_pc"); 3067 } 3068 } 3069 3070 EmitLabel("debug_inlined_end", 1); 3071 Asm->EOL(); 3072} 3073