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