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