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