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