DwarfDebug.cpp revision 5bc942cc3cc970836d48d8ad276ef3b2b1120ffc
1//===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file contains support for writing dwarf debug info into asm files. 11// 12//===----------------------------------------------------------------------===// 13 14#define DEBUG_TYPE "dwarfdebug" 15#include "DwarfDebug.h" 16#include "DIE.h" 17#include "DwarfCompileUnit.h" 18#include "llvm/Constants.h" 19#include "llvm/Module.h" 20#include "llvm/Instructions.h" 21#include "llvm/CodeGen/MachineFunction.h" 22#include "llvm/CodeGen/MachineModuleInfo.h" 23#include "llvm/MC/MCAsmInfo.h" 24#include "llvm/MC/MCSection.h" 25#include "llvm/MC/MCStreamer.h" 26#include "llvm/MC/MCSymbol.h" 27#include "llvm/Target/Mangler.h" 28#include "llvm/Target/TargetData.h" 29#include "llvm/Target/TargetFrameLowering.h" 30#include "llvm/Target/TargetLoweringObjectFile.h" 31#include "llvm/Target/TargetMachine.h" 32#include "llvm/Target/TargetRegisterInfo.h" 33#include "llvm/Target/TargetOptions.h" 34#include "llvm/Analysis/DebugInfo.h" 35#include "llvm/Analysis/DIBuilder.h" 36#include "llvm/ADT/Statistic.h" 37#include "llvm/ADT/STLExtras.h" 38#include "llvm/ADT/StringExtras.h" 39#include "llvm/Support/CommandLine.h" 40#include "llvm/Support/Debug.h" 41#include "llvm/Support/ErrorHandling.h" 42#include "llvm/Support/ValueHandle.h" 43#include "llvm/Support/FormattedStream.h" 44#include "llvm/Support/Timer.h" 45#include "llvm/Support/Path.h" 46using namespace llvm; 47 48static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print", 49 cl::Hidden, 50 cl::desc("Disable debug info printing")); 51 52static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden, 53 cl::desc("Make an absence of debug location information explicit."), 54 cl::init(false)); 55 56namespace { 57 const char *DWARFGroupName = "DWARF Emission"; 58 const char *DbgTimerName = "DWARF Debug Writer"; 59} // end anonymous namespace 60 61//===----------------------------------------------------------------------===// 62 63/// Configuration values for initial hash set sizes (log2). 64/// 65static const unsigned InitAbbreviationsSetSize = 9; // log2(512) 66 67namespace llvm { 68 69DIType DbgVariable::getType() const { 70 DIType Ty = Var.getType(); 71 // FIXME: isBlockByrefVariable should be reformulated in terms of complex 72 // addresses instead. 73 if (Var.isBlockByrefVariable()) { 74 /* Byref variables, in Blocks, are declared by the programmer as 75 "SomeType VarName;", but the compiler creates a 76 __Block_byref_x_VarName struct, and gives the variable VarName 77 either the struct, or a pointer to the struct, as its type. This 78 is necessary for various behind-the-scenes things the compiler 79 needs to do with by-reference variables in blocks. 80 81 However, as far as the original *programmer* is concerned, the 82 variable should still have type 'SomeType', as originally declared. 83 84 The following function dives into the __Block_byref_x_VarName 85 struct to find the original type of the variable. This will be 86 passed back to the code generating the type for the Debug 87 Information Entry for the variable 'VarName'. 'VarName' will then 88 have the original type 'SomeType' in its debug information. 89 90 The original type 'SomeType' will be the type of the field named 91 'VarName' inside the __Block_byref_x_VarName struct. 92 93 NOTE: In order for this to not completely fail on the debugger 94 side, the Debug Information Entry for the variable VarName needs to 95 have a DW_AT_location that tells the debugger how to unwind through 96 the pointers and __Block_byref_x_VarName struct to find the actual 97 value of the variable. The function addBlockByrefType does this. */ 98 DIType subType = Ty; 99 unsigned tag = Ty.getTag(); 100 101 if (tag == dwarf::DW_TAG_pointer_type) { 102 DIDerivedType DTy = DIDerivedType(Ty); 103 subType = DTy.getTypeDerivedFrom(); 104 } 105 106 DICompositeType blockStruct = DICompositeType(subType); 107 DIArray Elements = blockStruct.getTypeArray(); 108 109 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) { 110 DIDescriptor Element = Elements.getElement(i); 111 DIDerivedType DT = DIDerivedType(Element); 112 if (getName() == DT.getName()) 113 return (DT.getTypeDerivedFrom()); 114 } 115 return Ty; 116 } 117 return Ty; 118} 119 120} // end llvm namespace 121 122DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M) 123 : Asm(A), MMI(Asm->MMI), FirstCU(0), 124 AbbreviationsSet(InitAbbreviationsSetSize), 125 PrevLabel(NULL) { 126 NextStringPoolNumber = 0; 127 128 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0; 129 DwarfStrSectionSym = TextSectionSym = 0; 130 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0; 131 FunctionBeginSym = FunctionEndSym = 0; 132 { 133 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled); 134 beginModule(M); 135 } 136} 137DwarfDebug::~DwarfDebug() { 138} 139 140MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) { 141 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str]; 142 if (Entry.first) return Entry.first; 143 144 Entry.second = NextStringPoolNumber++; 145 return Entry.first = Asm->GetTempSymbol("string", Entry.second); 146} 147 148 149/// assignAbbrevNumber - Define a unique number for the abbreviation. 150/// 151void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) { 152 // Profile the node so that we can make it unique. 153 FoldingSetNodeID ID; 154 Abbrev.Profile(ID); 155 156 // Check the set for priors. 157 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev); 158 159 // If it's newly added. 160 if (InSet == &Abbrev) { 161 // Add to abbreviation list. 162 Abbreviations.push_back(&Abbrev); 163 164 // Assign the vector position + 1 as its number. 165 Abbrev.setNumber(Abbreviations.size()); 166 } else { 167 // Assign existing abbreviation number. 168 Abbrev.setNumber(InSet->getNumber()); 169 } 170} 171 172/// getRealLinkageName - If special LLVM prefix that is used to inform the asm 173/// printer to not emit usual symbol prefix before the symbol name is used then 174/// return linkage name after skipping this special LLVM prefix. 175static StringRef getRealLinkageName(StringRef LinkageName) { 176 char One = '\1'; 177 if (LinkageName.startswith(StringRef(&One, 1))) 178 return LinkageName.substr(1); 179 return LinkageName; 180} 181 182/// createSubprogramDIE - Create new DIE using SP. 183DIE *DwarfDebug::createSubprogramDIE(DISubprogram SP) { 184 CompileUnit *SPCU = getCompileUnit(SP); 185 DIE *SPDie = SPCU->getDIE(SP); 186 if (SPDie) 187 return SPDie; 188 189 SPDie = new DIE(dwarf::DW_TAG_subprogram); 190 191 // DW_TAG_inlined_subroutine may refer to this DIE. 192 SPCU->insertDIE(SP, SPDie); 193 194 // Add to context owner. 195 SPCU->addToContextOwner(SPDie, SP.getContext()); 196 197 // Add function template parameters. 198 SPCU->addTemplateParams(*SPDie, SP.getTemplateParams()); 199 200 StringRef LinkageName = SP.getLinkageName(); 201 if (!LinkageName.empty()) 202 SPCU->addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, 203 dwarf::DW_FORM_string, 204 getRealLinkageName(LinkageName)); 205 206 // If this DIE is going to refer declaration info using AT_specification 207 // then there is no need to add other attributes. 208 if (SP.getFunctionDeclaration().isSubprogram()) 209 return SPDie; 210 211 // Constructors and operators for anonymous aggregates do not have names. 212 if (!SP.getName().empty()) 213 SPCU->addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, 214 SP.getName()); 215 216 SPCU->addSourceLine(SPDie, SP); 217 218 if (SP.isPrototyped()) 219 SPCU->addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1); 220 221 // Add Return Type. 222 DICompositeType SPTy = SP.getType(); 223 DIArray Args = SPTy.getTypeArray(); 224 unsigned SPTag = SPTy.getTag(); 225 226 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type) 227 SPCU->addType(SPDie, SPTy); 228 else 229 SPCU->addType(SPDie, DIType(Args.getElement(0))); 230 231 unsigned VK = SP.getVirtuality(); 232 if (VK) { 233 SPCU->addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK); 234 DIEBlock *Block = SPCU->getDIEBlock(); 235 SPCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 236 SPCU->addUInt(Block, 0, dwarf::DW_FORM_udata, SP.getVirtualIndex()); 237 SPCU->addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block); 238 ContainingTypeMap.insert(std::make_pair(SPDie, 239 SP.getContainingType())); 240 } 241 242 if (!SP.isDefinition()) { 243 SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1); 244 245 // Add arguments. Do not add arguments for subprogram definition. They will 246 // be handled while processing variables. 247 DICompositeType SPTy = SP.getType(); 248 DIArray Args = SPTy.getTypeArray(); 249 unsigned SPTag = SPTy.getTag(); 250 251 if (SPTag == dwarf::DW_TAG_subroutine_type) 252 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) { 253 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter); 254 DIType ATy = DIType(DIType(Args.getElement(i))); 255 SPCU->addType(Arg, ATy); 256 if (ATy.isArtificial()) 257 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); 258 SPDie->addChild(Arg); 259 } 260 } 261 262 if (SP.isArtificial()) 263 SPCU->addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); 264 265 if (!SP.isLocalToUnit()) 266 SPCU->addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1); 267 268 if (SP.isOptimized()) 269 SPCU->addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1); 270 271 if (unsigned isa = Asm->getISAEncoding()) { 272 SPCU->addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa); 273 } 274 275 return SPDie; 276} 277 278/// isSubprogramContext - Return true if Context is either a subprogram 279/// or another context nested inside a subprogram. 280static bool isSubprogramContext(const MDNode *Context) { 281 if (!Context) 282 return false; 283 DIDescriptor D(Context); 284 if (D.isSubprogram()) 285 return true; 286 if (D.isType()) 287 return isSubprogramContext(DIType(Context).getContext()); 288 return false; 289} 290 291/// updateSubprogramScopeDIE - Find DIE for the given subprogram and 292/// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes. 293/// If there are global variables in this scope then create and insert 294/// DIEs for these variables. 295DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) { 296 CompileUnit *SPCU = getCompileUnit(SPNode); 297 DIE *SPDie = SPCU->getDIE(SPNode); 298 299 assert(SPDie && "Unable to find subprogram DIE!"); 300 DISubprogram SP(SPNode); 301 302 DISubprogram SPDecl = SP.getFunctionDeclaration(); 303 if (SPDecl.isSubprogram()) 304 // Refer function declaration directly. 305 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4, 306 createSubprogramDIE(SPDecl)); 307 else { 308 // There is not any need to generate specification DIE for a function 309 // defined at compile unit level. If a function is defined inside another 310 // function then gdb prefers the definition at top level and but does not 311 // expect specification DIE in parent function. So avoid creating 312 // specification DIE for a function defined inside a function. 313 if (SP.isDefinition() && !SP.getContext().isCompileUnit() && 314 !SP.getContext().isFile() && 315 !isSubprogramContext(SP.getContext())) { 316 SPCU-> addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1); 317 318 // Add arguments. 319 DICompositeType SPTy = SP.getType(); 320 DIArray Args = SPTy.getTypeArray(); 321 unsigned SPTag = SPTy.getTag(); 322 if (SPTag == dwarf::DW_TAG_subroutine_type) 323 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) { 324 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter); 325 DIType ATy = DIType(DIType(Args.getElement(i))); 326 SPCU->addType(Arg, ATy); 327 if (ATy.isArtificial()) 328 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); 329 SPDie->addChild(Arg); 330 } 331 DIE *SPDeclDie = SPDie; 332 SPDie = new DIE(dwarf::DW_TAG_subprogram); 333 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4, 334 SPDeclDie); 335 SPCU->addDie(SPDie); 336 } 337 } 338 // Pick up abstract subprogram DIE. 339 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) { 340 SPDie = new DIE(dwarf::DW_TAG_subprogram); 341 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, 342 dwarf::DW_FORM_ref4, AbsSPDIE); 343 SPCU->addDie(SPDie); 344 } 345 346 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 347 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber())); 348 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, 349 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber())); 350 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo(); 351 MachineLocation Location(RI->getFrameRegister(*Asm->MF)); 352 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location); 353 354 return SPDie; 355} 356 357/// constructLexicalScope - Construct new DW_TAG_lexical_block 358/// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels. 359DIE *DwarfDebug::constructLexicalScopeDIE(LexicalScope *Scope) { 360 361 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block); 362 if (Scope->isAbstractScope()) 363 return ScopeDIE; 364 365 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges(); 366 if (Ranges.empty()) 367 return 0; 368 369 CompileUnit *TheCU = getCompileUnit(Scope->getScopeNode()); 370 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(); 371 if (Ranges.size() > 1) { 372 // .debug_range section has not been laid out yet. Emit offset in 373 // .debug_range as a uint, size 4, for now. emitDIE will handle 374 // DW_AT_ranges appropriately. 375 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4, 376 DebugRangeSymbols.size() 377 * Asm->getTargetData().getPointerSize()); 378 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(), 379 RE = Ranges.end(); RI != RE; ++RI) { 380 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first)); 381 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second)); 382 } 383 DebugRangeSymbols.push_back(NULL); 384 DebugRangeSymbols.push_back(NULL); 385 return ScopeDIE; 386 } 387 388 const MCSymbol *Start = getLabelBeforeInsn(RI->first); 389 const MCSymbol *End = getLabelAfterInsn(RI->second); 390 391 if (End == 0) return 0; 392 393 assert(Start->isDefined() && "Invalid starting label for an inlined scope!"); 394 assert(End->isDefined() && "Invalid end label for an inlined scope!"); 395 396 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start); 397 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End); 398 399 return ScopeDIE; 400} 401 402/// constructInlinedScopeDIE - This scope represents inlined body of 403/// a function. Construct DIE to represent this concrete inlined copy 404/// of the function. 405DIE *DwarfDebug::constructInlinedScopeDIE(LexicalScope *Scope) { 406 407 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges(); 408 assert (Ranges.empty() == false 409 && "LexicalScope does not have instruction markers!"); 410 411 if (!Scope->getScopeNode()) 412 return NULL; 413 DIScope DS(Scope->getScopeNode()); 414 DISubprogram InlinedSP = getDISubprogram(DS); 415 CompileUnit *TheCU = getCompileUnit(InlinedSP); 416 DIE *OriginDIE = TheCU->getDIE(InlinedSP); 417 if (!OriginDIE) { 418 DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram."); 419 return NULL; 420 } 421 422 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(); 423 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first); 424 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second); 425 426 if (StartLabel == 0 || EndLabel == 0) { 427 assert (0 && "Unexpected Start and End labels for a inlined scope!"); 428 return 0; 429 } 430 assert(StartLabel->isDefined() && 431 "Invalid starting label for an inlined scope!"); 432 assert(EndLabel->isDefined() && 433 "Invalid end label for an inlined scope!"); 434 435 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine); 436 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, 437 dwarf::DW_FORM_ref4, OriginDIE); 438 439 if (Ranges.size() > 1) { 440 // .debug_range section has not been laid out yet. Emit offset in 441 // .debug_range as a uint, size 4, for now. emitDIE will handle 442 // DW_AT_ranges appropriately. 443 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4, 444 DebugRangeSymbols.size() 445 * Asm->getTargetData().getPointerSize()); 446 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(), 447 RE = Ranges.end(); RI != RE; ++RI) { 448 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first)); 449 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second)); 450 } 451 DebugRangeSymbols.push_back(NULL); 452 DebugRangeSymbols.push_back(NULL); 453 } else { 454 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 455 StartLabel); 456 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, 457 EndLabel); 458 } 459 460 InlinedSubprogramDIEs.insert(OriginDIE); 461 462 // Track the start label for this inlined function. 463 //.debug_inlined section specification does not clearly state how 464 // to emit inlined scope that is split into multiple instruction ranges. 465 // For now, use first instruction range and emit low_pc/high_pc pair and 466 // corresponding .debug_inlined section entry for this pair. 467 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator 468 I = InlineInfo.find(InlinedSP); 469 470 if (I == InlineInfo.end()) { 471 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, 472 ScopeDIE)); 473 InlinedSPNodes.push_back(InlinedSP); 474 } else 475 I->second.push_back(std::make_pair(StartLabel, ScopeDIE)); 476 477 DILocation DL(Scope->getInlinedAt()); 478 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID()); 479 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber()); 480 481 return ScopeDIE; 482} 483 484/// isUnsignedDIType - Return true if type encoding is unsigned. 485static bool isUnsignedDIType(DIType Ty) { 486 DIDerivedType DTy(Ty); 487 if (DTy.Verify()) 488 return isUnsignedDIType(DTy.getTypeDerivedFrom()); 489 490 DIBasicType BTy(Ty); 491 if (BTy.Verify()) { 492 unsigned Encoding = BTy.getEncoding(); 493 if (Encoding == dwarf::DW_ATE_unsigned || 494 Encoding == dwarf::DW_ATE_unsigned_char) 495 return true; 496 } 497 return false; 498} 499 500/// constructVariableDIE - Construct a DIE for the given DbgVariable. 501DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, LexicalScope *Scope) { 502 StringRef Name = DV->getName(); 503 if (Name.empty()) 504 return NULL; 505 506 // Translate tag to proper Dwarf tag. The result variable is dropped for 507 // now. 508 unsigned Tag; 509 switch (DV->getTag()) { 510 case dwarf::DW_TAG_return_variable: 511 return NULL; 512 case dwarf::DW_TAG_arg_variable: 513 Tag = dwarf::DW_TAG_formal_parameter; 514 break; 515 case dwarf::DW_TAG_auto_variable: // fall thru 516 default: 517 Tag = dwarf::DW_TAG_variable; 518 break; 519 } 520 521 // Define variable debug information entry. 522 DIE *VariableDie = new DIE(Tag); 523 CompileUnit *VariableCU = getCompileUnit(DV->getVariable()); 524 DIE *AbsDIE = NULL; 525 DenseMap<const DbgVariable *, const DbgVariable *>::iterator 526 V2AVI = VarToAbstractVarMap.find(DV); 527 if (V2AVI != VarToAbstractVarMap.end()) 528 AbsDIE = V2AVI->second->getDIE(); 529 530 if (AbsDIE) 531 VariableCU->addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, 532 dwarf::DW_FORM_ref4, AbsDIE); 533 else { 534 VariableCU->addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, 535 Name); 536 VariableCU->addSourceLine(VariableDie, DV->getVariable()); 537 538 // Add variable type. 539 VariableCU->addType(VariableDie, DV->getType()); 540 } 541 542 if (Tag == dwarf::DW_TAG_formal_parameter && DV->getType().isArtificial()) 543 VariableCU->addUInt(VariableDie, dwarf::DW_AT_artificial, 544 dwarf::DW_FORM_flag, 1); 545 else if (DIVariable(DV->getVariable()).isArtificial()) 546 VariableCU->addUInt(VariableDie, dwarf::DW_AT_artificial, 547 dwarf::DW_FORM_flag, 1); 548 549 if (Scope->isAbstractScope()) { 550 DV->setDIE(VariableDie); 551 return VariableDie; 552 } 553 554 // Add variable address. 555 556 unsigned Offset = DV->getDotDebugLocOffset(); 557 if (Offset != ~0U) { 558 VariableCU->addLabel(VariableDie, dwarf::DW_AT_location, 559 dwarf::DW_FORM_data4, 560 Asm->GetTempSymbol("debug_loc", Offset)); 561 DV->setDIE(VariableDie); 562 UseDotDebugLocEntry.insert(VariableDie); 563 return VariableDie; 564 } 565 566 // Check if variable is described by a DBG_VALUE instruction. 567 DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI = 568 DbgVariableToDbgInstMap.find(DV); 569 if (DVI != DbgVariableToDbgInstMap.end()) { 570 const MachineInstr *DVInsn = DVI->second; 571 bool updated = false; 572 if (DVInsn->getNumOperands() == 3) { 573 if (DVInsn->getOperand(0).isReg()) { 574 const MachineOperand RegOp = DVInsn->getOperand(0); 575 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo(); 576 if (DVInsn->getOperand(1).isImm() && 577 TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) { 578 unsigned FrameReg = 0; 579 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering(); 580 int Offset = 581 TFI->getFrameIndexReference(*Asm->MF, 582 DVInsn->getOperand(1).getImm(), 583 FrameReg); 584 MachineLocation Location(FrameReg, Offset); 585 VariableCU->addVariableAddress(DV, VariableDie, Location); 586 587 } else if (RegOp.getReg()) 588 VariableCU->addVariableAddress(DV, VariableDie, 589 MachineLocation(RegOp.getReg())); 590 updated = true; 591 } 592 else if (DVInsn->getOperand(0).isImm()) 593 updated = 594 VariableCU->addConstantValue(VariableDie, DVInsn->getOperand(0), 595 DV->getType()); 596 else if (DVInsn->getOperand(0).isFPImm()) 597 updated = 598 VariableCU->addConstantFPValue(VariableDie, DVInsn->getOperand(0)); 599 else if (DVInsn->getOperand(0).isCImm()) 600 updated = 601 VariableCU->addConstantValue(VariableDie, 602 DVInsn->getOperand(0).getCImm(), 603 isUnsignedDIType(DV->getType())); 604 } else { 605 VariableCU->addVariableAddress(DV, VariableDie, 606 Asm->getDebugValueLocation(DVInsn)); 607 updated = true; 608 } 609 if (!updated) { 610 // If variableDie is not updated then DBG_VALUE instruction does not 611 // have valid variable info. 612 delete VariableDie; 613 return NULL; 614 } 615 DV->setDIE(VariableDie); 616 return VariableDie; 617 } 618 619 // .. else use frame index, if available. 620 int FI = 0; 621 if (findVariableFrameIndex(DV, &FI)) { 622 unsigned FrameReg = 0; 623 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering(); 624 int Offset = 625 TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg); 626 MachineLocation Location(FrameReg, Offset); 627 VariableCU->addVariableAddress(DV, VariableDie, Location); 628 } 629 630 DV->setDIE(VariableDie); 631 return VariableDie; 632 633} 634 635/// constructScopeDIE - Construct a DIE for this scope. 636DIE *DwarfDebug::constructScopeDIE(LexicalScope *Scope) { 637 if (!Scope || !Scope->getScopeNode()) 638 return NULL; 639 640 SmallVector <DIE *, 8> Children; 641 642 // Collect arguments for current function. 643 if (LScopes.isCurrentFunctionScope(Scope)) 644 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i) 645 if (DbgVariable *ArgDV = CurrentFnArguments[i]) 646 if (DIE *Arg = constructVariableDIE(ArgDV, Scope)) 647 Children.push_back(Arg); 648 649 // Collect lexical scope childrens first. 650 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope); 651 for (unsigned i = 0, N = Variables.size(); i < N; ++i) 652 if (DIE *Variable = constructVariableDIE(Variables[i], Scope)) 653 Children.push_back(Variable); 654 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren(); 655 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) 656 if (DIE *Nested = constructScopeDIE(Scopes[j])) 657 Children.push_back(Nested); 658 DIScope DS(Scope->getScopeNode()); 659 DIE *ScopeDIE = NULL; 660 if (Scope->getInlinedAt()) 661 ScopeDIE = constructInlinedScopeDIE(Scope); 662 else if (DS.isSubprogram()) { 663 ProcessedSPNodes.insert(DS); 664 if (Scope->isAbstractScope()) { 665 ScopeDIE = getCompileUnit(DS)->getDIE(DS); 666 // Note down abstract DIE. 667 if (ScopeDIE) 668 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE)); 669 } 670 else 671 ScopeDIE = updateSubprogramScopeDIE(DS); 672 } 673 else { 674 // There is no need to emit empty lexical block DIE. 675 if (Children.empty()) 676 return NULL; 677 ScopeDIE = constructLexicalScopeDIE(Scope); 678 } 679 680 if (!ScopeDIE) return NULL; 681 682 // Add children 683 for (SmallVector<DIE *, 8>::iterator I = Children.begin(), 684 E = Children.end(); I != E; ++I) 685 ScopeDIE->addChild(*I); 686 687 if (DS.isSubprogram()) 688 getCompileUnit(DS)->addPubTypes(DISubprogram(DS)); 689 690 return ScopeDIE; 691} 692 693/// GetOrCreateSourceID - Look up the source id with the given directory and 694/// source file names. If none currently exists, create a new id and insert it 695/// in the SourceIds map. This can update DirectoryNames and SourceFileNames 696/// maps as well. 697 698unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName, 699 StringRef DirName) { 700 // If FE did not provide a file name, then assume stdin. 701 if (FileName.empty()) 702 return GetOrCreateSourceID("<stdin>", StringRef()); 703 704 // MCStream expects full path name as filename. 705 if (!DirName.empty() && !sys::path::is_absolute(FileName)) { 706 SmallString<128> FullPathName = DirName; 707 sys::path::append(FullPathName, FileName); 708 // Here FullPathName will be copied into StringMap by GetOrCreateSourceID. 709 return GetOrCreateSourceID(StringRef(FullPathName), StringRef()); 710 } 711 712 StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName); 713 if (Entry.getValue()) 714 return Entry.getValue(); 715 716 unsigned SrcId = SourceIdMap.size(); 717 Entry.setValue(SrcId); 718 719 // Print out a .file directive to specify files for .loc directives. 720 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey()); 721 722 return SrcId; 723} 724 725/// constructCompileUnit - Create new CompileUnit for the given 726/// metadata node with tag DW_TAG_compile_unit. 727void DwarfDebug::constructCompileUnit(const MDNode *N) { 728 DICompileUnit DIUnit(N); 729 StringRef FN = DIUnit.getFilename(); 730 StringRef Dir = DIUnit.getDirectory(); 731 unsigned ID = GetOrCreateSourceID(FN, Dir); 732 733 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit); 734 CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this); 735 NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string, 736 DIUnit.getProducer()); 737 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 738 DIUnit.getLanguage()); 739 NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN); 740 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This 741 // simplifies debug range entries. 742 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0); 743 // DW_AT_stmt_list is a offset of line number information for this 744 // compile unit in debug_line section. 745 if(Asm->MAI->doesDwarfRequireRelocationForSectionOffset()) 746 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 747 Asm->GetTempSymbol("section_line")); 748 else 749 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0); 750 751 if (!Dir.empty()) 752 NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir); 753 if (DIUnit.isOptimized()) 754 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1); 755 756 StringRef Flags = DIUnit.getFlags(); 757 if (!Flags.empty()) 758 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, 759 Flags); 760 761 unsigned RVer = DIUnit.getRunTimeVersion(); 762 if (RVer) 763 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers, 764 dwarf::DW_FORM_data1, RVer); 765 766 if (!FirstCU) 767 FirstCU = NewCU; 768 CUMap.insert(std::make_pair(N, NewCU)); 769} 770 771/// getCompileUnit - Get CompileUnit DIE. 772CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const { 773 assert (N && "Invalid DwarfDebug::getCompileUnit argument!"); 774 DIDescriptor D(N); 775 const MDNode *CUNode = NULL; 776 if (D.isCompileUnit()) 777 CUNode = N; 778 else if (D.isSubprogram()) 779 CUNode = DISubprogram(N).getCompileUnit(); 780 else if (D.isType()) 781 CUNode = DIType(N).getCompileUnit(); 782 else if (D.isGlobalVariable()) 783 CUNode = DIGlobalVariable(N).getCompileUnit(); 784 else if (D.isVariable()) 785 CUNode = DIVariable(N).getCompileUnit(); 786 else if (D.isNameSpace()) 787 CUNode = DINameSpace(N).getCompileUnit(); 788 else if (D.isFile()) 789 CUNode = DIFile(N).getCompileUnit(); 790 else 791 return FirstCU; 792 793 DenseMap<const MDNode *, CompileUnit *>::const_iterator I 794 = CUMap.find(CUNode); 795 if (I == CUMap.end()) 796 return FirstCU; 797 return I->second; 798} 799 800// Return const expression if value is a GEP to access merged global 801// constant. e.g. 802// i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0) 803static const ConstantExpr *getMergedGlobalExpr(const Value *V) { 804 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V); 805 if (!CE || CE->getNumOperands() != 3 || 806 CE->getOpcode() != Instruction::GetElementPtr) 807 return NULL; 808 809 // First operand points to a global struct. 810 Value *Ptr = CE->getOperand(0); 811 if (!isa<GlobalValue>(Ptr) || 812 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType())) 813 return NULL; 814 815 // Second operand is zero. 816 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1)); 817 if (!CI || !CI->isZero()) 818 return NULL; 819 820 // Third operand is offset. 821 if (!isa<ConstantInt>(CE->getOperand(2))) 822 return NULL; 823 824 return CE; 825} 826 827/// constructGlobalVariableDIE - Construct global variable DIE. 828void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) { 829 DIGlobalVariable GV(N); 830 831 // If debug information is malformed then ignore it. 832 if (GV.Verify() == false) 833 return; 834 835 // Check for pre-existence. 836 CompileUnit *TheCU = getCompileUnit(N); 837 if (TheCU->getDIE(GV)) 838 return; 839 840 DIType GTy = GV.getType(); 841 DIE *VariableDIE = new DIE(GV.getTag()); 842 843 bool isGlobalVariable = GV.getGlobal() != NULL; 844 845 // Add name. 846 TheCU->addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string, 847 GV.getDisplayName()); 848 StringRef LinkageName = GV.getLinkageName(); 849 if (!LinkageName.empty() && isGlobalVariable) 850 TheCU->addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name, 851 dwarf::DW_FORM_string, 852 getRealLinkageName(LinkageName)); 853 // Add type. 854 TheCU->addType(VariableDIE, GTy); 855 856 // Add scoping info. 857 if (!GV.isLocalToUnit()) { 858 TheCU->addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1); 859 // Expose as global. 860 TheCU->addGlobal(GV.getName(), VariableDIE); 861 } 862 // Add line number info. 863 TheCU->addSourceLine(VariableDIE, GV); 864 // Add to map. 865 TheCU->insertDIE(N, VariableDIE); 866 // Add to context owner. 867 DIDescriptor GVContext = GV.getContext(); 868 TheCU->addToContextOwner(VariableDIE, GVContext); 869 // Add location. 870 if (isGlobalVariable) { 871 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 872 TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr); 873 TheCU->addLabel(Block, 0, dwarf::DW_FORM_udata, 874 Asm->Mang->getSymbol(GV.getGlobal())); 875 // Do not create specification DIE if context is either compile unit 876 // or a subprogram. 877 if (GV.isDefinition() && !GVContext.isCompileUnit() && 878 !GVContext.isFile() && !isSubprogramContext(GVContext)) { 879 // Create specification DIE. 880 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable); 881 TheCU->addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, 882 dwarf::DW_FORM_ref4, VariableDIE); 883 TheCU->addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block); 884 TheCU->addUInt(VariableDIE, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 885 1); 886 TheCU->addDie(VariableSpecDIE); 887 } else { 888 TheCU->addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block); 889 } 890 } else if (const ConstantInt *CI = 891 dyn_cast_or_null<ConstantInt>(GV.getConstant())) 892 TheCU->addConstantValue(VariableDIE, CI, isUnsignedDIType(GTy)); 893 else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) { 894 // GV is a merged global. 895 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 896 Value *Ptr = CE->getOperand(0); 897 TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr); 898 TheCU->addLabel(Block, 0, dwarf::DW_FORM_udata, 899 Asm->Mang->getSymbol(cast<GlobalValue>(Ptr))); 900 TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 901 SmallVector<Value*, 3> Idx(CE->op_begin()+1, CE->op_end()); 902 TheCU->addUInt(Block, 0, dwarf::DW_FORM_udata, 903 Asm->getTargetData().getIndexedOffset(Ptr->getType(), Idx)); 904 TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus); 905 TheCU->addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block); 906 } 907 908 return; 909} 910 911/// construct SubprogramDIE - Construct subprogram DIE. 912void DwarfDebug::constructSubprogramDIE(const MDNode *N) { 913 DISubprogram SP(N); 914 915 // Check for pre-existence. 916 CompileUnit *TheCU = getCompileUnit(N); 917 if (TheCU->getDIE(N)) 918 return; 919 920 if (!SP.isDefinition()) 921 // This is a method declaration which will be handled while constructing 922 // class type. 923 return; 924 925 DIE *SubprogramDie = createSubprogramDIE(SP); 926 927 // Add to map. 928 TheCU->insertDIE(N, SubprogramDie); 929 930 // Add to context owner. 931 TheCU->addToContextOwner(SubprogramDie, SP.getContext()); 932 933 // Expose as global. 934 TheCU->addGlobal(SP.getName(), SubprogramDie); 935 936 return; 937} 938 939/// beginModule - Emit all Dwarf sections that should come prior to the 940/// content. Create global DIEs and emit initial debug info sections. 941/// This is invoked by the target AsmPrinter. 942void DwarfDebug::beginModule(Module *M) { 943 if (DisableDebugInfoPrinting) 944 return; 945 946 // If module has named metadata anchors then use them, otherwise scan the 947 // module using debug info finder to collect debug info. 948 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu"); 949 if (CU_Nodes) { 950 951 NamedMDNode *GV_Nodes = M->getNamedMetadata("llvm.dbg.gv"); 952 NamedMDNode *SP_Nodes = M->getNamedMetadata("llvm.dbg.sp"); 953 if (!GV_Nodes && !SP_Nodes) 954 // If there are not any global variables or any functions then 955 // there is not any debug info in this module. 956 return; 957 958 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) 959 constructCompileUnit(CU_Nodes->getOperand(i)); 960 961 if (GV_Nodes) 962 for (unsigned i = 0, e = GV_Nodes->getNumOperands(); i != e; ++i) 963 constructGlobalVariableDIE(GV_Nodes->getOperand(i)); 964 965 if (SP_Nodes) 966 for (unsigned i = 0, e = SP_Nodes->getNumOperands(); i != e; ++i) 967 constructSubprogramDIE(SP_Nodes->getOperand(i)); 968 969 } else { 970 971 DebugInfoFinder DbgFinder; 972 DbgFinder.processModule(*M); 973 974 bool HasDebugInfo = false; 975 // Scan all the compile-units to see if there are any marked as the main 976 // unit. If not, we do not generate debug info. 977 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(), 978 E = DbgFinder.compile_unit_end(); I != E; ++I) { 979 if (DICompileUnit(*I).isMain()) { 980 HasDebugInfo = true; 981 break; 982 } 983 } 984 if (!HasDebugInfo) return; 985 986 // Create all the compile unit DIEs. 987 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(), 988 E = DbgFinder.compile_unit_end(); I != E; ++I) 989 constructCompileUnit(*I); 990 991 // Create DIEs for each global variable. 992 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(), 993 E = DbgFinder.global_variable_end(); I != E; ++I) 994 constructGlobalVariableDIE(*I); 995 996 // Create DIEs for each subprogram. 997 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(), 998 E = DbgFinder.subprogram_end(); I != E; ++I) 999 constructSubprogramDIE(*I); 1000 } 1001 1002 // Tell MMI that we have debug info. 1003 MMI->setDebugInfoAvailability(true); 1004 1005 // Emit initial sections. 1006 EmitSectionLabels(); 1007 1008 //getOrCreateTypeDIE 1009 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum")) 1010 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 1011 DIType Ty(NMD->getOperand(i)); 1012 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty); 1013 } 1014 1015 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty")) 1016 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 1017 DIType Ty(NMD->getOperand(i)); 1018 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty); 1019 } 1020 1021 // Prime section data. 1022 SectionMap.insert(Asm->getObjFileLowering().getTextSection()); 1023} 1024 1025/// endModule - Emit all Dwarf sections that should come after the content. 1026/// 1027void DwarfDebug::endModule() { 1028 if (!FirstCU) return; 1029 const Module *M = MMI->getModule(); 1030 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap; 1031 if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) { 1032 for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) { 1033 if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue; 1034 DISubprogram SP(AllSPs->getOperand(SI)); 1035 if (!SP.Verify()) continue; 1036 1037 // Collect info for variables that were optimized out. 1038 if (!SP.isDefinition()) continue; 1039 StringRef FName = SP.getLinkageName(); 1040 if (FName.empty()) 1041 FName = SP.getName(); 1042 NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName); 1043 if (!NMD) continue; 1044 unsigned E = NMD->getNumOperands(); 1045 if (!E) continue; 1046 LexicalScope *Scope = new LexicalScope(NULL, DIDescriptor(SP), NULL, 1047 false); 1048 DeadFnScopeMap[SP] = Scope; 1049 SmallVector<DbgVariable *, 8> Variables; 1050 for (unsigned I = 0; I != E; ++I) { 1051 DIVariable DV(NMD->getOperand(I)); 1052 if (!DV.Verify()) continue; 1053 Variables.push_back(new DbgVariable(DV)); 1054 } 1055 1056 // Construct subprogram DIE and add variables DIEs. 1057 constructSubprogramDIE(SP); 1058 DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP); 1059 for (unsigned i = 0, N = Variables.size(); i < N; ++i) { 1060 if (DIE *VariableDIE = constructVariableDIE(Variables[i], Scope)) 1061 ScopeDIE->addChild(VariableDIE); 1062 } 1063 } 1064 } 1065 1066 // Attach DW_AT_inline attribute with inlined subprogram DIEs. 1067 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(), 1068 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) { 1069 DIE *ISP = *AI; 1070 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined); 1071 } 1072 1073 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(), 1074 CE = ContainingTypeMap.end(); CI != CE; ++CI) { 1075 DIE *SPDie = CI->first; 1076 const MDNode *N = dyn_cast_or_null<MDNode>(CI->second); 1077 if (!N) continue; 1078 DIE *NDie = getCompileUnit(N)->getDIE(N); 1079 if (!NDie) continue; 1080 getCompileUnit(N)->addDIEEntry(SPDie, dwarf::DW_AT_containing_type, 1081 dwarf::DW_FORM_ref4, NDie); 1082 } 1083 1084 // Standard sections final addresses. 1085 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection()); 1086 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end")); 1087 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection()); 1088 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end")); 1089 1090 // End text sections. 1091 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) { 1092 Asm->OutStreamer.SwitchSection(SectionMap[i]); 1093 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i)); 1094 } 1095 1096 // Compute DIE offsets and sizes. 1097 computeSizeAndOffsets(); 1098 1099 // Emit all the DIEs into a debug info section 1100 emitDebugInfo(); 1101 1102 // Corresponding abbreviations into a abbrev section. 1103 emitAbbreviations(); 1104 1105 // Emit info into a debug pubnames section. 1106 emitDebugPubNames(); 1107 1108 // Emit info into a debug pubtypes section. 1109 emitDebugPubTypes(); 1110 1111 // Emit info into a debug loc section. 1112 emitDebugLoc(); 1113 1114 // Emit info into a debug aranges section. 1115 EmitDebugARanges(); 1116 1117 // Emit info into a debug ranges section. 1118 emitDebugRanges(); 1119 1120 // Emit info into a debug macinfo section. 1121 emitDebugMacInfo(); 1122 1123 // Emit inline info. 1124 emitDebugInlineInfo(); 1125 1126 // Emit info into a debug str section. 1127 emitDebugStr(); 1128 1129 // clean up. 1130 DeleteContainerSeconds(DeadFnScopeMap); 1131 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(), 1132 E = CUMap.end(); I != E; ++I) 1133 delete I->second; 1134 FirstCU = NULL; // Reset for the next Module, if any. 1135} 1136 1137/// findAbstractVariable - Find abstract variable, if any, associated with Var. 1138DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV, 1139 DebugLoc ScopeLoc) { 1140 LLVMContext &Ctx = DV->getContext(); 1141 // More then one inlined variable corresponds to one abstract variable. 1142 DIVariable Var = cleanseInlinedVariable(DV, Ctx); 1143 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var); 1144 if (AbsDbgVariable) 1145 return AbsDbgVariable; 1146 1147 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx)); 1148 if (!Scope) 1149 return NULL; 1150 1151 AbsDbgVariable = new DbgVariable(Var); 1152 addScopeVariable(Scope, AbsDbgVariable); 1153 AbstractVariables[Var] = AbsDbgVariable; 1154 return AbsDbgVariable; 1155} 1156 1157/// addCurrentFnArgument - If Var is a current function argument then add 1158/// it to CurrentFnArguments list. 1159bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF, 1160 DbgVariable *Var, LexicalScope *Scope) { 1161 if (!LScopes.isCurrentFunctionScope(Scope)) 1162 return false; 1163 DIVariable DV = Var->getVariable(); 1164 if (DV.getTag() != dwarf::DW_TAG_arg_variable) 1165 return false; 1166 unsigned ArgNo = DV.getArgNumber(); 1167 if (ArgNo == 0) 1168 return false; 1169 1170 size_t Size = CurrentFnArguments.size(); 1171 if (Size == 0) 1172 CurrentFnArguments.resize(MF->getFunction()->arg_size()); 1173 // llvm::Function argument size is not good indicator of how many 1174 // arguments does the function have at source level. 1175 if (ArgNo > Size) 1176 CurrentFnArguments.resize(ArgNo * 2); 1177 CurrentFnArguments[ArgNo - 1] = Var; 1178 return true; 1179} 1180 1181/// collectVariableInfoFromMMITable - Collect variable information from 1182/// side table maintained by MMI. 1183void 1184DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF, 1185 SmallPtrSet<const MDNode *, 16> &Processed) { 1186 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo(); 1187 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(), 1188 VE = VMap.end(); VI != VE; ++VI) { 1189 const MDNode *Var = VI->first; 1190 if (!Var) continue; 1191 Processed.insert(Var); 1192 DIVariable DV(Var); 1193 const std::pair<unsigned, DebugLoc> &VP = VI->second; 1194 1195 LexicalScope *Scope = LScopes.findLexicalScope(VP.second); 1196 1197 // If variable scope is not found then skip this variable. 1198 if (Scope == 0) 1199 continue; 1200 1201 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second); 1202 DbgVariable *RegVar = new DbgVariable(DV); 1203 recordVariableFrameIndex(RegVar, VP.first); 1204 if (!addCurrentFnArgument(MF, RegVar, Scope)) 1205 addScopeVariable(Scope, RegVar); 1206 if (AbsDbgVariable) { 1207 recordVariableFrameIndex(AbsDbgVariable, VP.first); 1208 VarToAbstractVarMap[RegVar] = AbsDbgVariable; 1209 } 1210 } 1211} 1212 1213/// isDbgValueInDefinedReg - Return true if debug value, encoded by 1214/// DBG_VALUE instruction, is in a defined reg. 1215static bool isDbgValueInDefinedReg(const MachineInstr *MI) { 1216 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!"); 1217 return MI->getNumOperands() == 3 && 1218 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() && 1219 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0; 1220} 1221 1222/// getDebugLocEntry - Get .debug_loc entry for the instruction range starting 1223/// at MI. 1224static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm, 1225 const MCSymbol *FLabel, 1226 const MCSymbol *SLabel, 1227 const MachineInstr *MI) { 1228 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata(); 1229 1230 if (MI->getNumOperands() != 3) { 1231 MachineLocation MLoc = Asm->getDebugValueLocation(MI); 1232 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var); 1233 } 1234 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) { 1235 MachineLocation MLoc; 1236 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm()); 1237 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var); 1238 } 1239 if (MI->getOperand(0).isImm()) 1240 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm()); 1241 if (MI->getOperand(0).isFPImm()) 1242 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm()); 1243 if (MI->getOperand(0).isCImm()) 1244 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm()); 1245 1246 assert (0 && "Unexpected 3 operand DBG_VALUE instruction!"); 1247 return DotDebugLocEntry(); 1248} 1249 1250/// collectVariableInfo - Find variables for each lexical scope. 1251void 1252DwarfDebug::collectVariableInfo(const MachineFunction *MF, 1253 SmallPtrSet<const MDNode *, 16> &Processed) { 1254 1255 /// collection info from MMI table. 1256 collectVariableInfoFromMMITable(MF, Processed); 1257 1258 for (SmallVectorImpl<const MDNode*>::const_iterator 1259 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE; 1260 ++UVI) { 1261 const MDNode *Var = *UVI; 1262 if (Processed.count(Var)) 1263 continue; 1264 1265 // History contains relevant DBG_VALUE instructions for Var and instructions 1266 // clobbering it. 1267 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var]; 1268 if (History.empty()) 1269 continue; 1270 const MachineInstr *MInsn = History.front(); 1271 1272 DIVariable DV(Var); 1273 LexicalScope *Scope = NULL; 1274 if (DV.getTag() == dwarf::DW_TAG_arg_variable && 1275 DISubprogram(DV.getContext()).describes(MF->getFunction())) 1276 Scope = LScopes.getCurrentFunctionScope(); 1277 else { 1278 if (DV.getVersion() <= LLVMDebugVersion9) 1279 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc()); 1280 else { 1281 if (MDNode *IA = DV.getInlinedAt()) 1282 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA)); 1283 else 1284 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1))); 1285 } 1286 } 1287 // If variable scope is not found then skip this variable. 1288 if (!Scope) 1289 continue; 1290 1291 Processed.insert(DV); 1292 assert(MInsn->isDebugValue() && "History must begin with debug value"); 1293 DbgVariable *RegVar = new DbgVariable(DV); 1294 if (!addCurrentFnArgument(MF, RegVar, Scope)) 1295 addScopeVariable(Scope, RegVar); 1296 if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) { 1297 DbgVariableToDbgInstMap[AbsVar] = MInsn; 1298 VarToAbstractVarMap[RegVar] = AbsVar; 1299 } 1300 1301 // Simple ranges that are fully coalesced. 1302 if (History.size() <= 1 || (History.size() == 2 && 1303 MInsn->isIdenticalTo(History.back()))) { 1304 DbgVariableToDbgInstMap[RegVar] = MInsn; 1305 continue; 1306 } 1307 1308 // handle multiple DBG_VALUE instructions describing one variable. 1309 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size()); 1310 1311 for (SmallVectorImpl<const MachineInstr*>::const_iterator 1312 HI = History.begin(), HE = History.end(); HI != HE; ++HI) { 1313 const MachineInstr *Begin = *HI; 1314 assert(Begin->isDebugValue() && "Invalid History entry"); 1315 1316 // Check if DBG_VALUE is truncating a range. 1317 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() 1318 && !Begin->getOperand(0).getReg()) 1319 continue; 1320 1321 // Compute the range for a register location. 1322 const MCSymbol *FLabel = getLabelBeforeInsn(Begin); 1323 const MCSymbol *SLabel = 0; 1324 1325 if (HI + 1 == HE) 1326 // If Begin is the last instruction in History then its value is valid 1327 // until the end of the function. 1328 SLabel = FunctionEndSym; 1329 else { 1330 const MachineInstr *End = HI[1]; 1331 DEBUG(dbgs() << "DotDebugLoc Pair:\n" 1332 << "\t" << *Begin << "\t" << *End << "\n"); 1333 if (End->isDebugValue()) 1334 SLabel = getLabelBeforeInsn(End); 1335 else { 1336 // End is a normal instruction clobbering the range. 1337 SLabel = getLabelAfterInsn(End); 1338 assert(SLabel && "Forgot label after clobber instruction"); 1339 ++HI; 1340 } 1341 } 1342 1343 // The value is valid until the next DBG_VALUE or clobber. 1344 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin)); 1345 } 1346 DotDebugLocEntries.push_back(DotDebugLocEntry()); 1347 } 1348 1349 // Collect info for variables that were optimized out. 1350 const Function *F = MF->getFunction(); 1351 if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) { 1352 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 1353 DIVariable DV(cast<MDNode>(NMD->getOperand(i))); 1354 if (!DV || !Processed.insert(DV)) 1355 continue; 1356 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) 1357 addScopeVariable(Scope, new DbgVariable(DV)); 1358 } 1359 } 1360} 1361 1362/// getLabelBeforeInsn - Return Label preceding the instruction. 1363const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) { 1364 MCSymbol *Label = LabelsBeforeInsn.lookup(MI); 1365 assert(Label && "Didn't insert label before instruction"); 1366 return Label; 1367} 1368 1369/// getLabelAfterInsn - Return Label immediately following the instruction. 1370const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) { 1371 return LabelsAfterInsn.lookup(MI); 1372} 1373 1374/// beginInstruction - Process beginning of an instruction. 1375void DwarfDebug::beginInstruction(const MachineInstr *MI) { 1376 // Check if source location changes, but ignore DBG_VALUE locations. 1377 if (!MI->isDebugValue()) { 1378 DebugLoc DL = MI->getDebugLoc(); 1379 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) { 1380 unsigned Flags = DWARF2_FLAG_IS_STMT; 1381 PrevInstLoc = DL; 1382 if (DL == PrologEndLoc) { 1383 Flags |= DWARF2_FLAG_PROLOGUE_END; 1384 PrologEndLoc = DebugLoc(); 1385 } 1386 if (!DL.isUnknown()) { 1387 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext()); 1388 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags); 1389 } else 1390 recordSourceLine(0, 0, 0, 0); 1391 } 1392 } 1393 1394 // Insert labels where requested. 1395 DenseMap<const MachineInstr*, MCSymbol*>::iterator I = 1396 LabelsBeforeInsn.find(MI); 1397 1398 // No label needed. 1399 if (I == LabelsBeforeInsn.end()) 1400 return; 1401 1402 // Label already assigned. 1403 if (I->second) 1404 return; 1405 1406 if (!PrevLabel) { 1407 PrevLabel = MMI->getContext().CreateTempSymbol(); 1408 Asm->OutStreamer.EmitLabel(PrevLabel); 1409 } 1410 I->second = PrevLabel; 1411} 1412 1413/// endInstruction - Process end of an instruction. 1414void DwarfDebug::endInstruction(const MachineInstr *MI) { 1415 // Don't create a new label after DBG_VALUE instructions. 1416 // They don't generate code. 1417 if (!MI->isDebugValue()) 1418 PrevLabel = 0; 1419 1420 DenseMap<const MachineInstr*, MCSymbol*>::iterator I = 1421 LabelsAfterInsn.find(MI); 1422 1423 // No label needed. 1424 if (I == LabelsAfterInsn.end()) 1425 return; 1426 1427 // Label already assigned. 1428 if (I->second) 1429 return; 1430 1431 // We need a label after this instruction. 1432 if (!PrevLabel) { 1433 PrevLabel = MMI->getContext().CreateTempSymbol(); 1434 Asm->OutStreamer.EmitLabel(PrevLabel); 1435 } 1436 I->second = PrevLabel; 1437} 1438 1439/// identifyScopeMarkers() - 1440/// Each LexicalScope has first instruction and last instruction to mark 1441/// beginning and end of a scope respectively. Create an inverse map that list 1442/// scopes starts (and ends) with an instruction. One instruction may start (or 1443/// end) multiple scopes. Ignore scopes that are not reachable. 1444void DwarfDebug::identifyScopeMarkers() { 1445 SmallVector<LexicalScope *, 4> WorkList; 1446 WorkList.push_back(LScopes.getCurrentFunctionScope()); 1447 while (!WorkList.empty()) { 1448 LexicalScope *S = WorkList.pop_back_val(); 1449 1450 const SmallVector<LexicalScope *, 4> &Children = S->getChildren(); 1451 if (!Children.empty()) 1452 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(), 1453 SE = Children.end(); SI != SE; ++SI) 1454 WorkList.push_back(*SI); 1455 1456 if (S->isAbstractScope()) 1457 continue; 1458 1459 const SmallVector<InsnRange, 4> &Ranges = S->getRanges(); 1460 if (Ranges.empty()) 1461 continue; 1462 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(), 1463 RE = Ranges.end(); RI != RE; ++RI) { 1464 assert(RI->first && "InsnRange does not have first instruction!"); 1465 assert(RI->second && "InsnRange does not have second instruction!"); 1466 requestLabelBeforeInsn(RI->first); 1467 requestLabelAfterInsn(RI->second); 1468 } 1469 } 1470} 1471 1472/// getScopeNode - Get MDNode for DebugLoc's scope. 1473static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) { 1474 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx)) 1475 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx); 1476 return DL.getScope(Ctx); 1477} 1478 1479/// getFnDebugLoc - Walk up the scope chain of given debug loc and find 1480/// line number info for the function. 1481static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) { 1482 const MDNode *Scope = getScopeNode(DL, Ctx); 1483 DISubprogram SP = getDISubprogram(Scope); 1484 if (SP.Verify()) 1485 return DebugLoc::get(SP.getLineNumber(), 0, SP); 1486 return DebugLoc(); 1487} 1488 1489/// beginFunction - Gather pre-function debug information. Assumes being 1490/// emitted immediately after the function entry point. 1491void DwarfDebug::beginFunction(const MachineFunction *MF) { 1492 if (!MMI->hasDebugInfo()) return; 1493 LScopes.initialize(*MF); 1494 if (LScopes.empty()) return; 1495 identifyScopeMarkers(); 1496 1497 FunctionBeginSym = Asm->GetTempSymbol("func_begin", 1498 Asm->getFunctionNumber()); 1499 // Assumes in correct section after the entry point. 1500 Asm->OutStreamer.EmitLabel(FunctionBeginSym); 1501 1502 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned"); 1503 1504 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo(); 1505 /// LiveUserVar - Map physreg numbers to the MDNode they contain. 1506 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs()); 1507 1508 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); 1509 I != E; ++I) { 1510 bool AtBlockEntry = true; 1511 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end(); 1512 II != IE; ++II) { 1513 const MachineInstr *MI = II; 1514 1515 if (MI->isDebugValue()) { 1516 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!"); 1517 1518 // Keep track of user variables. 1519 const MDNode *Var = 1520 MI->getOperand(MI->getNumOperands() - 1).getMetadata(); 1521 1522 // Variable is in a register, we need to check for clobbers. 1523 if (isDbgValueInDefinedReg(MI)) 1524 LiveUserVar[MI->getOperand(0).getReg()] = Var; 1525 1526 // Check the history of this variable. 1527 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var]; 1528 if (History.empty()) { 1529 UserVariables.push_back(Var); 1530 // The first mention of a function argument gets the FunctionBeginSym 1531 // label, so arguments are visible when breaking at function entry. 1532 DIVariable DV(Var); 1533 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable && 1534 DISubprogram(getDISubprogram(DV.getContext())) 1535 .describes(MF->getFunction())) 1536 LabelsBeforeInsn[MI] = FunctionBeginSym; 1537 } else { 1538 // We have seen this variable before. Try to coalesce DBG_VALUEs. 1539 const MachineInstr *Prev = History.back(); 1540 if (Prev->isDebugValue()) { 1541 // Coalesce identical entries at the end of History. 1542 if (History.size() >= 2 && 1543 Prev->isIdenticalTo(History[History.size() - 2])) { 1544 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n" 1545 << "\t" << *Prev 1546 << "\t" << *History[History.size() - 2] << "\n"); 1547 History.pop_back(); 1548 } 1549 1550 // Terminate old register assignments that don't reach MI; 1551 MachineFunction::const_iterator PrevMBB = Prev->getParent(); 1552 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) && 1553 isDbgValueInDefinedReg(Prev)) { 1554 // Previous register assignment needs to terminate at the end of 1555 // its basic block. 1556 MachineBasicBlock::const_iterator LastMI = 1557 PrevMBB->getLastNonDebugInstr(); 1558 if (LastMI == PrevMBB->end()) { 1559 // Drop DBG_VALUE for empty range. 1560 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n" 1561 << "\t" << *Prev << "\n"); 1562 History.pop_back(); 1563 } 1564 else { 1565 // Terminate after LastMI. 1566 History.push_back(LastMI); 1567 } 1568 } 1569 } 1570 } 1571 History.push_back(MI); 1572 } else { 1573 // Not a DBG_VALUE instruction. 1574 if (!MI->isLabel()) 1575 AtBlockEntry = false; 1576 1577 // First known non DBG_VALUE location marks beginning of function 1578 // body. 1579 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()) 1580 PrologEndLoc = MI->getDebugLoc(); 1581 1582 // Check if the instruction clobbers any registers with debug vars. 1583 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(), 1584 MOE = MI->operands_end(); MOI != MOE; ++MOI) { 1585 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg()) 1586 continue; 1587 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg()); 1588 unsigned Reg = *AI; ++AI) { 1589 const MDNode *Var = LiveUserVar[Reg]; 1590 if (!Var) 1591 continue; 1592 // Reg is now clobbered. 1593 LiveUserVar[Reg] = 0; 1594 1595 // Was MD last defined by a DBG_VALUE referring to Reg? 1596 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var); 1597 if (HistI == DbgValues.end()) 1598 continue; 1599 SmallVectorImpl<const MachineInstr*> &History = HistI->second; 1600 if (History.empty()) 1601 continue; 1602 const MachineInstr *Prev = History.back(); 1603 // Sanity-check: Register assignments are terminated at the end of 1604 // their block. 1605 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent()) 1606 continue; 1607 // Is the variable still in Reg? 1608 if (!isDbgValueInDefinedReg(Prev) || 1609 Prev->getOperand(0).getReg() != Reg) 1610 continue; 1611 // Var is clobbered. Make sure the next instruction gets a label. 1612 History.push_back(MI); 1613 } 1614 } 1615 } 1616 } 1617 } 1618 1619 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end(); 1620 I != E; ++I) { 1621 SmallVectorImpl<const MachineInstr*> &History = I->second; 1622 if (History.empty()) 1623 continue; 1624 1625 // Make sure the final register assignments are terminated. 1626 const MachineInstr *Prev = History.back(); 1627 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) { 1628 const MachineBasicBlock *PrevMBB = Prev->getParent(); 1629 MachineBasicBlock::const_iterator LastMI = 1630 PrevMBB->getLastNonDebugInstr(); 1631 if (LastMI == PrevMBB->end()) 1632 // Drop DBG_VALUE for empty range. 1633 History.pop_back(); 1634 else { 1635 // Terminate after LastMI. 1636 History.push_back(LastMI); 1637 } 1638 } 1639 // Request labels for the full history. 1640 for (unsigned i = 0, e = History.size(); i != e; ++i) { 1641 const MachineInstr *MI = History[i]; 1642 if (MI->isDebugValue()) 1643 requestLabelBeforeInsn(MI); 1644 else 1645 requestLabelAfterInsn(MI); 1646 } 1647 } 1648 1649 PrevInstLoc = DebugLoc(); 1650 PrevLabel = FunctionBeginSym; 1651 1652 // Record beginning of function. 1653 if (!PrologEndLoc.isUnknown()) { 1654 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc, 1655 MF->getFunction()->getContext()); 1656 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(), 1657 FnStartDL.getScope(MF->getFunction()->getContext()), 1658 DWARF2_FLAG_IS_STMT); 1659 } 1660} 1661 1662void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) { 1663// SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS); 1664 ScopeVariables[LS].push_back(Var); 1665// Vars.push_back(Var); 1666} 1667 1668/// endFunction - Gather and emit post-function debug information. 1669/// 1670void DwarfDebug::endFunction(const MachineFunction *MF) { 1671 if (!MMI->hasDebugInfo() || LScopes.empty()) return; 1672 1673 // Define end label for subprogram. 1674 FunctionEndSym = Asm->GetTempSymbol("func_end", 1675 Asm->getFunctionNumber()); 1676 // Assumes in correct section after the entry point. 1677 Asm->OutStreamer.EmitLabel(FunctionEndSym); 1678 1679 SmallPtrSet<const MDNode *, 16> ProcessedVars; 1680 collectVariableInfo(MF, ProcessedVars); 1681 1682 // Construct abstract scopes. 1683 SmallVector<LexicalScope *, 4> &AList = LScopes.getAbstractScopesList(); 1684 for (SmallVector<LexicalScope *, 4>::iterator AI = AList.begin(), 1685 AE = AList.end(); AI != AE; ++AI) { 1686 DISubprogram SP((*AI)->getScopeNode()); 1687 if (SP.Verify()) { 1688 // Collect info for variables that were optimized out. 1689 StringRef FName = SP.getLinkageName(); 1690 if (FName.empty()) 1691 FName = SP.getName(); 1692 if (NamedMDNode *NMD = 1693 getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) { 1694 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 1695 DIVariable DV(cast<MDNode>(NMD->getOperand(i))); 1696 if (!DV || !ProcessedVars.insert(DV)) 1697 continue; 1698 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext())) 1699 addScopeVariable(Scope, new DbgVariable(DV)); 1700 } 1701 } 1702 } 1703 if (ProcessedSPNodes.count((*AI)->getScopeNode()) == 0) 1704 constructScopeDIE(*AI); 1705 } 1706 1707 DIE *CurFnDIE = constructScopeDIE(LScopes.getCurrentFunctionScope()); 1708 1709 if (!DisableFramePointerElim(*MF)) { 1710 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1711 CompileUnit *TheCU = getCompileUnit(FnScope->getScopeNode()); 1712 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr, 1713 dwarf::DW_FORM_flag, 1); 1714 } 1715 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(), 1716 MMI->getFrameMoves())); 1717 1718 // Clear debug info 1719 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator 1720 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I) 1721 DeleteContainerPointers(I->second); 1722 ScopeVariables.clear(); 1723 DeleteContainerPointers(CurrentFnArguments); 1724 DbgVariableToFrameIndexMap.clear(); 1725 VarToAbstractVarMap.clear(); 1726 DbgVariableToDbgInstMap.clear(); 1727 UserVariables.clear(); 1728 DbgValues.clear(); 1729 AbstractVariables.clear(); 1730 LabelsBeforeInsn.clear(); 1731 LabelsAfterInsn.clear(); 1732 PrevLabel = NULL; 1733} 1734 1735/// recordVariableFrameIndex - Record a variable's index. 1736void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) { 1737 assert (V && "Invalid DbgVariable!"); 1738 DbgVariableToFrameIndexMap[V] = Index; 1739} 1740 1741/// findVariableFrameIndex - Return true if frame index for the variable 1742/// is found. Update FI to hold value of the index. 1743bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) { 1744 assert (V && "Invalid DbgVariable!"); 1745 DenseMap<const DbgVariable *, int>::iterator I = 1746 DbgVariableToFrameIndexMap.find(V); 1747 if (I == DbgVariableToFrameIndexMap.end()) 1748 return false; 1749 *FI = I->second; 1750 return true; 1751} 1752 1753/// recordSourceLine - Register a source line with debug info. Returns the 1754/// unique label that was emitted and which provides correspondence to 1755/// the source line list. 1756void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S, 1757 unsigned Flags) { 1758 StringRef Fn; 1759 StringRef Dir; 1760 unsigned Src = 1; 1761 if (S) { 1762 DIDescriptor Scope(S); 1763 1764 if (Scope.isCompileUnit()) { 1765 DICompileUnit CU(S); 1766 Fn = CU.getFilename(); 1767 Dir = CU.getDirectory(); 1768 } else if (Scope.isFile()) { 1769 DIFile F(S); 1770 Fn = F.getFilename(); 1771 Dir = F.getDirectory(); 1772 } else if (Scope.isSubprogram()) { 1773 DISubprogram SP(S); 1774 Fn = SP.getFilename(); 1775 Dir = SP.getDirectory(); 1776 } else if (Scope.isLexicalBlock()) { 1777 DILexicalBlock DB(S); 1778 Fn = DB.getFilename(); 1779 Dir = DB.getDirectory(); 1780 } else 1781 assert(0 && "Unexpected scope info"); 1782 1783 Src = GetOrCreateSourceID(Fn, Dir); 1784 } 1785 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn); 1786} 1787 1788//===----------------------------------------------------------------------===// 1789// Emit Methods 1790//===----------------------------------------------------------------------===// 1791 1792/// computeSizeAndOffset - Compute the size and offset of a DIE. 1793/// 1794unsigned 1795DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) { 1796 // Get the children. 1797 const std::vector<DIE *> &Children = Die->getChildren(); 1798 1799 // If not last sibling and has children then add sibling offset attribute. 1800 if (!Last && !Children.empty()) 1801 Die->addSiblingOffset(DIEValueAllocator); 1802 1803 // Record the abbreviation. 1804 assignAbbrevNumber(Die->getAbbrev()); 1805 1806 // Get the abbreviation for this DIE. 1807 unsigned AbbrevNumber = Die->getAbbrevNumber(); 1808 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1]; 1809 1810 // Set DIE offset 1811 Die->setOffset(Offset); 1812 1813 // Start the size with the size of abbreviation code. 1814 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber); 1815 1816 const SmallVector<DIEValue*, 32> &Values = Die->getValues(); 1817 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData(); 1818 1819 // Size the DIE attribute values. 1820 for (unsigned i = 0, N = Values.size(); i < N; ++i) 1821 // Size attribute value. 1822 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm()); 1823 1824 // Size the DIE children if any. 1825 if (!Children.empty()) { 1826 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes && 1827 "Children flag not set"); 1828 1829 for (unsigned j = 0, M = Children.size(); j < M; ++j) 1830 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M); 1831 1832 // End of children marker. 1833 Offset += sizeof(int8_t); 1834 } 1835 1836 Die->setSize(Offset - Die->getOffset()); 1837 return Offset; 1838} 1839 1840/// computeSizeAndOffsets - Compute the size and offset of all the DIEs. 1841/// 1842void DwarfDebug::computeSizeAndOffsets() { 1843 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(), 1844 E = CUMap.end(); I != E; ++I) { 1845 // Compute size of compile unit header. 1846 unsigned Offset = 1847 sizeof(int32_t) + // Length of Compilation Unit Info 1848 sizeof(int16_t) + // DWARF version number 1849 sizeof(int32_t) + // Offset Into Abbrev. Section 1850 sizeof(int8_t); // Pointer Size (in bytes) 1851 computeSizeAndOffset(I->second->getCUDie(), Offset, true); 1852 } 1853} 1854 1855/// EmitSectionSym - Switch to the specified MCSection and emit an assembler 1856/// temporary label to it if SymbolStem is specified. 1857static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section, 1858 const char *SymbolStem = 0) { 1859 Asm->OutStreamer.SwitchSection(Section); 1860 if (!SymbolStem) return 0; 1861 1862 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem); 1863 Asm->OutStreamer.EmitLabel(TmpSym); 1864 return TmpSym; 1865} 1866 1867/// EmitSectionLabels - Emit initial Dwarf sections with a label at 1868/// the start of each one. 1869void DwarfDebug::EmitSectionLabels() { 1870 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 1871 1872 // Dwarf sections base addresses. 1873 DwarfInfoSectionSym = 1874 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info"); 1875 DwarfAbbrevSectionSym = 1876 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev"); 1877 EmitSectionSym(Asm, TLOF.getDwarfARangesSection()); 1878 1879 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection()) 1880 EmitSectionSym(Asm, MacroInfo); 1881 1882 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line"); 1883 EmitSectionSym(Asm, TLOF.getDwarfLocSection()); 1884 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection()); 1885 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection()); 1886 DwarfStrSectionSym = 1887 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str"); 1888 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(), 1889 "debug_range"); 1890 1891 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(), 1892 "section_debug_loc"); 1893 1894 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin"); 1895 EmitSectionSym(Asm, TLOF.getDataSection()); 1896} 1897 1898/// emitDIE - Recursively emits a debug information entry. 1899/// 1900void DwarfDebug::emitDIE(DIE *Die) { 1901 // Get the abbreviation for this DIE. 1902 unsigned AbbrevNumber = Die->getAbbrevNumber(); 1903 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1]; 1904 1905 // Emit the code (index) for the abbreviation. 1906 if (Asm->isVerbose()) 1907 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" + 1908 Twine::utohexstr(Die->getOffset()) + ":0x" + 1909 Twine::utohexstr(Die->getSize()) + " " + 1910 dwarf::TagString(Abbrev->getTag())); 1911 Asm->EmitULEB128(AbbrevNumber); 1912 1913 const SmallVector<DIEValue*, 32> &Values = Die->getValues(); 1914 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData(); 1915 1916 // Emit the DIE attribute values. 1917 for (unsigned i = 0, N = Values.size(); i < N; ++i) { 1918 unsigned Attr = AbbrevData[i].getAttribute(); 1919 unsigned Form = AbbrevData[i].getForm(); 1920 assert(Form && "Too many attributes for DIE (check abbreviation)"); 1921 1922 if (Asm->isVerbose()) 1923 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr)); 1924 1925 switch (Attr) { 1926 case dwarf::DW_AT_sibling: 1927 Asm->EmitInt32(Die->getSiblingOffset()); 1928 break; 1929 case dwarf::DW_AT_abstract_origin: { 1930 DIEEntry *E = cast<DIEEntry>(Values[i]); 1931 DIE *Origin = E->getEntry(); 1932 unsigned Addr = Origin->getOffset(); 1933 Asm->EmitInt32(Addr); 1934 break; 1935 } 1936 case dwarf::DW_AT_ranges: { 1937 // DW_AT_range Value encodes offset in debug_range section. 1938 DIEInteger *V = cast<DIEInteger>(Values[i]); 1939 1940 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) { 1941 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym, 1942 V->getValue(), 1943 4); 1944 } else { 1945 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym, 1946 V->getValue(), 1947 DwarfDebugRangeSectionSym, 1948 4); 1949 } 1950 break; 1951 } 1952 case dwarf::DW_AT_location: { 1953 if (UseDotDebugLocEntry.count(Die) != 0) { 1954 DIELabel *L = cast<DIELabel>(Values[i]); 1955 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4); 1956 } else 1957 Values[i]->EmitValue(Asm, Form); 1958 break; 1959 } 1960 case dwarf::DW_AT_accessibility: { 1961 if (Asm->isVerbose()) { 1962 DIEInteger *V = cast<DIEInteger>(Values[i]); 1963 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue())); 1964 } 1965 Values[i]->EmitValue(Asm, Form); 1966 break; 1967 } 1968 default: 1969 // Emit an attribute using the defined form. 1970 Values[i]->EmitValue(Asm, Form); 1971 break; 1972 } 1973 } 1974 1975 // Emit the DIE children if any. 1976 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) { 1977 const std::vector<DIE *> &Children = Die->getChildren(); 1978 1979 for (unsigned j = 0, M = Children.size(); j < M; ++j) 1980 emitDIE(Children[j]); 1981 1982 if (Asm->isVerbose()) 1983 Asm->OutStreamer.AddComment("End Of Children Mark"); 1984 Asm->EmitInt8(0); 1985 } 1986} 1987 1988/// emitDebugInfo - Emit the debug info section. 1989/// 1990void DwarfDebug::emitDebugInfo() { 1991 // Start debug info section. 1992 Asm->OutStreamer.SwitchSection( 1993 Asm->getObjFileLowering().getDwarfInfoSection()); 1994 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(), 1995 E = CUMap.end(); I != E; ++I) { 1996 CompileUnit *TheCU = I->second; 1997 DIE *Die = TheCU->getCUDie(); 1998 1999 // Emit the compile units header. 2000 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin", 2001 TheCU->getID())); 2002 2003 // Emit size of content not including length itself 2004 unsigned ContentSize = Die->getSize() + 2005 sizeof(int16_t) + // DWARF version number 2006 sizeof(int32_t) + // Offset Into Abbrev. Section 2007 sizeof(int8_t); // Pointer Size (in bytes) 2008 2009 Asm->OutStreamer.AddComment("Length of Compilation Unit Info"); 2010 Asm->EmitInt32(ContentSize); 2011 Asm->OutStreamer.AddComment("DWARF version number"); 2012 Asm->EmitInt16(dwarf::DWARF_VERSION); 2013 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section"); 2014 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"), 2015 DwarfAbbrevSectionSym); 2016 Asm->OutStreamer.AddComment("Address Size (in bytes)"); 2017 Asm->EmitInt8(Asm->getTargetData().getPointerSize()); 2018 2019 emitDIE(Die); 2020 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID())); 2021 } 2022} 2023 2024/// emitAbbreviations - Emit the abbreviation section. 2025/// 2026void DwarfDebug::emitAbbreviations() const { 2027 // Check to see if it is worth the effort. 2028 if (!Abbreviations.empty()) { 2029 // Start the debug abbrev section. 2030 Asm->OutStreamer.SwitchSection( 2031 Asm->getObjFileLowering().getDwarfAbbrevSection()); 2032 2033 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin")); 2034 2035 // For each abbrevation. 2036 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) { 2037 // Get abbreviation data 2038 const DIEAbbrev *Abbrev = Abbreviations[i]; 2039 2040 // Emit the abbrevations code (base 1 index.) 2041 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code"); 2042 2043 // Emit the abbreviations data. 2044 Abbrev->Emit(Asm); 2045 } 2046 2047 // Mark end of abbreviations. 2048 Asm->EmitULEB128(0, "EOM(3)"); 2049 2050 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end")); 2051 } 2052} 2053 2054/// emitEndOfLineMatrix - Emit the last address of the section and the end of 2055/// the line matrix. 2056/// 2057void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) { 2058 // Define last address of section. 2059 Asm->OutStreamer.AddComment("Extended Op"); 2060 Asm->EmitInt8(0); 2061 2062 Asm->OutStreamer.AddComment("Op size"); 2063 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1); 2064 Asm->OutStreamer.AddComment("DW_LNE_set_address"); 2065 Asm->EmitInt8(dwarf::DW_LNE_set_address); 2066 2067 Asm->OutStreamer.AddComment("Section end label"); 2068 2069 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd), 2070 Asm->getTargetData().getPointerSize(), 2071 0/*AddrSpace*/); 2072 2073 // Mark end of matrix. 2074 Asm->OutStreamer.AddComment("DW_LNE_end_sequence"); 2075 Asm->EmitInt8(0); 2076 Asm->EmitInt8(1); 2077 Asm->EmitInt8(1); 2078} 2079 2080/// emitDebugPubNames - Emit visible names into a debug pubnames section. 2081/// 2082void DwarfDebug::emitDebugPubNames() { 2083 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(), 2084 E = CUMap.end(); I != E; ++I) { 2085 CompileUnit *TheCU = I->second; 2086 // Start the dwarf pubnames section. 2087 Asm->OutStreamer.SwitchSection( 2088 Asm->getObjFileLowering().getDwarfPubNamesSection()); 2089 2090 Asm->OutStreamer.AddComment("Length of Public Names Info"); 2091 Asm->EmitLabelDifference( 2092 Asm->GetTempSymbol("pubnames_end", TheCU->getID()), 2093 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4); 2094 2095 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", 2096 TheCU->getID())); 2097 2098 Asm->OutStreamer.AddComment("DWARF Version"); 2099 Asm->EmitInt16(dwarf::DWARF_VERSION); 2100 2101 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info"); 2102 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()), 2103 DwarfInfoSectionSym); 2104 2105 Asm->OutStreamer.AddComment("Compilation Unit Length"); 2106 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()), 2107 Asm->GetTempSymbol("info_begin", TheCU->getID()), 2108 4); 2109 2110 const StringMap<DIE*> &Globals = TheCU->getGlobals(); 2111 for (StringMap<DIE*>::const_iterator 2112 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) { 2113 const char *Name = GI->getKeyData(); 2114 DIE *Entity = GI->second; 2115 2116 Asm->OutStreamer.AddComment("DIE offset"); 2117 Asm->EmitInt32(Entity->getOffset()); 2118 2119 if (Asm->isVerbose()) 2120 Asm->OutStreamer.AddComment("External Name"); 2121 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0); 2122 } 2123 2124 Asm->OutStreamer.AddComment("End Mark"); 2125 Asm->EmitInt32(0); 2126 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", 2127 TheCU->getID())); 2128 } 2129} 2130 2131void DwarfDebug::emitDebugPubTypes() { 2132 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(), 2133 E = CUMap.end(); I != E; ++I) { 2134 CompileUnit *TheCU = I->second; 2135 // Start the dwarf pubnames section. 2136 Asm->OutStreamer.SwitchSection( 2137 Asm->getObjFileLowering().getDwarfPubTypesSection()); 2138 Asm->OutStreamer.AddComment("Length of Public Types Info"); 2139 Asm->EmitLabelDifference( 2140 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()), 2141 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4); 2142 2143 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin", 2144 TheCU->getID())); 2145 2146 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version"); 2147 Asm->EmitInt16(dwarf::DWARF_VERSION); 2148 2149 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info"); 2150 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()), 2151 DwarfInfoSectionSym); 2152 2153 Asm->OutStreamer.AddComment("Compilation Unit Length"); 2154 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()), 2155 Asm->GetTempSymbol("info_begin", TheCU->getID()), 2156 4); 2157 2158 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes(); 2159 for (StringMap<DIE*>::const_iterator 2160 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) { 2161 const char *Name = GI->getKeyData(); 2162 DIE *Entity = GI->second; 2163 2164 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset"); 2165 Asm->EmitInt32(Entity->getOffset()); 2166 2167 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name"); 2168 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0); 2169 } 2170 2171 Asm->OutStreamer.AddComment("End Mark"); 2172 Asm->EmitInt32(0); 2173 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end", 2174 TheCU->getID())); 2175 } 2176} 2177 2178/// emitDebugStr - Emit visible names into a debug str section. 2179/// 2180void DwarfDebug::emitDebugStr() { 2181 // Check to see if it is worth the effort. 2182 if (StringPool.empty()) return; 2183 2184 // Start the dwarf str section. 2185 Asm->OutStreamer.SwitchSection( 2186 Asm->getObjFileLowering().getDwarfStrSection()); 2187 2188 // Get all of the string pool entries and put them in an array by their ID so 2189 // we can sort them. 2190 SmallVector<std::pair<unsigned, 2191 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries; 2192 2193 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator 2194 I = StringPool.begin(), E = StringPool.end(); I != E; ++I) 2195 Entries.push_back(std::make_pair(I->second.second, &*I)); 2196 2197 array_pod_sort(Entries.begin(), Entries.end()); 2198 2199 for (unsigned i = 0, e = Entries.size(); i != e; ++i) { 2200 // Emit a label for reference from debug information entries. 2201 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first); 2202 2203 // Emit the string itself. 2204 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/); 2205 } 2206} 2207 2208/// emitDebugLoc - Emit visible names into a debug loc section. 2209/// 2210void DwarfDebug::emitDebugLoc() { 2211 if (DotDebugLocEntries.empty()) 2212 return; 2213 2214 for (SmallVector<DotDebugLocEntry, 4>::iterator 2215 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end(); 2216 I != E; ++I) { 2217 DotDebugLocEntry &Entry = *I; 2218 if (I + 1 != DotDebugLocEntries.end()) 2219 Entry.Merge(I+1); 2220 } 2221 2222 // Start the dwarf loc section. 2223 Asm->OutStreamer.SwitchSection( 2224 Asm->getObjFileLowering().getDwarfLocSection()); 2225 unsigned char Size = Asm->getTargetData().getPointerSize(); 2226 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0)); 2227 unsigned index = 1; 2228 for (SmallVector<DotDebugLocEntry, 4>::iterator 2229 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end(); 2230 I != E; ++I, ++index) { 2231 DotDebugLocEntry &Entry = *I; 2232 if (Entry.isMerged()) continue; 2233 if (Entry.isEmpty()) { 2234 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0); 2235 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0); 2236 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index)); 2237 } else { 2238 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0); 2239 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0); 2240 DIVariable DV(Entry.Variable); 2241 Asm->OutStreamer.AddComment("Loc expr size"); 2242 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol(); 2243 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol(); 2244 Asm->EmitLabelDifference(end, begin, 2); 2245 Asm->OutStreamer.EmitLabel(begin); 2246 if (Entry.isInt()) { 2247 DIBasicType BTy(DV.getType()); 2248 if (BTy.Verify() && 2249 (BTy.getEncoding() == dwarf::DW_ATE_signed 2250 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) { 2251 Asm->OutStreamer.AddComment("DW_OP_consts"); 2252 Asm->EmitInt8(dwarf::DW_OP_consts); 2253 Asm->EmitSLEB128(Entry.getInt()); 2254 } else { 2255 Asm->OutStreamer.AddComment("DW_OP_constu"); 2256 Asm->EmitInt8(dwarf::DW_OP_constu); 2257 Asm->EmitULEB128(Entry.getInt()); 2258 } 2259 } else if (Entry.isLocation()) { 2260 if (!DV.hasComplexAddress()) 2261 // Regular entry. 2262 Asm->EmitDwarfRegOp(Entry.Loc); 2263 else { 2264 // Complex address entry. 2265 unsigned N = DV.getNumAddrElements(); 2266 unsigned i = 0; 2267 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) { 2268 if (Entry.Loc.getOffset()) { 2269 i = 2; 2270 Asm->EmitDwarfRegOp(Entry.Loc); 2271 Asm->OutStreamer.AddComment("DW_OP_deref"); 2272 Asm->EmitInt8(dwarf::DW_OP_deref); 2273 Asm->OutStreamer.AddComment("DW_OP_plus_uconst"); 2274 Asm->EmitInt8(dwarf::DW_OP_plus_uconst); 2275 Asm->EmitSLEB128(DV.getAddrElement(1)); 2276 } else { 2277 // If first address element is OpPlus then emit 2278 // DW_OP_breg + Offset instead of DW_OP_reg + Offset. 2279 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1)); 2280 Asm->EmitDwarfRegOp(Loc); 2281 i = 2; 2282 } 2283 } else { 2284 Asm->EmitDwarfRegOp(Entry.Loc); 2285 } 2286 2287 // Emit remaining complex address elements. 2288 for (; i < N; ++i) { 2289 uint64_t Element = DV.getAddrElement(i); 2290 if (Element == DIBuilder::OpPlus) { 2291 Asm->EmitInt8(dwarf::DW_OP_plus_uconst); 2292 Asm->EmitULEB128(DV.getAddrElement(++i)); 2293 } else if (Element == DIBuilder::OpDeref) 2294 Asm->EmitInt8(dwarf::DW_OP_deref); 2295 else llvm_unreachable("unknown Opcode found in complex address"); 2296 } 2297 } 2298 } 2299 // else ... ignore constant fp. There is not any good way to 2300 // to represent them here in dwarf. 2301 Asm->OutStreamer.EmitLabel(end); 2302 } 2303 } 2304} 2305 2306/// EmitDebugARanges - Emit visible names into a debug aranges section. 2307/// 2308void DwarfDebug::EmitDebugARanges() { 2309 // Start the dwarf aranges section. 2310 Asm->OutStreamer.SwitchSection( 2311 Asm->getObjFileLowering().getDwarfARangesSection()); 2312} 2313 2314/// emitDebugRanges - Emit visible names into a debug ranges section. 2315/// 2316void DwarfDebug::emitDebugRanges() { 2317 // Start the dwarf ranges section. 2318 Asm->OutStreamer.SwitchSection( 2319 Asm->getObjFileLowering().getDwarfRangesSection()); 2320 unsigned char Size = Asm->getTargetData().getPointerSize(); 2321 for (SmallVector<const MCSymbol *, 8>::iterator 2322 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end(); 2323 I != E; ++I) { 2324 if (*I) 2325 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0); 2326 else 2327 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0); 2328 } 2329} 2330 2331/// emitDebugMacInfo - Emit visible names into a debug macinfo section. 2332/// 2333void DwarfDebug::emitDebugMacInfo() { 2334 if (const MCSection *LineInfo = 2335 Asm->getObjFileLowering().getDwarfMacroInfoSection()) { 2336 // Start the dwarf macinfo section. 2337 Asm->OutStreamer.SwitchSection(LineInfo); 2338 } 2339} 2340 2341/// emitDebugInlineInfo - Emit inline info using following format. 2342/// Section Header: 2343/// 1. length of section 2344/// 2. Dwarf version number 2345/// 3. address size. 2346/// 2347/// Entries (one "entry" for each function that was inlined): 2348/// 2349/// 1. offset into __debug_str section for MIPS linkage name, if exists; 2350/// otherwise offset into __debug_str for regular function name. 2351/// 2. offset into __debug_str section for regular function name. 2352/// 3. an unsigned LEB128 number indicating the number of distinct inlining 2353/// instances for the function. 2354/// 2355/// The rest of the entry consists of a {die_offset, low_pc} pair for each 2356/// inlined instance; the die_offset points to the inlined_subroutine die in the 2357/// __debug_info section, and the low_pc is the starting address for the 2358/// inlining instance. 2359void DwarfDebug::emitDebugInlineInfo() { 2360 if (!Asm->MAI->doesDwarfUsesInlineInfoSection()) 2361 return; 2362 2363 if (!FirstCU) 2364 return; 2365 2366 Asm->OutStreamer.SwitchSection( 2367 Asm->getObjFileLowering().getDwarfDebugInlineSection()); 2368 2369 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry"); 2370 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1), 2371 Asm->GetTempSymbol("debug_inlined_begin", 1), 4); 2372 2373 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1)); 2374 2375 Asm->OutStreamer.AddComment("Dwarf Version"); 2376 Asm->EmitInt16(dwarf::DWARF_VERSION); 2377 Asm->OutStreamer.AddComment("Address Size (in bytes)"); 2378 Asm->EmitInt8(Asm->getTargetData().getPointerSize()); 2379 2380 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(), 2381 E = InlinedSPNodes.end(); I != E; ++I) { 2382 2383 const MDNode *Node = *I; 2384 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II 2385 = InlineInfo.find(Node); 2386 SmallVector<InlineInfoLabels, 4> &Labels = II->second; 2387 DISubprogram SP(Node); 2388 StringRef LName = SP.getLinkageName(); 2389 StringRef Name = SP.getName(); 2390 2391 Asm->OutStreamer.AddComment("MIPS linkage name"); 2392 if (LName.empty()) { 2393 Asm->OutStreamer.EmitBytes(Name, 0); 2394 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator. 2395 } else 2396 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)), 2397 DwarfStrSectionSym); 2398 2399 Asm->OutStreamer.AddComment("Function name"); 2400 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym); 2401 Asm->EmitULEB128(Labels.size(), "Inline count"); 2402 2403 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(), 2404 LE = Labels.end(); LI != LE; ++LI) { 2405 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset"); 2406 Asm->EmitInt32(LI->second->getOffset()); 2407 2408 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc"); 2409 Asm->OutStreamer.EmitSymbolValue(LI->first, 2410 Asm->getTargetData().getPointerSize(),0); 2411 } 2412 } 2413 2414 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1)); 2415} 2416