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