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