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