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