DwarfDebug.cpp revision 75395847817b88798f9d8cdfb7bc99388167d291
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/// addRegisterAddress - Add register location entry in variable DIE. 816bool DwarfDebug::addRegisterAddress(DIE *Die, DbgVariable *DV, 817 const MachineOperand &MO) { 818 assert (MO.isReg() && "Invalid machine operand!"); 819 if (!MO.getReg()) 820 return false; 821 MachineLocation Location; 822 Location.set(MO.getReg()); 823 addAddress(Die, dwarf::DW_AT_location, Location); 824 if (MCSymbol *VS = DV->getDbgValueLabel()) 825 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS); 826 return true; 827} 828 829/// addConstantValue - Add constant value entry in variable DIE. 830bool DwarfDebug::addConstantValue(DIE *Die, DbgVariable *DV, 831 const MachineOperand &MO) { 832 assert (MO.isImm() && "Invalid machine operand!"); 833 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 834 unsigned Imm = MO.getImm(); 835 addUInt(Block, 0, dwarf::DW_FORM_udata, Imm); 836 addBlock(Die, dwarf::DW_AT_const_value, 0, Block); 837 if (MCSymbol *VS = DV->getDbgValueLabel()) 838 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS); 839 return true; 840} 841 842/// addConstantFPValue - Add constant value entry in variable DIE. 843bool DwarfDebug::addConstantFPValue(DIE *Die, DbgVariable *DV, 844 const MachineOperand &MO) { 845 assert (MO.isFPImm() && "Invalid machine operand!"); 846 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 847 APFloat FPImm = MO.getFPImm()->getValueAPF(); 848 849 // Get the raw data form of the floating point. 850 const APInt FltVal = FPImm.bitcastToAPInt(); 851 const char *FltPtr = (const char*)FltVal.getRawData(); 852 853 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte. 854 bool LittleEndian = Asm->getTargetData().isLittleEndian(); 855 int Incr = (LittleEndian ? 1 : -1); 856 int Start = (LittleEndian ? 0 : NumBytes - 1); 857 int Stop = (LittleEndian ? NumBytes : -1); 858 859 // Output the constant to DWARF one byte at a time. 860 for (; Start != Stop; Start += Incr) 861 addUInt(Block, 0, dwarf::DW_FORM_data1, 862 (unsigned char)0xFF & FltPtr[Start]); 863 864 addBlock(Die, dwarf::DW_AT_const_value, 0, Block); 865 866 if (MCSymbol *VS = DV->getDbgValueLabel()) 867 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, 868 VS); 869 return true; 870} 871 872 873/// addToContextOwner - Add Die into the list of its context owner's children. 874void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) { 875 if (Context.isType()) { 876 DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context.getNode())); 877 ContextDIE->addChild(Die); 878 } else if (Context.isNameSpace()) { 879 DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context.getNode())); 880 ContextDIE->addChild(Die); 881 } else if (DIE *ContextDIE = ModuleCU->getDIE(Context.getNode())) 882 ContextDIE->addChild(Die); 883 else 884 ModuleCU->addDie(Die); 885} 886 887/// getOrCreateTypeDIE - Find existing DIE or create new DIE for the 888/// given DIType. 889DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) { 890 DIE *TyDIE = ModuleCU->getDIE(Ty.getNode()); 891 if (TyDIE) 892 return TyDIE; 893 894 // Create new type. 895 TyDIE = new DIE(dwarf::DW_TAG_base_type); 896 ModuleCU->insertDIE(Ty.getNode(), TyDIE); 897 if (Ty.isBasicType()) 898 constructTypeDIE(*TyDIE, DIBasicType(Ty.getNode())); 899 else if (Ty.isCompositeType()) 900 constructTypeDIE(*TyDIE, DICompositeType(Ty.getNode())); 901 else { 902 assert(Ty.isDerivedType() && "Unknown kind of DIType"); 903 constructTypeDIE(*TyDIE, DIDerivedType(Ty.getNode())); 904 } 905 906 addToContextOwner(TyDIE, Ty.getContext()); 907 return TyDIE; 908} 909 910/// addType - Add a new type attribute to the specified entity. 911void DwarfDebug::addType(DIE *Entity, DIType Ty) { 912 if (!Ty.isValid()) 913 return; 914 915 // Check for pre-existence. 916 DIEEntry *Entry = ModuleCU->getDIEEntry(Ty.getNode()); 917 // If it exists then use the existing value. 918 if (Entry) { 919 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry); 920 return; 921 } 922 923 // Construct type. 924 DIE *Buffer = getOrCreateTypeDIE(Ty); 925 926 // Set up proxy. 927 Entry = createDIEEntry(Buffer); 928 ModuleCU->insertDIEEntry(Ty.getNode(), Entry); 929 930 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry); 931} 932 933/// constructTypeDIE - Construct basic type die from DIBasicType. 934void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) { 935 // Get core information. 936 StringRef Name = BTy.getName(); 937 Buffer.setTag(dwarf::DW_TAG_base_type); 938 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, 939 BTy.getEncoding()); 940 941 // Add name if not anonymous or intermediate type. 942 if (!Name.empty()) 943 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name); 944 uint64_t Size = BTy.getSizeInBits() >> 3; 945 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size); 946} 947 948/// constructTypeDIE - Construct derived type die from DIDerivedType. 949void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) { 950 // Get core information. 951 StringRef Name = DTy.getName(); 952 uint64_t Size = DTy.getSizeInBits() >> 3; 953 unsigned Tag = DTy.getTag(); 954 955 // FIXME - Workaround for templates. 956 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type; 957 958 Buffer.setTag(Tag); 959 960 // Map to main type, void will not have a type. 961 DIType FromTy = DTy.getTypeDerivedFrom(); 962 addType(&Buffer, FromTy); 963 964 // Add name if not anonymous or intermediate type. 965 if (!Name.empty()) 966 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name); 967 968 // Add size if non-zero (derived types might be zero-sized.) 969 if (Size) 970 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size); 971 972 // Add source line info if available and TyDesc is not a forward declaration. 973 if (!DTy.isForwardDecl()) 974 addSourceLine(&Buffer, &DTy); 975} 976 977/// constructTypeDIE - Construct type DIE from DICompositeType. 978void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) { 979 // Get core information. 980 StringRef Name = CTy.getName(); 981 982 uint64_t Size = CTy.getSizeInBits() >> 3; 983 unsigned Tag = CTy.getTag(); 984 Buffer.setTag(Tag); 985 986 switch (Tag) { 987 case dwarf::DW_TAG_vector_type: 988 case dwarf::DW_TAG_array_type: 989 constructArrayTypeDIE(Buffer, &CTy); 990 break; 991 case dwarf::DW_TAG_enumeration_type: { 992 DIArray Elements = CTy.getTypeArray(); 993 994 // Add enumerators to enumeration type. 995 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) { 996 DIE *ElemDie = NULL; 997 DIDescriptor Enum(Elements.getElement(i).getNode()); 998 if (Enum.isEnumerator()) { 999 ElemDie = constructEnumTypeDIE(DIEnumerator(Enum.getNode())); 1000 Buffer.addChild(ElemDie); 1001 } 1002 } 1003 } 1004 break; 1005 case dwarf::DW_TAG_subroutine_type: { 1006 // Add return type. 1007 DIArray Elements = CTy.getTypeArray(); 1008 DIDescriptor RTy = Elements.getElement(0); 1009 addType(&Buffer, DIType(RTy.getNode())); 1010 1011 // Add prototype flag. 1012 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1); 1013 1014 // Add arguments. 1015 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) { 1016 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter); 1017 DIDescriptor Ty = Elements.getElement(i); 1018 addType(Arg, DIType(Ty.getNode())); 1019 Buffer.addChild(Arg); 1020 } 1021 } 1022 break; 1023 case dwarf::DW_TAG_structure_type: 1024 case dwarf::DW_TAG_union_type: 1025 case dwarf::DW_TAG_class_type: { 1026 // Add elements to structure type. 1027 DIArray Elements = CTy.getTypeArray(); 1028 1029 // A forward struct declared type may not have elements available. 1030 unsigned N = Elements.getNumElements(); 1031 if (N == 0) 1032 break; 1033 1034 // Add elements to structure type. 1035 for (unsigned i = 0; i < N; ++i) { 1036 DIDescriptor Element = Elements.getElement(i); 1037 DIE *ElemDie = NULL; 1038 if (Element.isSubprogram()) 1039 ElemDie = createSubprogramDIE(DISubprogram(Element.getNode())); 1040 else if (Element.isVariable()) { 1041 DIVariable DV(Element.getNode()); 1042 ElemDie = new DIE(dwarf::DW_TAG_variable); 1043 addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, 1044 DV.getName()); 1045 addType(ElemDie, DV.getType()); 1046 addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1); 1047 addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1); 1048 addSourceLine(ElemDie, &DV); 1049 } else if (Element.isDerivedType()) 1050 ElemDie = createMemberDIE(DIDerivedType(Element.getNode())); 1051 else 1052 continue; 1053 Buffer.addChild(ElemDie); 1054 } 1055 1056 if (CTy.isAppleBlockExtension()) 1057 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1); 1058 1059 unsigned RLang = CTy.getRunTimeLang(); 1060 if (RLang) 1061 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, 1062 dwarf::DW_FORM_data1, RLang); 1063 1064 DICompositeType ContainingType = CTy.getContainingType(); 1065 if (DIDescriptor(ContainingType.getNode()).isCompositeType()) 1066 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, 1067 getOrCreateTypeDIE(DIType(ContainingType.getNode()))); 1068 break; 1069 } 1070 default: 1071 break; 1072 } 1073 1074 // Add name if not anonymous or intermediate type. 1075 if (!Name.empty()) 1076 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name); 1077 1078 if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type || 1079 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) { 1080 // Add size if non-zero (derived types might be zero-sized.) 1081 if (Size) 1082 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size); 1083 else { 1084 // Add zero size if it is not a forward declaration. 1085 if (CTy.isForwardDecl()) 1086 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1); 1087 else 1088 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0); 1089 } 1090 1091 // Add source line info if available. 1092 if (!CTy.isForwardDecl()) 1093 addSourceLine(&Buffer, &CTy); 1094 } 1095} 1096 1097/// constructSubrangeDIE - Construct subrange DIE from DISubrange. 1098void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){ 1099 int64_t L = SR.getLo(); 1100 int64_t H = SR.getHi(); 1101 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type); 1102 1103 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy); 1104 if (L) 1105 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L); 1106 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H); 1107 1108 Buffer.addChild(DW_Subrange); 1109} 1110 1111/// constructArrayTypeDIE - Construct array type DIE from DICompositeType. 1112void DwarfDebug::constructArrayTypeDIE(DIE &Buffer, 1113 DICompositeType *CTy) { 1114 Buffer.setTag(dwarf::DW_TAG_array_type); 1115 if (CTy->getTag() == dwarf::DW_TAG_vector_type) 1116 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1); 1117 1118 // Emit derived type. 1119 addType(&Buffer, CTy->getTypeDerivedFrom()); 1120 DIArray Elements = CTy->getTypeArray(); 1121 1122 // Get an anonymous type for index type. 1123 DIE *IdxTy = ModuleCU->getIndexTyDie(); 1124 if (!IdxTy) { 1125 // Construct an anonymous type for index type. 1126 IdxTy = new DIE(dwarf::DW_TAG_base_type); 1127 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t)); 1128 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, 1129 dwarf::DW_ATE_signed); 1130 ModuleCU->addDie(IdxTy); 1131 ModuleCU->setIndexTyDie(IdxTy); 1132 } 1133 1134 // Add subranges to array type. 1135 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) { 1136 DIDescriptor Element = Elements.getElement(i); 1137 if (Element.getTag() == dwarf::DW_TAG_subrange_type) 1138 constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy); 1139 } 1140} 1141 1142/// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator. 1143DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) { 1144 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator); 1145 StringRef Name = ETy.getName(); 1146 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name); 1147 int64_t Value = ETy.getEnumValue(); 1148 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value); 1149 return Enumerator; 1150} 1151 1152/// getRealLinkageName - If special LLVM prefix that is used to inform the asm 1153/// printer to not emit usual symbol prefix before the symbol name is used then 1154/// return linkage name after skipping this special LLVM prefix. 1155static StringRef getRealLinkageName(StringRef LinkageName) { 1156 char One = '\1'; 1157 if (LinkageName.startswith(StringRef(&One, 1))) 1158 return LinkageName.substr(1); 1159 return LinkageName; 1160} 1161 1162/// createGlobalVariableDIE - Create new DIE using GV. 1163DIE *DwarfDebug::createGlobalVariableDIE(const DIGlobalVariable &GV) { 1164 // If the global variable was optmized out then no need to create debug info 1165 // entry. 1166 if (!GV.getGlobal()) return NULL; 1167 if (GV.getDisplayName().empty()) return NULL; 1168 1169 DIE *GVDie = new DIE(dwarf::DW_TAG_variable); 1170 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, 1171 GV.getDisplayName()); 1172 1173 StringRef LinkageName = GV.getLinkageName(); 1174 if (!LinkageName.empty()) 1175 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string, 1176 getRealLinkageName(LinkageName)); 1177 1178 addType(GVDie, GV.getType()); 1179 if (!GV.isLocalToUnit()) 1180 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1); 1181 addSourceLine(GVDie, &GV); 1182 1183 return GVDie; 1184} 1185 1186/// createMemberDIE - Create new member DIE. 1187DIE *DwarfDebug::createMemberDIE(const DIDerivedType &DT) { 1188 DIE *MemberDie = new DIE(DT.getTag()); 1189 StringRef Name = DT.getName(); 1190 if (!Name.empty()) 1191 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name); 1192 1193 addType(MemberDie, DT.getTypeDerivedFrom()); 1194 1195 addSourceLine(MemberDie, &DT); 1196 1197 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock(); 1198 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 1199 1200 uint64_t Size = DT.getSizeInBits(); 1201 uint64_t FieldSize = DT.getOriginalTypeSize(); 1202 1203 if (Size != FieldSize) { 1204 // Handle bitfield. 1205 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3); 1206 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits()); 1207 1208 uint64_t Offset = DT.getOffsetInBits(); 1209 uint64_t AlignMask = ~(DT.getAlignInBits() - 1); 1210 uint64_t HiMark = (Offset + FieldSize) & AlignMask; 1211 uint64_t FieldOffset = (HiMark - FieldSize); 1212 Offset -= FieldOffset; 1213 1214 // Maybe we need to work from the other end. 1215 if (Asm->getTargetData().isLittleEndian()) 1216 Offset = FieldSize - (Offset + Size); 1217 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset); 1218 1219 // Here WD_AT_data_member_location points to the anonymous 1220 // field that includes this bit field. 1221 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3); 1222 1223 } else 1224 // This is not a bitfield. 1225 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3); 1226 1227 if (DT.getTag() == dwarf::DW_TAG_inheritance 1228 && DT.isVirtual()) { 1229 1230 // For C++, virtual base classes are not at fixed offset. Use following 1231 // expression to extract appropriate offset from vtable. 1232 // BaseAddr = ObAddr + *((*ObAddr) - Offset) 1233 1234 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock(); 1235 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup); 1236 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 1237 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 1238 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits()); 1239 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus); 1240 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 1241 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus); 1242 1243 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, 1244 VBaseLocationDie); 1245 } else 1246 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie); 1247 1248 if (DT.isProtected()) 1249 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag, 1250 dwarf::DW_ACCESS_protected); 1251 else if (DT.isPrivate()) 1252 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag, 1253 dwarf::DW_ACCESS_private); 1254 else if (DT.getTag() == dwarf::DW_TAG_inheritance) 1255 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag, 1256 dwarf::DW_ACCESS_public); 1257 if (DT.isVirtual()) 1258 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, 1259 dwarf::DW_VIRTUALITY_virtual); 1260 return MemberDie; 1261} 1262 1263/// createSubprogramDIE - Create new DIE using SP. 1264DIE *DwarfDebug::createSubprogramDIE(const DISubprogram &SP, bool MakeDecl) { 1265 DIE *SPDie = ModuleCU->getDIE(SP.getNode()); 1266 if (SPDie) 1267 return SPDie; 1268 1269 SPDie = new DIE(dwarf::DW_TAG_subprogram); 1270 // Constructors and operators for anonymous aggregates do not have names. 1271 if (!SP.getName().empty()) 1272 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName()); 1273 1274 StringRef LinkageName = SP.getLinkageName(); 1275 if (!LinkageName.empty()) 1276 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string, 1277 getRealLinkageName(LinkageName)); 1278 1279 addSourceLine(SPDie, &SP); 1280 1281 // Add prototyped tag, if C or ObjC. 1282 unsigned Lang = SP.getCompileUnit().getLanguage(); 1283 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 || 1284 Lang == dwarf::DW_LANG_ObjC) 1285 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1); 1286 1287 // Add Return Type. 1288 DICompositeType SPTy = SP.getType(); 1289 DIArray Args = SPTy.getTypeArray(); 1290 unsigned SPTag = SPTy.getTag(); 1291 1292 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type) 1293 addType(SPDie, SPTy); 1294 else 1295 addType(SPDie, DIType(Args.getElement(0).getNode())); 1296 1297 unsigned VK = SP.getVirtuality(); 1298 if (VK) { 1299 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK); 1300 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 1301 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 1302 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex()); 1303 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block); 1304 ContainingTypeMap.insert(std::make_pair(SPDie, 1305 SP.getContainingType().getNode())); 1306 } 1307 1308 if (MakeDecl || !SP.isDefinition()) { 1309 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1); 1310 1311 // Add arguments. Do not add arguments for subprogram definition. They will 1312 // be handled while processing variables. 1313 DICompositeType SPTy = SP.getType(); 1314 DIArray Args = SPTy.getTypeArray(); 1315 unsigned SPTag = SPTy.getTag(); 1316 1317 if (SPTag == dwarf::DW_TAG_subroutine_type) 1318 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) { 1319 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter); 1320 DIType ATy = DIType(DIType(Args.getElement(i).getNode())); 1321 addType(Arg, ATy); 1322 if (ATy.isArtificial()) 1323 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); 1324 SPDie->addChild(Arg); 1325 } 1326 } 1327 1328 if (SP.isArtificial()) 1329 addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); 1330 1331 if (!SP.isLocalToUnit()) 1332 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1); 1333 1334 if (SP.isOptimized()) 1335 addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1); 1336 1337 // DW_TAG_inlined_subroutine may refer to this DIE. 1338 ModuleCU->insertDIE(SP.getNode(), SPDie); 1339 1340 return SPDie; 1341} 1342 1343DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) { 1344 assert(N && "Invalid Scope encoding!"); 1345 1346 DbgScope *AScope = AbstractScopes.lookup(N); 1347 if (AScope) 1348 return AScope; 1349 1350 DbgScope *Parent = NULL; 1351 1352 DIDescriptor Scope(N); 1353 if (Scope.isLexicalBlock()) { 1354 DILexicalBlock DB(N); 1355 DIDescriptor ParentDesc = DB.getContext(); 1356 Parent = getOrCreateAbstractScope(ParentDesc.getNode()); 1357 } 1358 1359 AScope = new DbgScope(Parent, DIDescriptor(N), NULL); 1360 1361 if (Parent) 1362 Parent->addScope(AScope); 1363 AScope->setAbstractScope(); 1364 AbstractScopes[N] = AScope; 1365 if (DIDescriptor(N).isSubprogram()) 1366 AbstractScopesList.push_back(AScope); 1367 return AScope; 1368} 1369 1370/// isSubprogramContext - Return true if Context is either a subprogram 1371/// or another context nested inside a subprogram. 1372static bool isSubprogramContext(MDNode *Context) { 1373 if (!Context) 1374 return false; 1375 DIDescriptor D(Context); 1376 if (D.isSubprogram()) 1377 return true; 1378 if (D.isType()) 1379 return isSubprogramContext(DIType(Context).getContext().getNode()); 1380 return false; 1381} 1382 1383/// updateSubprogramScopeDIE - Find DIE for the given subprogram and 1384/// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes. 1385/// If there are global variables in this scope then create and insert 1386/// DIEs for these variables. 1387DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) { 1388 DIE *SPDie = ModuleCU->getDIE(SPNode); 1389 assert(SPDie && "Unable to find subprogram DIE!"); 1390 DISubprogram SP(SPNode); 1391 1392 // There is not any need to generate specification DIE for a function 1393 // defined at compile unit level. If a function is defined inside another 1394 // function then gdb prefers the definition at top level and but does not 1395 // expect specification DIE in parent function. So avoid creating 1396 // specification DIE for a function defined inside a function. 1397 if (SP.isDefinition() && !SP.getContext().isCompileUnit() && 1398 !SP.getContext().isFile() && 1399 !isSubprogramContext(SP.getContext().getNode())) { 1400 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1); 1401 1402 // Add arguments. 1403 DICompositeType SPTy = SP.getType(); 1404 DIArray Args = SPTy.getTypeArray(); 1405 unsigned SPTag = SPTy.getTag(); 1406 if (SPTag == dwarf::DW_TAG_subroutine_type) 1407 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) { 1408 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter); 1409 DIType ATy = DIType(DIType(Args.getElement(i).getNode())); 1410 addType(Arg, ATy); 1411 if (ATy.isArtificial()) 1412 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); 1413 SPDie->addChild(Arg); 1414 } 1415 DIE *SPDeclDie = SPDie; 1416 SPDie = new DIE(dwarf::DW_TAG_subprogram); 1417 addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4, 1418 SPDeclDie); 1419 ModuleCU->addDie(SPDie); 1420 } 1421 1422 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 1423 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber())); 1424 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, 1425 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber())); 1426 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo(); 1427 MachineLocation Location(RI->getFrameRegister(*Asm->MF)); 1428 addAddress(SPDie, dwarf::DW_AT_frame_base, Location); 1429 1430 return SPDie; 1431} 1432 1433/// constructLexicalScope - Construct new DW_TAG_lexical_block 1434/// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels. 1435DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) { 1436 1437 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block); 1438 if (Scope->isAbstractScope()) 1439 return ScopeDIE; 1440 1441 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges(); 1442 if (Ranges.empty()) 1443 return 0; 1444 1445 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(); 1446 if (Ranges.size() > 1) { 1447 // .debug_range section has not been laid out yet. Emit offset in 1448 // .debug_range as a uint, size 4, for now. emitDIE will handle 1449 // DW_AT_ranges appropriately. 1450 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4, 1451 DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize()); 1452 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(), 1453 RE = Ranges.end(); RI != RE; ++RI) { 1454 DebugRangeSymbols.push_back(LabelsBeforeInsn.lookup(RI->first)); 1455 DebugRangeSymbols.push_back(LabelsAfterInsn.lookup(RI->second)); 1456 } 1457 DebugRangeSymbols.push_back(NULL); 1458 DebugRangeSymbols.push_back(NULL); 1459 return ScopeDIE; 1460 } 1461 1462 MCSymbol *Start = LabelsBeforeInsn.lookup(RI->first); 1463 MCSymbol *End = LabelsAfterInsn.lookup(RI->second); 1464 1465 if (Start == 0 || End == 0) return 0; 1466 1467 assert(Start->isDefined() && "Invalid starting label for an inlined scope!"); 1468 assert(End->isDefined() && "Invalid end label for an inlined scope!"); 1469 1470 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start); 1471 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End); 1472 1473 return ScopeDIE; 1474} 1475 1476/// constructInlinedScopeDIE - This scope represents inlined body of 1477/// a function. Construct DIE to represent this concrete inlined copy 1478/// of the function. 1479DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) { 1480 1481 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges(); 1482 assert (Ranges.empty() == false 1483 && "DbgScope does not have instruction markers!"); 1484 1485 // FIXME : .debug_inlined section specification does not clearly state how 1486 // to emit inlined scope that is split into multiple instruction ranges. 1487 // For now, use first instruction range and emit low_pc/high_pc pair and 1488 // corresponding .debug_inlined section entry for this pair. 1489 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(); 1490 MCSymbol *StartLabel = LabelsBeforeInsn.lookup(RI->first); 1491 MCSymbol *EndLabel = LabelsAfterInsn.lookup(RI->second); 1492 1493 if (StartLabel == 0 || EndLabel == 0) { 1494 assert (0 && "Unexpected Start and End labels for a inlined scope!"); 1495 return 0; 1496 } 1497 assert(StartLabel->isDefined() && 1498 "Invalid starting label for an inlined scope!"); 1499 assert(EndLabel->isDefined() && 1500 "Invalid end label for an inlined scope!"); 1501 1502 if (!Scope->getScopeNode()) 1503 return NULL; 1504 DIScope DS(Scope->getScopeNode()); 1505 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine); 1506 1507 DISubprogram InlinedSP = getDISubprogram(DS.getNode()); 1508 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode()); 1509 assert(OriginDIE && "Unable to find Origin DIE!"); 1510 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, 1511 dwarf::DW_FORM_ref4, OriginDIE); 1512 1513 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel); 1514 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel); 1515 1516 InlinedSubprogramDIEs.insert(OriginDIE); 1517 1518 // Track the start label for this inlined function. 1519 DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator 1520 I = InlineInfo.find(InlinedSP.getNode()); 1521 1522 if (I == InlineInfo.end()) { 1523 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartLabel, 1524 ScopeDIE)); 1525 InlinedSPNodes.push_back(InlinedSP.getNode()); 1526 } else 1527 I->second.push_back(std::make_pair(StartLabel, ScopeDIE)); 1528 1529 DILocation DL(Scope->getInlinedAt()); 1530 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID()); 1531 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber()); 1532 1533 return ScopeDIE; 1534} 1535 1536 1537/// constructVariableDIE - Construct a DIE for the given DbgVariable. 1538DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) { 1539 // Get the descriptor. 1540 const DIVariable &VD = DV->getVariable(); 1541 StringRef Name = VD.getName(); 1542 if (Name.empty()) 1543 return NULL; 1544 1545 // Translate tag to proper Dwarf tag. The result variable is dropped for 1546 // now. 1547 unsigned Tag; 1548 switch (VD.getTag()) { 1549 case dwarf::DW_TAG_return_variable: 1550 return NULL; 1551 case dwarf::DW_TAG_arg_variable: 1552 Tag = dwarf::DW_TAG_formal_parameter; 1553 break; 1554 case dwarf::DW_TAG_auto_variable: // fall thru 1555 default: 1556 Tag = dwarf::DW_TAG_variable; 1557 break; 1558 } 1559 1560 // Define variable debug information entry. 1561 DIE *VariableDie = new DIE(Tag); 1562 1563 1564 DIE *AbsDIE = NULL; 1565 if (DbgVariable *AV = DV->getAbstractVariable()) 1566 AbsDIE = AV->getDIE(); 1567 1568 if (AbsDIE) { 1569 DIScope DS(Scope->getScopeNode()); 1570 DISubprogram InlinedSP = getDISubprogram(DS.getNode()); 1571 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode()); 1572 (void) OriginSPDIE; 1573 assert(OriginSPDIE && "Unable to find Origin DIE for the SP!"); 1574 DIE *AbsDIE = DV->getAbstractVariable()->getDIE(); 1575 assert(AbsDIE && "Unable to find Origin DIE for the Variable!"); 1576 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, 1577 dwarf::DW_FORM_ref4, AbsDIE); 1578 } 1579 else { 1580 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name); 1581 addSourceLine(VariableDie, &VD); 1582 1583 // Add variable type. 1584 // FIXME: isBlockByrefVariable should be reformulated in terms of complex 1585 // addresses instead. 1586 if (VD.isBlockByrefVariable()) 1587 addType(VariableDie, getBlockByrefType(VD.getType(), Name)); 1588 else 1589 addType(VariableDie, VD.getType()); 1590 } 1591 1592 // Add variable address. 1593 if (!Scope->isAbstractScope()) { 1594 // Check if variable is described by DBG_VALUE instruction. 1595 if (const MachineInstr *DVInsn = DV->getDbgValue()) { 1596 bool updated = false; 1597 // FIXME : Handle getNumOperands != 3 1598 if (DVInsn->getNumOperands() == 3) { 1599 if (DVInsn->getOperand(0).isReg()) 1600 updated = addRegisterAddress(VariableDie, DV, DVInsn->getOperand(0)); 1601 else if (DVInsn->getOperand(0).isImm()) 1602 updated = addConstantValue(VariableDie, DV, DVInsn->getOperand(0)); 1603 else if (DVInsn->getOperand(0).isFPImm()) 1604 updated = addConstantFPValue(VariableDie, DV, DVInsn->getOperand(0)); 1605 } else { 1606 MachineLocation Location = Asm->getDebugValueLocation(DVInsn); 1607 if (Location.getReg()) { 1608 addAddress(VariableDie, dwarf::DW_AT_location, Location); 1609 if (MCSymbol *VS = DV->getDbgValueLabel()) 1610 addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, 1611 VS); 1612 updated = true; 1613 } 1614 } 1615 if (!updated) { 1616 // If variableDie is not updated then DBG_VALUE instruction does not 1617 // have valid variable info. 1618 delete VariableDie; 1619 return NULL; 1620 } 1621 } 1622 else { 1623 MachineLocation Location; 1624 unsigned FrameReg; 1625 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo(); 1626 int Offset = RI->getFrameIndexReference(*Asm->MF, DV->getFrameIndex(), 1627 FrameReg); 1628 Location.set(FrameReg, Offset); 1629 1630 if (VD.hasComplexAddress()) 1631 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location); 1632 else if (VD.isBlockByrefVariable()) 1633 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location); 1634 else 1635 addAddress(VariableDie, dwarf::DW_AT_location, Location); 1636 } 1637 } 1638 1639 if (Tag == dwarf::DW_TAG_formal_parameter && VD.getType().isArtificial()) 1640 addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); 1641 DV->setDIE(VariableDie); 1642 return VariableDie; 1643 1644} 1645 1646void DwarfDebug::addPubTypes(DISubprogram SP) { 1647 DICompositeType SPTy = SP.getType(); 1648 unsigned SPTag = SPTy.getTag(); 1649 if (SPTag != dwarf::DW_TAG_subroutine_type) 1650 return; 1651 1652 DIArray Args = SPTy.getTypeArray(); 1653 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) { 1654 DIType ATy(Args.getElement(i).getNode()); 1655 if (!ATy.isValid()) 1656 continue; 1657 DICompositeType CATy = getDICompositeType(ATy); 1658 if (DIDescriptor(CATy.getNode()).Verify() && !CATy.getName().empty() 1659 && !CATy.isForwardDecl()) { 1660 if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode())) 1661 ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry()); 1662 } 1663 } 1664} 1665 1666/// constructScopeDIE - Construct a DIE for this scope. 1667DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) { 1668 if (!Scope || !Scope->getScopeNode()) 1669 return NULL; 1670 1671 DIScope DS(Scope->getScopeNode()); 1672 DIE *ScopeDIE = NULL; 1673 if (Scope->getInlinedAt()) 1674 ScopeDIE = constructInlinedScopeDIE(Scope); 1675 else if (DS.isSubprogram()) { 1676 if (Scope->isAbstractScope()) 1677 ScopeDIE = ModuleCU->getDIE(DS.getNode()); 1678 else 1679 ScopeDIE = updateSubprogramScopeDIE(DS.getNode()); 1680 } 1681 else 1682 ScopeDIE = constructLexicalScopeDIE(Scope); 1683 if (!ScopeDIE) return NULL; 1684 1685 // Add variables to scope. 1686 const SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables(); 1687 for (unsigned i = 0, N = Variables.size(); i < N; ++i) { 1688 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope); 1689 if (VariableDIE) 1690 ScopeDIE->addChild(VariableDIE); 1691 } 1692 1693 // Add nested scopes. 1694 const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes(); 1695 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) { 1696 // Define the Scope debug information entry. 1697 DIE *NestedDIE = constructScopeDIE(Scopes[j]); 1698 if (NestedDIE) 1699 ScopeDIE->addChild(NestedDIE); 1700 } 1701 1702 if (DS.isSubprogram()) 1703 addPubTypes(DISubprogram(DS.getNode())); 1704 1705 return ScopeDIE; 1706} 1707 1708/// GetOrCreateSourceID - Look up the source id with the given directory and 1709/// source file names. If none currently exists, create a new id and insert it 1710/// in the SourceIds map. This can update DirectoryNames and SourceFileNames 1711/// maps as well. 1712unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName){ 1713 unsigned DId; 1714 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName); 1715 if (DI != DirectoryIdMap.end()) { 1716 DId = DI->getValue(); 1717 } else { 1718 DId = DirectoryNames.size() + 1; 1719 DirectoryIdMap[DirName] = DId; 1720 DirectoryNames.push_back(DirName); 1721 } 1722 1723 unsigned FId; 1724 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName); 1725 if (FI != SourceFileIdMap.end()) { 1726 FId = FI->getValue(); 1727 } else { 1728 FId = SourceFileNames.size() + 1; 1729 SourceFileIdMap[FileName] = FId; 1730 SourceFileNames.push_back(FileName); 1731 } 1732 1733 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI = 1734 SourceIdMap.find(std::make_pair(DId, FId)); 1735 if (SI != SourceIdMap.end()) 1736 return SI->second; 1737 1738 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0. 1739 SourceIdMap[std::make_pair(DId, FId)] = SrcId; 1740 SourceIds.push_back(std::make_pair(DId, FId)); 1741 1742 return SrcId; 1743} 1744 1745/// getOrCreateNameSpace - Create a DIE for DINameSpace. 1746DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) { 1747 DIE *NDie = ModuleCU->getDIE(NS.getNode()); 1748 if (NDie) 1749 return NDie; 1750 NDie = new DIE(dwarf::DW_TAG_namespace); 1751 ModuleCU->insertDIE(NS.getNode(), NDie); 1752 if (!NS.getName().empty()) 1753 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName()); 1754 addSourceLine(NDie, &NS); 1755 addToContextOwner(NDie, NS.getContext()); 1756 return NDie; 1757} 1758 1759void DwarfDebug::constructCompileUnit(MDNode *N) { 1760 DICompileUnit DIUnit(N); 1761 // Use first compile unit marked as isMain as the compile unit for this 1762 // module. 1763 if (ModuleCU || !DIUnit.isMain()) 1764 return; 1765 StringRef FN = DIUnit.getFilename(); 1766 StringRef Dir = DIUnit.getDirectory(); 1767 unsigned ID = GetOrCreateSourceID(Dir, FN); 1768 1769 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit); 1770 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string, 1771 DIUnit.getProducer()); 1772 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1, 1773 DIUnit.getLanguage()); 1774 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN); 1775 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This 1776 // simplifies debug range entries. 1777 addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_data4, 0); 1778 // DW_AT_stmt_list is a offset of line number information for this 1779 // compile unit in debug_line section. It is always zero when only one 1780 // compile unit is emitted in one object file. 1781 addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0); 1782 1783 if (!Dir.empty()) 1784 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir); 1785 if (DIUnit.isOptimized()) 1786 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1); 1787 1788 StringRef Flags = DIUnit.getFlags(); 1789 if (!Flags.empty()) 1790 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags); 1791 1792 unsigned RVer = DIUnit.getRunTimeVersion(); 1793 if (RVer) 1794 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers, 1795 dwarf::DW_FORM_data1, RVer); 1796 1797 assert(!ModuleCU && 1798 "ModuleCU assigned since the top of constructCompileUnit"); 1799 ModuleCU = new CompileUnit(ID, Die); 1800} 1801 1802void DwarfDebug::constructGlobalVariableDIE(MDNode *N) { 1803 DIGlobalVariable DI_GV(N); 1804 1805 // If debug information is malformed then ignore it. 1806 if (DI_GV.Verify() == false) 1807 return; 1808 1809 // Check for pre-existence. 1810 if (ModuleCU->getDIE(DI_GV.getNode())) 1811 return; 1812 1813 DIE *VariableDie = createGlobalVariableDIE(DI_GV); 1814 if (!VariableDie) 1815 return; 1816 1817 // Add to map. 1818 ModuleCU->insertDIE(N, VariableDie); 1819 1820 // Add to context owner. 1821 DIDescriptor GVContext = DI_GV.getContext(); 1822 // Do not create specification DIE if context is either compile unit 1823 // or a subprogram. 1824 if (DI_GV.isDefinition() && !GVContext.isCompileUnit() && 1825 !GVContext.isFile() && 1826 !isSubprogramContext(GVContext.getNode())) { 1827 // Create specification DIE. 1828 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable); 1829 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, 1830 dwarf::DW_FORM_ref4, VariableDie); 1831 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 1832 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr); 1833 addLabel(Block, 0, dwarf::DW_FORM_udata, 1834 Asm->Mang->getSymbol(DI_GV.getGlobal())); 1835 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block); 1836 addUInt(VariableDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1); 1837 ModuleCU->addDie(VariableSpecDIE); 1838 } else { 1839 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 1840 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr); 1841 addLabel(Block, 0, dwarf::DW_FORM_udata, 1842 Asm->Mang->getSymbol(DI_GV.getGlobal())); 1843 addBlock(VariableDie, dwarf::DW_AT_location, 0, Block); 1844 } 1845 addToContextOwner(VariableDie, GVContext); 1846 1847 // Expose as global. FIXME - need to check external flag. 1848 ModuleCU->addGlobal(DI_GV.getName(), VariableDie); 1849 1850 DIType GTy = DI_GV.getType(); 1851 if (GTy.isCompositeType() && !GTy.getName().empty() 1852 && !GTy.isForwardDecl()) { 1853 DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode()); 1854 assert(Entry && "Missing global type!"); 1855 ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry()); 1856 } 1857 return; 1858} 1859 1860void DwarfDebug::constructSubprogramDIE(MDNode *N) { 1861 DISubprogram SP(N); 1862 1863 // Check for pre-existence. 1864 if (ModuleCU->getDIE(N)) 1865 return; 1866 1867 if (!SP.isDefinition()) 1868 // This is a method declaration which will be handled while constructing 1869 // class type. 1870 return; 1871 1872 DIE *SubprogramDie = createSubprogramDIE(SP); 1873 1874 // Add to map. 1875 ModuleCU->insertDIE(N, SubprogramDie); 1876 1877 // Add to context owner. 1878 addToContextOwner(SubprogramDie, SP.getContext()); 1879 1880 // Expose as global. 1881 ModuleCU->addGlobal(SP.getName(), SubprogramDie); 1882 1883 return; 1884} 1885 1886/// beginModule - Emit all Dwarf sections that should come prior to the 1887/// content. Create global DIEs and emit initial debug info sections. 1888/// This is inovked by the target AsmPrinter. 1889void DwarfDebug::beginModule(Module *M) { 1890 if (DisableDebugInfoPrinting) 1891 return; 1892 1893 DebugInfoFinder DbgFinder; 1894 DbgFinder.processModule(*M); 1895 1896 bool HasDebugInfo = false; 1897 1898 // Scan all the compile-units to see if there are any marked as the main unit. 1899 // if not, we do not generate debug info. 1900 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(), 1901 E = DbgFinder.compile_unit_end(); I != E; ++I) { 1902 if (DICompileUnit(*I).isMain()) { 1903 HasDebugInfo = true; 1904 break; 1905 } 1906 } 1907 1908 if (!HasDebugInfo) return; 1909 1910 // Tell MMI that we have debug info. 1911 MMI->setDebugInfoAvailability(true); 1912 1913 // Emit initial sections. 1914 EmitSectionLabels(); 1915 1916 // Create all the compile unit DIEs. 1917 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(), 1918 E = DbgFinder.compile_unit_end(); I != E; ++I) 1919 constructCompileUnit(*I); 1920 1921 // Create DIEs for each subprogram. 1922 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(), 1923 E = DbgFinder.subprogram_end(); I != E; ++I) 1924 constructSubprogramDIE(*I); 1925 1926 // Create DIEs for each global variable. 1927 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(), 1928 E = DbgFinder.global_variable_end(); I != E; ++I) 1929 constructGlobalVariableDIE(*I); 1930 1931 // Prime section data. 1932 SectionMap.insert(Asm->getObjFileLowering().getTextSection()); 1933 1934 // Print out .file directives to specify files for .loc directives. These are 1935 // printed out early so that they precede any .loc directives. 1936 if (Asm->MAI->hasDotLocAndDotFile()) { 1937 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) { 1938 // Remember source id starts at 1. 1939 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i); 1940 // FIXME: don't use sys::path for this! This should not depend on the 1941 // host. 1942 sys::Path FullPath(getSourceDirectoryName(Id.first)); 1943 bool AppendOk = 1944 FullPath.appendComponent(getSourceFileName(Id.second)); 1945 assert(AppendOk && "Could not append filename to directory!"); 1946 AppendOk = false; 1947 Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str()); 1948 } 1949 } 1950} 1951 1952/// endModule - Emit all Dwarf sections that should come after the content. 1953/// 1954void DwarfDebug::endModule() { 1955 if (!ModuleCU) return; 1956 1957 // Attach DW_AT_inline attribute with inlined subprogram DIEs. 1958 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(), 1959 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) { 1960 DIE *ISP = *AI; 1961 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined); 1962 } 1963 1964 for (DenseMap<DIE *, MDNode *>::iterator CI = ContainingTypeMap.begin(), 1965 CE = ContainingTypeMap.end(); CI != CE; ++CI) { 1966 DIE *SPDie = CI->first; 1967 MDNode *N = dyn_cast_or_null<MDNode>(CI->second); 1968 if (!N) continue; 1969 DIE *NDie = ModuleCU->getDIE(N); 1970 if (!NDie) continue; 1971 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie); 1972 } 1973 1974 // Standard sections final addresses. 1975 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection()); 1976 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end")); 1977 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection()); 1978 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end")); 1979 1980 // End text sections. 1981 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) { 1982 Asm->OutStreamer.SwitchSection(SectionMap[i]); 1983 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i)); 1984 } 1985 1986 // Emit common frame information. 1987 emitCommonDebugFrame(); 1988 1989 // Emit function debug frame information 1990 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(), 1991 E = DebugFrames.end(); I != E; ++I) 1992 emitFunctionDebugFrame(*I); 1993 1994 // Compute DIE offsets and sizes. 1995 computeSizeAndOffsets(); 1996 1997 // Emit all the DIEs into a debug info section 1998 emitDebugInfo(); 1999 2000 // Corresponding abbreviations into a abbrev section. 2001 emitAbbreviations(); 2002 2003 // Emit source line correspondence into a debug line section. 2004 emitDebugLines(); 2005 2006 // Emit info into a debug pubnames section. 2007 emitDebugPubNames(); 2008 2009 // Emit info into a debug pubtypes section. 2010 emitDebugPubTypes(); 2011 2012 // Emit info into a debug loc section. 2013 emitDebugLoc(); 2014 2015 // Emit info into a debug aranges section. 2016 EmitDebugARanges(); 2017 2018 // Emit info into a debug ranges section. 2019 emitDebugRanges(); 2020 2021 // Emit info into a debug macinfo section. 2022 emitDebugMacInfo(); 2023 2024 // Emit inline info. 2025 emitDebugInlineInfo(); 2026 2027 // Emit info into a debug str section. 2028 emitDebugStr(); 2029 2030 delete ModuleCU; 2031 ModuleCU = NULL; // Reset for the next Module, if any. 2032} 2033 2034/// findAbstractVariable - Find abstract variable, if any, associated with Var. 2035DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var, 2036 unsigned FrameIdx, 2037 DebugLoc ScopeLoc) { 2038 2039 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode()); 2040 if (AbsDbgVariable) 2041 return AbsDbgVariable; 2042 2043 LLVMContext &Ctx = Var.getNode()->getContext(); 2044 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx)); 2045 if (!Scope) 2046 return NULL; 2047 2048 AbsDbgVariable = new DbgVariable(Var, FrameIdx, 2049 NULL /* No more-abstract variable*/); 2050 Scope->addVariable(AbsDbgVariable); 2051 AbstractVariables[Var.getNode()] = AbsDbgVariable; 2052 return AbsDbgVariable; 2053} 2054 2055/// findAbstractVariable - Find abstract variable, if any, associated with Var. 2056/// FIXME : Refactor findAbstractVariable. 2057DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var, 2058 const MachineInstr *MI, 2059 DebugLoc ScopeLoc) { 2060 2061 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode()); 2062 if (AbsDbgVariable) 2063 return AbsDbgVariable; 2064 2065 LLVMContext &Ctx = Var.getNode()->getContext(); 2066 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx)); 2067 if (!Scope) 2068 return NULL; 2069 2070 AbsDbgVariable = new DbgVariable(Var, MI, 2071 NULL /* No more-abstract variable*/); 2072 Scope->addVariable(AbsDbgVariable); 2073 AbstractVariables[Var.getNode()] = AbsDbgVariable; 2074 DbgValueStartMap[MI] = AbsDbgVariable; 2075 return AbsDbgVariable; 2076} 2077 2078/// collectVariableInfo - Populate DbgScope entries with variables' info. 2079void DwarfDebug::collectVariableInfo() { 2080 const LLVMContext &Ctx = Asm->MF->getFunction()->getContext(); 2081 2082 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo(); 2083 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(), 2084 VE = VMap.end(); VI != VE; ++VI) { 2085 MDNode *Var = VI->first; 2086 if (!Var) continue; 2087 DIVariable DV(Var); 2088 const std::pair<unsigned, DebugLoc> &VP = VI->second; 2089 2090 DbgScope *Scope = 0; 2091 if (MDNode *IA = VP.second.getInlinedAt(Ctx)) 2092 Scope = ConcreteScopes.lookup(IA); 2093 if (Scope == 0) 2094 Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx)); 2095 2096 // If variable scope is not found then skip this variable. 2097 if (Scope == 0) 2098 continue; 2099 2100 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first, VP.second); 2101 DbgVariable *RegVar = new DbgVariable(DV, VP.first, AbsDbgVariable); 2102 Scope->addVariable(RegVar); 2103 } 2104 2105 // Collect variable information from DBG_VALUE machine instructions; 2106 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end(); 2107 I != E; ++I) { 2108 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end(); 2109 II != IE; ++II) { 2110 const MachineInstr *MInsn = II; 2111 if (!MInsn->isDebugValue()) 2112 continue; 2113 2114 // Ignore Undef values. 2115 if (MInsn->getOperand(0).isReg() && !MInsn->getOperand(0).getReg()) 2116 continue; 2117 2118 DIVariable DV( 2119 const_cast<MDNode *>(MInsn->getOperand(MInsn->getNumOperands() - 1) 2120 .getMetadata())); 2121 if (DV.getTag() == dwarf::DW_TAG_arg_variable) { 2122 // FIXME Handle inlined subroutine arguments. 2123 DbgVariable *ArgVar = new DbgVariable(DV, MInsn, NULL); 2124 CurrentFnDbgScope->addVariable(ArgVar); 2125 DbgValueStartMap[MInsn] = ArgVar; 2126 continue; 2127 } 2128 2129 DebugLoc DL = MInsn->getDebugLoc(); 2130 if (DL.isUnknown()) continue; 2131 DbgScope *Scope = 0; 2132 if (MDNode *IA = DL.getInlinedAt(Ctx)) 2133 Scope = ConcreteScopes.lookup(IA); 2134 if (Scope == 0) 2135 Scope = DbgScopeMap.lookup(DL.getScope(Ctx)); 2136 2137 // If variable scope is not found then skip this variable. 2138 if (Scope == 0) 2139 continue; 2140 2141 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, MInsn, DL); 2142 DbgVariable *RegVar = new DbgVariable(DV, MInsn, AbsDbgVariable); 2143 DbgValueStartMap[MInsn] = RegVar; 2144 Scope->addVariable(RegVar); 2145 } 2146 } 2147} 2148 2149/// beginScope - Process beginning of a scope. 2150void DwarfDebug::beginScope(const MachineInstr *MI) { 2151 // Check location. 2152 DebugLoc DL = MI->getDebugLoc(); 2153 if (DL.isUnknown()) { 2154 // This instruction has no debug location. If the preceding instruction 2155 // did, emit debug location information to indicate that the debug 2156 // location is now unknown. 2157 MCSymbol *Label = NULL; 2158 if (DL == PrevInstLoc) 2159 Label = PrevLabel; 2160 else { 2161 Label = recordSourceLine(DL.getLine(), DL.getCol(), 0); 2162 PrevInstLoc = DL; 2163 PrevLabel = Label; 2164 } 2165 2166 // If this instruction begins a scope then note down corresponding label. 2167 if (InsnsBeginScopeSet.count(MI) != 0) 2168 LabelsBeforeInsn[MI] = Label; 2169 2170 return; 2171 } 2172 2173 MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext()); 2174 2175 // FIXME: Should only verify each scope once! 2176 if (!DIScope(Scope).Verify()) 2177 return; 2178 2179 // DBG_VALUE instruction establishes new value. 2180 if (MI->isDebugValue()) { 2181 DenseMap<const MachineInstr *, DbgVariable *>::iterator DI 2182 = DbgValueStartMap.find(MI); 2183 if (DI != DbgValueStartMap.end()) { 2184 MCSymbol *Label = NULL; 2185 if (DL == PrevInstLoc) 2186 Label = PrevLabel; 2187 else { 2188 Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope); 2189 PrevInstLoc = DL; 2190 PrevLabel = Label; 2191 } 2192 DI->second->setDbgValueLabel(Label); 2193 } 2194 return; 2195 } 2196 2197 // Emit a label to indicate location change. This is used for line 2198 // table even if this instruction does not start a new scope. 2199 MCSymbol *Label = NULL; 2200 if (DL == PrevInstLoc) 2201 Label = PrevLabel; 2202 else { 2203 Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope); 2204 PrevInstLoc = DL; 2205 PrevLabel = Label; 2206 } 2207 2208 // If this instruction begins a scope then note down corresponding label. 2209 if (InsnsBeginScopeSet.count(MI) != 0) 2210 LabelsBeforeInsn[MI] = Label; 2211} 2212 2213/// endScope - Process end of a scope. 2214void DwarfDebug::endScope(const MachineInstr *MI) { 2215 if (InsnsEndScopeSet.count(MI) != 0) { 2216 // Emit a label if this instruction ends a scope. 2217 MCSymbol *Label = MMI->getContext().CreateTempSymbol(); 2218 Asm->OutStreamer.EmitLabel(Label); 2219 LabelsAfterInsn[MI] = Label; 2220 } 2221} 2222 2223/// getOrCreateDbgScope - Create DbgScope for the scope. 2224DbgScope *DwarfDebug::getOrCreateDbgScope(MDNode *Scope, MDNode *InlinedAt) { 2225 if (!InlinedAt) { 2226 DbgScope *WScope = DbgScopeMap.lookup(Scope); 2227 if (WScope) 2228 return WScope; 2229 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL); 2230 DbgScopeMap.insert(std::make_pair(Scope, WScope)); 2231 if (DIDescriptor(Scope).isLexicalBlock()) { 2232 DbgScope *Parent = 2233 getOrCreateDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL); 2234 WScope->setParent(Parent); 2235 Parent->addScope(WScope); 2236 } 2237 2238 if (!WScope->getParent()) { 2239 StringRef SPName = DISubprogram(Scope).getLinkageName(); 2240 if (SPName == Asm->MF->getFunction()->getName()) 2241 CurrentFnDbgScope = WScope; 2242 } 2243 2244 return WScope; 2245 } 2246 2247 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt); 2248 if (WScope) 2249 return WScope; 2250 2251 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt); 2252 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope)); 2253 DILocation DL(InlinedAt); 2254 DbgScope *Parent = 2255 getOrCreateDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode()); 2256 WScope->setParent(Parent); 2257 Parent->addScope(WScope); 2258 2259 ConcreteScopes[InlinedAt] = WScope; 2260 getOrCreateAbstractScope(Scope); 2261 2262 return WScope; 2263} 2264 2265/// hasValidLocation - Return true if debug location entry attached with 2266/// machine instruction encodes valid location info. 2267static bool hasValidLocation(LLVMContext &Ctx, 2268 const MachineInstr *MInsn, 2269 MDNode *&Scope, MDNode *&InlinedAt) { 2270 if (MInsn->isDebugValue()) 2271 return false; 2272 DebugLoc DL = MInsn->getDebugLoc(); 2273 if (DL.isUnknown()) return false; 2274 2275 MDNode *S = DL.getScope(Ctx); 2276 2277 // There is no need to create another DIE for compile unit. For all 2278 // other scopes, create one DbgScope now. This will be translated 2279 // into a scope DIE at the end. 2280 if (DIScope(S).isCompileUnit()) return false; 2281 2282 Scope = S; 2283 InlinedAt = DL.getInlinedAt(Ctx); 2284 return true; 2285} 2286 2287/// calculateDominanceGraph - Calculate dominance graph for DbgScope 2288/// hierarchy. 2289static void calculateDominanceGraph(DbgScope *Scope) { 2290 assert (Scope && "Unable to calculate scop edominance graph!"); 2291 SmallVector<DbgScope *, 4> WorkStack; 2292 WorkStack.push_back(Scope); 2293 unsigned Counter = 0; 2294 while (!WorkStack.empty()) { 2295 DbgScope *WS = WorkStack.back(); 2296 const SmallVector<DbgScope *, 4> &Children = WS->getScopes(); 2297 bool visitedChildren = false; 2298 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(), 2299 SE = Children.end(); SI != SE; ++SI) { 2300 DbgScope *ChildScope = *SI; 2301 if (!ChildScope->getDFSOut()) { 2302 WorkStack.push_back(ChildScope); 2303 visitedChildren = true; 2304 ChildScope->setDFSIn(++Counter); 2305 break; 2306 } 2307 } 2308 if (!visitedChildren) { 2309 WorkStack.pop_back(); 2310 WS->setDFSOut(++Counter); 2311 } 2312 } 2313} 2314 2315/// printDbgScopeInfo - Print DbgScope info for each machine instruction. 2316static 2317void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF, 2318 DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap) 2319{ 2320#ifndef NDEBUG 2321 unsigned PrevDFSIn = 0; 2322 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); 2323 I != E; ++I) { 2324 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end(); 2325 II != IE; ++II) { 2326 const MachineInstr *MInsn = II; 2327 MDNode *Scope = NULL; 2328 MDNode *InlinedAt = NULL; 2329 2330 // Check if instruction has valid location information. 2331 if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) { 2332 dbgs() << " [ "; 2333 if (InlinedAt) 2334 dbgs() << "*"; 2335 DenseMap<const MachineInstr *, DbgScope *>::iterator DI = 2336 MI2ScopeMap.find(MInsn); 2337 if (DI != MI2ScopeMap.end()) { 2338 DbgScope *S = DI->second; 2339 dbgs() << S->getDFSIn(); 2340 PrevDFSIn = S->getDFSIn(); 2341 } else 2342 dbgs() << PrevDFSIn; 2343 } else 2344 dbgs() << " [ x" << PrevDFSIn; 2345 dbgs() << " ]"; 2346 MInsn->dump(); 2347 } 2348 dbgs() << "\n"; 2349 } 2350#endif 2351} 2352/// extractScopeInformation - Scan machine instructions in this function 2353/// and collect DbgScopes. Return true, if at least one scope was found. 2354bool DwarfDebug::extractScopeInformation() { 2355 // If scope information was extracted using .dbg intrinsics then there is not 2356 // any need to extract these information by scanning each instruction. 2357 if (!DbgScopeMap.empty()) 2358 return false; 2359 2360 // Scan each instruction and create scopes. First build working set of scopes. 2361 LLVMContext &Ctx = Asm->MF->getFunction()->getContext(); 2362 SmallVector<DbgRange, 4> MIRanges; 2363 DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap; 2364 MDNode *PrevScope = NULL; 2365 MDNode *PrevInlinedAt = NULL; 2366 const MachineInstr *RangeBeginMI = NULL; 2367 const MachineInstr *PrevMI = NULL; 2368 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end(); 2369 I != E; ++I) { 2370 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end(); 2371 II != IE; ++II) { 2372 const MachineInstr *MInsn = II; 2373 MDNode *Scope = NULL; 2374 MDNode *InlinedAt = NULL; 2375 2376 // Check if instruction has valid location information. 2377 if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) { 2378 PrevMI = MInsn; 2379 continue; 2380 } 2381 2382 // If scope has not changed then skip this instruction. 2383 if (Scope == PrevScope && PrevInlinedAt == InlinedAt) { 2384 PrevMI = MInsn; 2385 continue; 2386 } 2387 2388 if (RangeBeginMI) { 2389 // If we have alread seen a beginning of a instruction range and 2390 // current instruction scope does not match scope of first instruction 2391 // in this range then create a new instruction range. 2392 DbgRange R(RangeBeginMI, PrevMI); 2393 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt); 2394 MIRanges.push_back(R); 2395 } 2396 2397 // This is a beginning of a new instruction range. 2398 RangeBeginMI = MInsn; 2399 2400 // Reset previous markers. 2401 PrevMI = MInsn; 2402 PrevScope = Scope; 2403 PrevInlinedAt = InlinedAt; 2404 } 2405 } 2406 2407 // Create last instruction range. 2408 if (RangeBeginMI && PrevMI && PrevScope) { 2409 DbgRange R(RangeBeginMI, PrevMI); 2410 MIRanges.push_back(R); 2411 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt); 2412 } 2413 2414 if (!CurrentFnDbgScope) 2415 return false; 2416 2417 calculateDominanceGraph(CurrentFnDbgScope); 2418 if (PrintDbgScope) 2419 printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap); 2420 2421 // Find ranges of instructions covered by each DbgScope; 2422 DbgScope *PrevDbgScope = NULL; 2423 for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(), 2424 RE = MIRanges.end(); RI != RE; ++RI) { 2425 const DbgRange &R = *RI; 2426 DbgScope *S = MI2ScopeMap.lookup(R.first); 2427 assert (S && "Lost DbgScope for a machine instruction!"); 2428 if (PrevDbgScope && !PrevDbgScope->dominates(S)) 2429 PrevDbgScope->closeInsnRange(S); 2430 S->openInsnRange(R.first); 2431 S->extendInsnRange(R.second); 2432 PrevDbgScope = S; 2433 } 2434 2435 if (PrevDbgScope) 2436 PrevDbgScope->closeInsnRange(); 2437 2438 identifyScopeMarkers(); 2439 2440 return !DbgScopeMap.empty(); 2441} 2442 2443/// identifyScopeMarkers() - 2444/// Each DbgScope has first instruction and last instruction to mark beginning 2445/// and end of a scope respectively. Create an inverse map that list scopes 2446/// starts (and ends) with an instruction. One instruction may start (or end) 2447/// multiple scopes. Ignore scopes that are not reachable. 2448void DwarfDebug::identifyScopeMarkers() { 2449 SmallVector<DbgScope *, 4> WorkList; 2450 WorkList.push_back(CurrentFnDbgScope); 2451 while (!WorkList.empty()) { 2452 DbgScope *S = WorkList.pop_back_val(); 2453 2454 const SmallVector<DbgScope *, 4> &Children = S->getScopes(); 2455 if (!Children.empty()) 2456 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(), 2457 SE = Children.end(); SI != SE; ++SI) 2458 WorkList.push_back(*SI); 2459 2460 if (S->isAbstractScope()) 2461 continue; 2462 2463 const SmallVector<DbgRange, 4> &Ranges = S->getRanges(); 2464 if (Ranges.empty()) 2465 continue; 2466 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(), 2467 RE = Ranges.end(); RI != RE; ++RI) { 2468 assert(RI->first && "DbgRange does not have first instruction!"); 2469 assert(RI->second && "DbgRange does not have second instruction!"); 2470 InsnsBeginScopeSet.insert(RI->first); 2471 InsnsEndScopeSet.insert(RI->second); 2472 } 2473 } 2474} 2475 2476/// FindFirstDebugLoc - Find the first debug location in the function. This 2477/// is intended to be an approximation for the source position of the 2478/// beginning of the function. 2479static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) { 2480 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); 2481 I != E; ++I) 2482 for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end(); 2483 MBBI != MBBE; ++MBBI) { 2484 DebugLoc DL = MBBI->getDebugLoc(); 2485 if (!DL.isUnknown()) 2486 return DL; 2487 } 2488 return DebugLoc(); 2489} 2490 2491/// beginFunction - Gather pre-function debug information. Assumes being 2492/// emitted immediately after the function entry point. 2493void DwarfDebug::beginFunction(const MachineFunction *MF) { 2494 if (!MMI->hasDebugInfo()) return; 2495 if (!extractScopeInformation()) return; 2496 2497 collectVariableInfo(); 2498 2499 FunctionBeginSym = Asm->GetTempSymbol("func_begin", 2500 Asm->getFunctionNumber()); 2501 // Assumes in correct section after the entry point. 2502 Asm->OutStreamer.EmitLabel(FunctionBeginSym); 2503 2504 // Emit label for the implicitly defined dbg.stoppoint at the start of the 2505 // function. 2506 DebugLoc FDL = FindFirstDebugLoc(MF); 2507 if (FDL.isUnknown()) return; 2508 2509 MDNode *Scope = FDL.getScope(MF->getFunction()->getContext()); 2510 2511 DISubprogram SP = getDISubprogram(Scope); 2512 unsigned Line, Col; 2513 if (SP.Verify()) { 2514 Line = SP.getLineNumber(); 2515 Col = 0; 2516 } else { 2517 Line = FDL.getLine(); 2518 Col = FDL.getCol(); 2519 } 2520 2521 recordSourceLine(Line, Col, Scope); 2522} 2523 2524/// endFunction - Gather and emit post-function debug information. 2525/// 2526void DwarfDebug::endFunction(const MachineFunction *MF) { 2527 if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return; 2528 2529 if (CurrentFnDbgScope) { 2530 // Define end label for subprogram. 2531 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("func_end", 2532 Asm->getFunctionNumber())); 2533 2534 // Get function line info. 2535 if (!Lines.empty()) { 2536 // Get section line info. 2537 unsigned ID = SectionMap.insert(Asm->getCurrentSection()); 2538 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID); 2539 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1]; 2540 // Append the function info to section info. 2541 SectionLineInfos.insert(SectionLineInfos.end(), 2542 Lines.begin(), Lines.end()); 2543 } 2544 2545 // Construct abstract scopes. 2546 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(), 2547 AE = AbstractScopesList.end(); AI != AE; ++AI) 2548 constructScopeDIE(*AI); 2549 2550 DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope); 2551 2552 if (!DisableFramePointerElim(*MF)) 2553 addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr, 2554 dwarf::DW_FORM_flag, 1); 2555 2556 2557 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(), 2558 MMI->getFrameMoves())); 2559 } 2560 2561 // Clear debug info 2562 CurrentFnDbgScope = NULL; 2563 DeleteContainerSeconds(DbgScopeMap); 2564 InsnsBeginScopeSet.clear(); 2565 InsnsEndScopeSet.clear(); 2566 DbgValueStartMap.clear(); 2567 ConcreteScopes.clear(); 2568 DeleteContainerSeconds(AbstractScopes); 2569 AbstractScopesList.clear(); 2570 AbstractVariables.clear(); 2571 LabelsBeforeInsn.clear(); 2572 LabelsAfterInsn.clear(); 2573 Lines.clear(); 2574 PrevLabel = NULL; 2575} 2576 2577/// recordSourceLine - Register a source line with debug info. Returns the 2578/// unique label that was emitted and which provides correspondence to 2579/// the source line list. 2580MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, MDNode *S) { 2581 StringRef Dir; 2582 StringRef Fn; 2583 2584 unsigned Src = 1; 2585 if (S) { 2586 DIDescriptor Scope(S); 2587 2588 if (Scope.isCompileUnit()) { 2589 DICompileUnit CU(S); 2590 Dir = CU.getDirectory(); 2591 Fn = CU.getFilename(); 2592 } else if (Scope.isSubprogram()) { 2593 DISubprogram SP(S); 2594 Dir = SP.getDirectory(); 2595 Fn = SP.getFilename(); 2596 } else if (Scope.isLexicalBlock()) { 2597 DILexicalBlock DB(S); 2598 Dir = DB.getDirectory(); 2599 Fn = DB.getFilename(); 2600 } else 2601 assert(0 && "Unexpected scope info"); 2602 2603 Src = GetOrCreateSourceID(Dir, Fn); 2604 } 2605 2606 MCSymbol *Label = MMI->getContext().CreateTempSymbol(); 2607 Lines.push_back(SrcLineInfo(Line, Col, Src, Label)); 2608 2609 Asm->OutStreamer.EmitLabel(Label); 2610 return Label; 2611} 2612 2613//===----------------------------------------------------------------------===// 2614// Emit Methods 2615//===----------------------------------------------------------------------===// 2616 2617/// computeSizeAndOffset - Compute the size and offset of a DIE. 2618/// 2619unsigned 2620DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) { 2621 // Get the children. 2622 const std::vector<DIE *> &Children = Die->getChildren(); 2623 2624 // If not last sibling and has children then add sibling offset attribute. 2625 if (!Last && !Children.empty()) 2626 Die->addSiblingOffset(DIEValueAllocator); 2627 2628 // Record the abbreviation. 2629 assignAbbrevNumber(Die->getAbbrev()); 2630 2631 // Get the abbreviation for this DIE. 2632 unsigned AbbrevNumber = Die->getAbbrevNumber(); 2633 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1]; 2634 2635 // Set DIE offset 2636 Die->setOffset(Offset); 2637 2638 // Start the size with the size of abbreviation code. 2639 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber); 2640 2641 const SmallVector<DIEValue*, 32> &Values = Die->getValues(); 2642 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData(); 2643 2644 // Size the DIE attribute values. 2645 for (unsigned i = 0, N = Values.size(); i < N; ++i) 2646 // Size attribute value. 2647 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm()); 2648 2649 // Size the DIE children if any. 2650 if (!Children.empty()) { 2651 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes && 2652 "Children flag not set"); 2653 2654 for (unsigned j = 0, M = Children.size(); j < M; ++j) 2655 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M); 2656 2657 // End of children marker. 2658 Offset += sizeof(int8_t); 2659 } 2660 2661 Die->setSize(Offset - Die->getOffset()); 2662 return Offset; 2663} 2664 2665/// computeSizeAndOffsets - Compute the size and offset of all the DIEs. 2666/// 2667void DwarfDebug::computeSizeAndOffsets() { 2668 // Compute size of compile unit header. 2669 static unsigned Offset = 2670 sizeof(int32_t) + // Length of Compilation Unit Info 2671 sizeof(int16_t) + // DWARF version number 2672 sizeof(int32_t) + // Offset Into Abbrev. Section 2673 sizeof(int8_t); // Pointer Size (in bytes) 2674 2675 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true); 2676} 2677 2678/// EmitSectionSym - Switch to the specified MCSection and emit an assembler 2679/// temporary label to it if SymbolStem is specified. 2680static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section, 2681 const char *SymbolStem = 0) { 2682 Asm->OutStreamer.SwitchSection(Section); 2683 if (!SymbolStem) return 0; 2684 2685 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem); 2686 Asm->OutStreamer.EmitLabel(TmpSym); 2687 return TmpSym; 2688} 2689 2690/// EmitSectionLabels - Emit initial Dwarf sections with a label at 2691/// the start of each one. 2692void DwarfDebug::EmitSectionLabels() { 2693 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 2694 2695 // Dwarf sections base addresses. 2696 if (Asm->MAI->doesDwarfRequireFrameSection()) { 2697 DwarfFrameSectionSym = 2698 EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame"); 2699 } 2700 2701 DwarfInfoSectionSym = 2702 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info"); 2703 DwarfAbbrevSectionSym = 2704 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev"); 2705 EmitSectionSym(Asm, TLOF.getDwarfARangesSection()); 2706 2707 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection()) 2708 EmitSectionSym(Asm, MacroInfo); 2709 2710 EmitSectionSym(Asm, TLOF.getDwarfLineSection()); 2711 EmitSectionSym(Asm, TLOF.getDwarfLocSection()); 2712 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection()); 2713 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection()); 2714 DwarfStrSectionSym = 2715 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str"); 2716 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(), 2717 "debug_range"); 2718 2719 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin"); 2720 EmitSectionSym(Asm, TLOF.getDataSection()); 2721} 2722 2723/// emitDIE - Recusively Emits a debug information entry. 2724/// 2725void DwarfDebug::emitDIE(DIE *Die) { 2726 // Get the abbreviation for this DIE. 2727 unsigned AbbrevNumber = Die->getAbbrevNumber(); 2728 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1]; 2729 2730 // Emit the code (index) for the abbreviation. 2731 if (Asm->isVerbose()) 2732 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" + 2733 Twine::utohexstr(Die->getOffset()) + ":0x" + 2734 Twine::utohexstr(Die->getSize()) + " " + 2735 dwarf::TagString(Abbrev->getTag())); 2736 Asm->EmitULEB128(AbbrevNumber); 2737 2738 const SmallVector<DIEValue*, 32> &Values = Die->getValues(); 2739 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData(); 2740 2741 // Emit the DIE attribute values. 2742 for (unsigned i = 0, N = Values.size(); i < N; ++i) { 2743 unsigned Attr = AbbrevData[i].getAttribute(); 2744 unsigned Form = AbbrevData[i].getForm(); 2745 assert(Form && "Too many attributes for DIE (check abbreviation)"); 2746 2747 if (Asm->isVerbose()) 2748 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr)); 2749 2750 switch (Attr) { 2751 case dwarf::DW_AT_sibling: 2752 Asm->EmitInt32(Die->getSiblingOffset()); 2753 break; 2754 case dwarf::DW_AT_abstract_origin: { 2755 DIEEntry *E = cast<DIEEntry>(Values[i]); 2756 DIE *Origin = E->getEntry(); 2757 unsigned Addr = Origin->getOffset(); 2758 Asm->EmitInt32(Addr); 2759 break; 2760 } 2761 case dwarf::DW_AT_ranges: { 2762 // DW_AT_range Value encodes offset in debug_range section. 2763 DIEInteger *V = cast<DIEInteger>(Values[i]); 2764 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym, 2765 V->getValue(), 2766 DwarfDebugRangeSectionSym, 2767 4); 2768 break; 2769 } 2770 default: 2771 // Emit an attribute using the defined form. 2772 Values[i]->EmitValue(Asm, Form); 2773 break; 2774 } 2775 } 2776 2777 // Emit the DIE children if any. 2778 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) { 2779 const std::vector<DIE *> &Children = Die->getChildren(); 2780 2781 for (unsigned j = 0, M = Children.size(); j < M; ++j) 2782 emitDIE(Children[j]); 2783 2784 if (Asm->isVerbose()) 2785 Asm->OutStreamer.AddComment("End Of Children Mark"); 2786 Asm->EmitInt8(0); 2787 } 2788} 2789 2790/// emitDebugInfo - Emit the debug info section. 2791/// 2792void DwarfDebug::emitDebugInfo() { 2793 // Start debug info section. 2794 Asm->OutStreamer.SwitchSection( 2795 Asm->getObjFileLowering().getDwarfInfoSection()); 2796 DIE *Die = ModuleCU->getCUDie(); 2797 2798 // Emit the compile units header. 2799 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin", 2800 ModuleCU->getID())); 2801 2802 // Emit size of content not including length itself 2803 unsigned ContentSize = Die->getSize() + 2804 sizeof(int16_t) + // DWARF version number 2805 sizeof(int32_t) + // Offset Into Abbrev. Section 2806 sizeof(int8_t) + // Pointer Size (in bytes) 2807 sizeof(int32_t); // FIXME - extra pad for gdb bug. 2808 2809 Asm->OutStreamer.AddComment("Length of Compilation Unit Info"); 2810 Asm->EmitInt32(ContentSize); 2811 Asm->OutStreamer.AddComment("DWARF version number"); 2812 Asm->EmitInt16(dwarf::DWARF_VERSION); 2813 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section"); 2814 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"), 2815 DwarfAbbrevSectionSym); 2816 Asm->OutStreamer.AddComment("Address Size (in bytes)"); 2817 Asm->EmitInt8(Asm->getTargetData().getPointerSize()); 2818 2819 emitDIE(Die); 2820 // FIXME - extra padding for gdb bug. 2821 Asm->OutStreamer.AddComment("4 extra padding bytes for GDB"); 2822 Asm->EmitInt8(0); 2823 Asm->EmitInt8(0); 2824 Asm->EmitInt8(0); 2825 Asm->EmitInt8(0); 2826 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", ModuleCU->getID())); 2827} 2828 2829/// emitAbbreviations - Emit the abbreviation section. 2830/// 2831void DwarfDebug::emitAbbreviations() const { 2832 // Check to see if it is worth the effort. 2833 if (!Abbreviations.empty()) { 2834 // Start the debug abbrev section. 2835 Asm->OutStreamer.SwitchSection( 2836 Asm->getObjFileLowering().getDwarfAbbrevSection()); 2837 2838 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin")); 2839 2840 // For each abbrevation. 2841 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) { 2842 // Get abbreviation data 2843 const DIEAbbrev *Abbrev = Abbreviations[i]; 2844 2845 // Emit the abbrevations code (base 1 index.) 2846 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code"); 2847 2848 // Emit the abbreviations data. 2849 Abbrev->Emit(Asm); 2850 } 2851 2852 // Mark end of abbreviations. 2853 Asm->EmitULEB128(0, "EOM(3)"); 2854 2855 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end")); 2856 } 2857} 2858 2859/// emitEndOfLineMatrix - Emit the last address of the section and the end of 2860/// the line matrix. 2861/// 2862void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) { 2863 // Define last address of section. 2864 Asm->OutStreamer.AddComment("Extended Op"); 2865 Asm->EmitInt8(0); 2866 2867 Asm->OutStreamer.AddComment("Op size"); 2868 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1); 2869 Asm->OutStreamer.AddComment("DW_LNE_set_address"); 2870 Asm->EmitInt8(dwarf::DW_LNE_set_address); 2871 2872 Asm->OutStreamer.AddComment("Section end label"); 2873 2874 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd), 2875 Asm->getTargetData().getPointerSize(), 2876 0/*AddrSpace*/); 2877 2878 // Mark end of matrix. 2879 Asm->OutStreamer.AddComment("DW_LNE_end_sequence"); 2880 Asm->EmitInt8(0); 2881 Asm->EmitInt8(1); 2882 Asm->EmitInt8(1); 2883} 2884 2885/// emitDebugLines - Emit source line information. 2886/// 2887void DwarfDebug::emitDebugLines() { 2888 // If the target is using .loc/.file, the assembler will be emitting the 2889 // .debug_line table automatically. 2890 if (Asm->MAI->hasDotLocAndDotFile()) 2891 return; 2892 2893 // Minimum line delta, thus ranging from -10..(255-10). 2894 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1); 2895 // Maximum line delta, thus ranging from -10..(255-10). 2896 const int MaxLineDelta = 255 + MinLineDelta; 2897 2898 // Start the dwarf line section. 2899 Asm->OutStreamer.SwitchSection( 2900 Asm->getObjFileLowering().getDwarfLineSection()); 2901 2902 // Construct the section header. 2903 Asm->OutStreamer.AddComment("Length of Source Line Info"); 2904 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_end"), 2905 Asm->GetTempSymbol("line_begin"), 4); 2906 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_begin")); 2907 2908 Asm->OutStreamer.AddComment("DWARF version number"); 2909 Asm->EmitInt16(dwarf::DWARF_VERSION); 2910 2911 Asm->OutStreamer.AddComment("Prolog Length"); 2912 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_prolog_end"), 2913 Asm->GetTempSymbol("line_prolog_begin"), 4); 2914 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_begin")); 2915 2916 Asm->OutStreamer.AddComment("Minimum Instruction Length"); 2917 Asm->EmitInt8(1); 2918 Asm->OutStreamer.AddComment("Default is_stmt_start flag"); 2919 Asm->EmitInt8(1); 2920 Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)"); 2921 Asm->EmitInt8(MinLineDelta); 2922 Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)"); 2923 Asm->EmitInt8(MaxLineDelta); 2924 Asm->OutStreamer.AddComment("Special Opcode Base"); 2925 Asm->EmitInt8(-MinLineDelta); 2926 2927 // Line number standard opcode encodings argument count 2928 Asm->OutStreamer.AddComment("DW_LNS_copy arg count"); 2929 Asm->EmitInt8(0); 2930 Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count"); 2931 Asm->EmitInt8(1); 2932 Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count"); 2933 Asm->EmitInt8(1); 2934 Asm->OutStreamer.AddComment("DW_LNS_set_file arg count"); 2935 Asm->EmitInt8(1); 2936 Asm->OutStreamer.AddComment("DW_LNS_set_column arg count"); 2937 Asm->EmitInt8(1); 2938 Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count"); 2939 Asm->EmitInt8(0); 2940 Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count"); 2941 Asm->EmitInt8(0); 2942 Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count"); 2943 Asm->EmitInt8(0); 2944 Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count"); 2945 Asm->EmitInt8(1); 2946 2947 // Emit directories. 2948 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) { 2949 const std::string &Dir = getSourceDirectoryName(DI); 2950 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Directory"); 2951 Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0); 2952 } 2953 2954 Asm->OutStreamer.AddComment("End of directories"); 2955 Asm->EmitInt8(0); 2956 2957 // Emit files. 2958 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) { 2959 // Remember source id starts at 1. 2960 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI); 2961 const std::string &FN = getSourceFileName(Id.second); 2962 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Source"); 2963 Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0); 2964 2965 Asm->EmitULEB128(Id.first, "Directory #"); 2966 Asm->EmitULEB128(0, "Mod date"); 2967 Asm->EmitULEB128(0, "File size"); 2968 } 2969 2970 Asm->OutStreamer.AddComment("End of files"); 2971 Asm->EmitInt8(0); 2972 2973 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_end")); 2974 2975 // A sequence for each text section. 2976 unsigned SecSrcLinesSize = SectionSourceLines.size(); 2977 2978 for (unsigned j = 0; j < SecSrcLinesSize; ++j) { 2979 // Isolate current sections line info. 2980 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j]; 2981 2982 // Dwarf assumes we start with first line of first source file. 2983 unsigned Source = 1; 2984 unsigned Line = 1; 2985 2986 // Construct rows of the address, source, line, column matrix. 2987 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) { 2988 const SrcLineInfo &LineInfo = LineInfos[i]; 2989 MCSymbol *Label = LineInfo.getLabel(); 2990 if (!Label->isDefined()) continue; // Not emitted, in dead code. 2991 2992 if (Asm->isVerbose()) { 2993 std::pair<unsigned, unsigned> SrcID = 2994 getSourceDirectoryAndFileIds(LineInfo.getSourceID()); 2995 Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) + 2996 "/" + 2997 Twine(getSourceFileName(SrcID.second)) + 2998 ":" + Twine(LineInfo.getLine())); 2999 } 3000 3001 // Define the line address. 3002 Asm->OutStreamer.AddComment("Extended Op"); 3003 Asm->EmitInt8(0); 3004 Asm->OutStreamer.AddComment("Op size"); 3005 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1); 3006 3007 Asm->OutStreamer.AddComment("DW_LNE_set_address"); 3008 Asm->EmitInt8(dwarf::DW_LNE_set_address); 3009 3010 Asm->OutStreamer.AddComment("Location label"); 3011 Asm->OutStreamer.EmitSymbolValue(Label, 3012 Asm->getTargetData().getPointerSize(), 3013 0/*AddrSpace*/); 3014 3015 // If change of source, then switch to the new source. 3016 if (Source != LineInfo.getSourceID()) { 3017 Source = LineInfo.getSourceID(); 3018 Asm->OutStreamer.AddComment("DW_LNS_set_file"); 3019 Asm->EmitInt8(dwarf::DW_LNS_set_file); 3020 Asm->EmitULEB128(Source, "New Source"); 3021 } 3022 3023 // If change of line. 3024 if (Line != LineInfo.getLine()) { 3025 // Determine offset. 3026 int Offset = LineInfo.getLine() - Line; 3027 int Delta = Offset - MinLineDelta; 3028 3029 // Update line. 3030 Line = LineInfo.getLine(); 3031 3032 // If delta is small enough and in range... 3033 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) { 3034 // ... then use fast opcode. 3035 Asm->OutStreamer.AddComment("Line Delta"); 3036 Asm->EmitInt8(Delta - MinLineDelta); 3037 } else { 3038 // ... otherwise use long hand. 3039 Asm->OutStreamer.AddComment("DW_LNS_advance_line"); 3040 Asm->EmitInt8(dwarf::DW_LNS_advance_line); 3041 Asm->EmitSLEB128(Offset, "Line Offset"); 3042 Asm->OutStreamer.AddComment("DW_LNS_copy"); 3043 Asm->EmitInt8(dwarf::DW_LNS_copy); 3044 } 3045 } else { 3046 // Copy the previous row (different address or source) 3047 Asm->OutStreamer.AddComment("DW_LNS_copy"); 3048 Asm->EmitInt8(dwarf::DW_LNS_copy); 3049 } 3050 } 3051 3052 emitEndOfLineMatrix(j + 1); 3053 } 3054 3055 if (SecSrcLinesSize == 0) 3056 // Because we're emitting a debug_line section, we still need a line 3057 // table. The linker and friends expect it to exist. If there's nothing to 3058 // put into it, emit an empty table. 3059 emitEndOfLineMatrix(1); 3060 3061 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_end")); 3062} 3063 3064/// emitCommonDebugFrame - Emit common frame info into a debug frame section. 3065/// 3066void DwarfDebug::emitCommonDebugFrame() { 3067 if (!Asm->MAI->doesDwarfRequireFrameSection()) 3068 return; 3069 3070 int stackGrowth = Asm->getTargetData().getPointerSize(); 3071 if (Asm->TM.getFrameInfo()->getStackGrowthDirection() == 3072 TargetFrameInfo::StackGrowsDown) 3073 stackGrowth *= -1; 3074 3075 // Start the dwarf frame section. 3076 Asm->OutStreamer.SwitchSection( 3077 Asm->getObjFileLowering().getDwarfFrameSection()); 3078 3079 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common")); 3080 Asm->OutStreamer.AddComment("Length of Common Information Entry"); 3081 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"), 3082 Asm->GetTempSymbol("debug_frame_common_begin"), 4); 3083 3084 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin")); 3085 Asm->OutStreamer.AddComment("CIE Identifier Tag"); 3086 Asm->EmitInt32((int)dwarf::DW_CIE_ID); 3087 Asm->OutStreamer.AddComment("CIE Version"); 3088 Asm->EmitInt8(dwarf::DW_CIE_VERSION); 3089 Asm->OutStreamer.AddComment("CIE Augmentation"); 3090 Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator. 3091 Asm->EmitULEB128(1, "CIE Code Alignment Factor"); 3092 Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor"); 3093 Asm->OutStreamer.AddComment("CIE RA Column"); 3094 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo(); 3095 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false)); 3096 3097 std::vector<MachineMove> Moves; 3098 RI->getInitialFrameState(Moves); 3099 3100 Asm->EmitFrameMoves(Moves, 0, false); 3101 3102 Asm->EmitAlignment(2); 3103 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end")); 3104} 3105 3106/// emitFunctionDebugFrame - Emit per function frame info into a debug frame 3107/// section. 3108void DwarfDebug:: 3109emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) { 3110 if (!Asm->MAI->doesDwarfRequireFrameSection()) 3111 return; 3112 3113 // Start the dwarf frame section. 3114 Asm->OutStreamer.SwitchSection( 3115 Asm->getObjFileLowering().getDwarfFrameSection()); 3116 3117 Asm->OutStreamer.AddComment("Length of Frame Information Entry"); 3118 MCSymbol *DebugFrameBegin = 3119 Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number); 3120 MCSymbol *DebugFrameEnd = 3121 Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number); 3122 Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4); 3123 3124 Asm->OutStreamer.EmitLabel(DebugFrameBegin); 3125 3126 Asm->OutStreamer.AddComment("FDE CIE offset"); 3127 Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"), 3128 DwarfFrameSectionSym); 3129 3130 Asm->OutStreamer.AddComment("FDE initial location"); 3131 MCSymbol *FuncBeginSym = 3132 Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number); 3133 Asm->OutStreamer.EmitSymbolValue(FuncBeginSym, 3134 Asm->getTargetData().getPointerSize(), 3135 0/*AddrSpace*/); 3136 3137 3138 Asm->OutStreamer.AddComment("FDE address range"); 3139 Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number), 3140 FuncBeginSym, Asm->getTargetData().getPointerSize()); 3141 3142 Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false); 3143 3144 Asm->EmitAlignment(2); 3145 Asm->OutStreamer.EmitLabel(DebugFrameEnd); 3146} 3147 3148/// emitDebugPubNames - Emit visible names into a debug pubnames section. 3149/// 3150void DwarfDebug::emitDebugPubNames() { 3151 // Start the dwarf pubnames section. 3152 Asm->OutStreamer.SwitchSection( 3153 Asm->getObjFileLowering().getDwarfPubNamesSection()); 3154 3155 Asm->OutStreamer.AddComment("Length of Public Names Info"); 3156 Asm->EmitLabelDifference( 3157 Asm->GetTempSymbol("pubnames_end", ModuleCU->getID()), 3158 Asm->GetTempSymbol("pubnames_begin", ModuleCU->getID()), 4); 3159 3160 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", 3161 ModuleCU->getID())); 3162 3163 Asm->OutStreamer.AddComment("DWARF Version"); 3164 Asm->EmitInt16(dwarf::DWARF_VERSION); 3165 3166 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info"); 3167 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()), 3168 DwarfInfoSectionSym); 3169 3170 Asm->OutStreamer.AddComment("Compilation Unit Length"); 3171 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()), 3172 Asm->GetTempSymbol("info_begin", ModuleCU->getID()), 3173 4); 3174 3175 const StringMap<DIE*> &Globals = ModuleCU->getGlobals(); 3176 for (StringMap<DIE*>::const_iterator 3177 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) { 3178 const char *Name = GI->getKeyData(); 3179 DIE *Entity = GI->second; 3180 3181 Asm->OutStreamer.AddComment("DIE offset"); 3182 Asm->EmitInt32(Entity->getOffset()); 3183 3184 if (Asm->isVerbose()) 3185 Asm->OutStreamer.AddComment("External Name"); 3186 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0); 3187 } 3188 3189 Asm->OutStreamer.AddComment("End Mark"); 3190 Asm->EmitInt32(0); 3191 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", 3192 ModuleCU->getID())); 3193} 3194 3195void DwarfDebug::emitDebugPubTypes() { 3196 // Start the dwarf pubnames section. 3197 Asm->OutStreamer.SwitchSection( 3198 Asm->getObjFileLowering().getDwarfPubTypesSection()); 3199 Asm->OutStreamer.AddComment("Length of Public Types Info"); 3200 Asm->EmitLabelDifference( 3201 Asm->GetTempSymbol("pubtypes_end", ModuleCU->getID()), 3202 Asm->GetTempSymbol("pubtypes_begin", ModuleCU->getID()), 4); 3203 3204 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin", 3205 ModuleCU->getID())); 3206 3207 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version"); 3208 Asm->EmitInt16(dwarf::DWARF_VERSION); 3209 3210 Asm->OutStreamer.AddComment("Offset of Compilation ModuleCU Info"); 3211 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()), 3212 DwarfInfoSectionSym); 3213 3214 Asm->OutStreamer.AddComment("Compilation ModuleCU Length"); 3215 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()), 3216 Asm->GetTempSymbol("info_begin", ModuleCU->getID()), 3217 4); 3218 3219 const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes(); 3220 for (StringMap<DIE*>::const_iterator 3221 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) { 3222 const char *Name = GI->getKeyData(); 3223 DIE * Entity = GI->second; 3224 3225 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset"); 3226 Asm->EmitInt32(Entity->getOffset()); 3227 3228 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name"); 3229 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0); 3230 } 3231 3232 Asm->OutStreamer.AddComment("End Mark"); 3233 Asm->EmitInt32(0); 3234 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end", 3235 ModuleCU->getID())); 3236} 3237 3238/// emitDebugStr - Emit visible names into a debug str section. 3239/// 3240void DwarfDebug::emitDebugStr() { 3241 // Check to see if it is worth the effort. 3242 if (StringPool.empty()) return; 3243 3244 // Start the dwarf str section. 3245 Asm->OutStreamer.SwitchSection( 3246 Asm->getObjFileLowering().getDwarfStrSection()); 3247 3248 // Get all of the string pool entries and put them in an array by their ID so 3249 // we can sort them. 3250 SmallVector<std::pair<unsigned, 3251 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries; 3252 3253 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator 3254 I = StringPool.begin(), E = StringPool.end(); I != E; ++I) 3255 Entries.push_back(std::make_pair(I->second.second, &*I)); 3256 3257 array_pod_sort(Entries.begin(), Entries.end()); 3258 3259 for (unsigned i = 0, e = Entries.size(); i != e; ++i) { 3260 // Emit a label for reference from debug information entries. 3261 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first); 3262 3263 // Emit the string itself. 3264 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/); 3265 } 3266} 3267 3268/// emitDebugLoc - Emit visible names into a debug loc section. 3269/// 3270void DwarfDebug::emitDebugLoc() { 3271 // Start the dwarf loc section. 3272 Asm->OutStreamer.SwitchSection( 3273 Asm->getObjFileLowering().getDwarfLocSection()); 3274} 3275 3276/// EmitDebugARanges - Emit visible names into a debug aranges section. 3277/// 3278void DwarfDebug::EmitDebugARanges() { 3279 // Start the dwarf aranges section. 3280 Asm->OutStreamer.SwitchSection( 3281 Asm->getObjFileLowering().getDwarfARangesSection()); 3282} 3283 3284/// emitDebugRanges - Emit visible names into a debug ranges section. 3285/// 3286void DwarfDebug::emitDebugRanges() { 3287 // Start the dwarf ranges section. 3288 Asm->OutStreamer.SwitchSection( 3289 Asm->getObjFileLowering().getDwarfRangesSection()); 3290 unsigned char Size = Asm->getTargetData().getPointerSize(); 3291 for (SmallVector<const MCSymbol *, 8>::iterator 3292 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end(); 3293 I != E; ++I) { 3294 if (*I) 3295 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0); 3296 else 3297 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0); 3298 } 3299} 3300 3301/// emitDebugMacInfo - Emit visible names into a debug macinfo section. 3302/// 3303void DwarfDebug::emitDebugMacInfo() { 3304 if (const MCSection *LineInfo = 3305 Asm->getObjFileLowering().getDwarfMacroInfoSection()) { 3306 // Start the dwarf macinfo section. 3307 Asm->OutStreamer.SwitchSection(LineInfo); 3308 } 3309} 3310 3311/// emitDebugInlineInfo - Emit inline info using following format. 3312/// Section Header: 3313/// 1. length of section 3314/// 2. Dwarf version number 3315/// 3. address size. 3316/// 3317/// Entries (one "entry" for each function that was inlined): 3318/// 3319/// 1. offset into __debug_str section for MIPS linkage name, if exists; 3320/// otherwise offset into __debug_str for regular function name. 3321/// 2. offset into __debug_str section for regular function name. 3322/// 3. an unsigned LEB128 number indicating the number of distinct inlining 3323/// instances for the function. 3324/// 3325/// The rest of the entry consists of a {die_offset, low_pc} pair for each 3326/// inlined instance; the die_offset points to the inlined_subroutine die in the 3327/// __debug_info section, and the low_pc is the starting address for the 3328/// inlining instance. 3329void DwarfDebug::emitDebugInlineInfo() { 3330 if (!Asm->MAI->doesDwarfUsesInlineInfoSection()) 3331 return; 3332 3333 if (!ModuleCU) 3334 return; 3335 3336 Asm->OutStreamer.SwitchSection( 3337 Asm->getObjFileLowering().getDwarfDebugInlineSection()); 3338 3339 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry"); 3340 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1), 3341 Asm->GetTempSymbol("debug_inlined_begin", 1), 4); 3342 3343 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1)); 3344 3345 Asm->OutStreamer.AddComment("Dwarf Version"); 3346 Asm->EmitInt16(dwarf::DWARF_VERSION); 3347 Asm->OutStreamer.AddComment("Address Size (in bytes)"); 3348 Asm->EmitInt8(Asm->getTargetData().getPointerSize()); 3349 3350 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(), 3351 E = InlinedSPNodes.end(); I != E; ++I) { 3352 3353 MDNode *Node = *I; 3354 DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II 3355 = InlineInfo.find(Node); 3356 SmallVector<InlineInfoLabels, 4> &Labels = II->second; 3357 DISubprogram SP(Node); 3358 StringRef LName = SP.getLinkageName(); 3359 StringRef Name = SP.getName(); 3360 3361 Asm->OutStreamer.AddComment("MIPS linkage name"); 3362 if (LName.empty()) { 3363 Asm->OutStreamer.EmitBytes(Name, 0); 3364 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator. 3365 } else 3366 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)), 3367 DwarfStrSectionSym); 3368 3369 Asm->OutStreamer.AddComment("Function name"); 3370 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym); 3371 Asm->EmitULEB128(Labels.size(), "Inline count"); 3372 3373 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(), 3374 LE = Labels.end(); LI != LE; ++LI) { 3375 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset"); 3376 Asm->EmitInt32(LI->second->getOffset()); 3377 3378 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc"); 3379 Asm->OutStreamer.EmitSymbolValue(LI->first, 3380 Asm->getTargetData().getPointerSize(),0); 3381 } 3382 } 3383 3384 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1)); 3385} 3386