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