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