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