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