1 //===- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Units ------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains support for constructing a dwarf compile unit. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "DwarfCompileUnit.h" 14 #include "AddressPool.h" 15 #include "DwarfExpression.h" 16 #include "llvm/ADT/None.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallString.h" 19 #include "llvm/BinaryFormat/Dwarf.h" 20 #include "llvm/CodeGen/AsmPrinter.h" 21 #include "llvm/CodeGen/DIE.h" 22 #include "llvm/CodeGen/MachineFunction.h" 23 #include "llvm/CodeGen/MachineInstr.h" 24 #include "llvm/CodeGen/MachineOperand.h" 25 #include "llvm/CodeGen/TargetFrameLowering.h" 26 #include "llvm/CodeGen/TargetRegisterInfo.h" 27 #include "llvm/CodeGen/TargetSubtargetInfo.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/DebugInfo.h" 30 #include "llvm/IR/GlobalVariable.h" 31 #include "llvm/MC/MCSection.h" 32 #include "llvm/MC/MCStreamer.h" 33 #include "llvm/MC/MCSymbol.h" 34 #include "llvm/MC/MCSymbolWasm.h" 35 #include "llvm/MC/MachineLocation.h" 36 #include "llvm/Target/TargetLoweringObjectFile.h" 37 #include "llvm/Target/TargetMachine.h" 38 #include "llvm/Target/TargetOptions.h" 39 #include <iterator> 40 #include <string> 41 #include <utility> 42 43 using namespace llvm; 44 45 static dwarf::Tag GetCompileUnitType(UnitKind Kind, DwarfDebug *DW) { 46 47 // According to DWARF Debugging Information Format Version 5, 48 // 3.1.2 Skeleton Compilation Unit Entries: 49 // "When generating a split DWARF object file (see Section 7.3.2 50 // on page 187), the compilation unit in the .debug_info section 51 // is a "skeleton" compilation unit with the tag DW_TAG_skeleton_unit" 52 if (DW->getDwarfVersion() >= 5 && Kind == UnitKind::Skeleton) 53 return dwarf::DW_TAG_skeleton_unit; 54 55 return dwarf::DW_TAG_compile_unit; 56 } 57 58 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node, 59 AsmPrinter *A, DwarfDebug *DW, 60 DwarfFile *DWU, UnitKind Kind) 61 : DwarfUnit(GetCompileUnitType(Kind, DW), Node, A, DW, DWU), UniqueID(UID) { 62 insertDIE(Node, &getUnitDie()); 63 MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin"); 64 } 65 66 /// addLabelAddress - Add a dwarf label attribute data and value using 67 /// DW_FORM_addr or DW_FORM_GNU_addr_index. 68 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute, 69 const MCSymbol *Label) { 70 // Don't use the address pool in non-fission or in the skeleton unit itself. 71 if ((!DD->useSplitDwarf() || !Skeleton) && DD->getDwarfVersion() < 5) 72 return addLocalLabelAddress(Die, Attribute, Label); 73 74 if (Label) 75 DD->addArangeLabel(SymbolCU(this, Label)); 76 77 bool UseAddrOffsetFormOrExpressions = 78 DD->useAddrOffsetForm() || DD->useAddrOffsetExpressions(); 79 80 const MCSymbol *Base = nullptr; 81 if (Label->isInSection() && UseAddrOffsetFormOrExpressions) 82 Base = DD->getSectionLabel(&Label->getSection()); 83 84 if (!Base || Base == Label) { 85 unsigned idx = DD->getAddressPool().getIndex(Label); 86 Die.addValue(DIEValueAllocator, Attribute, 87 DD->getDwarfVersion() >= 5 ? dwarf::DW_FORM_addrx 88 : dwarf::DW_FORM_GNU_addr_index, 89 DIEInteger(idx)); 90 return; 91 } 92 93 // Could be extended to work with DWARFv4 Split DWARF if that's important for 94 // someone. In that case DW_FORM_data would be used. 95 assert(DD->getDwarfVersion() >= 5 && 96 "Addr+offset expressions are only valuable when using debug_addr (to " 97 "reduce relocations) available in DWARFv5 or higher"); 98 if (DD->useAddrOffsetExpressions()) { 99 auto *Loc = new (DIEValueAllocator) DIEBlock(); 100 addPoolOpAddress(*Loc, Label); 101 addBlock(Die, Attribute, dwarf::DW_FORM_exprloc, Loc); 102 } else 103 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_LLVM_addrx_offset, 104 new (DIEValueAllocator) DIEAddrOffset( 105 DD->getAddressPool().getIndex(Base), Label, Base)); 106 } 107 108 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die, 109 dwarf::Attribute Attribute, 110 const MCSymbol *Label) { 111 if (Label) 112 DD->addArangeLabel(SymbolCU(this, Label)); 113 114 if (Label) 115 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr, 116 DIELabel(Label)); 117 else 118 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr, 119 DIEInteger(0)); 120 } 121 122 unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) { 123 // If we print assembly, we can't separate .file entries according to 124 // compile units. Thus all files will belong to the default compile unit. 125 126 // FIXME: add a better feature test than hasRawTextSupport. Even better, 127 // extend .file to support this. 128 unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID(); 129 if (!File) 130 return Asm->OutStreamer->emitDwarfFileDirective(0, "", "", None, None, 131 CUID); 132 return Asm->OutStreamer->emitDwarfFileDirective( 133 0, File->getDirectory(), File->getFilename(), DD->getMD5AsBytes(File), 134 File->getSource(), CUID); 135 } 136 137 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE( 138 const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) { 139 // Check for pre-existence. 140 if (DIE *Die = getDIE(GV)) 141 return Die; 142 143 assert(GV); 144 145 auto *GVContext = GV->getScope(); 146 const DIType *GTy = GV->getType(); 147 148 // Construct the context before querying for the existence of the DIE in 149 // case such construction creates the DIE. 150 auto *CB = GVContext ? dyn_cast<DICommonBlock>(GVContext) : nullptr; 151 DIE *ContextDIE = CB ? getOrCreateCommonBlock(CB, GlobalExprs) 152 : getOrCreateContextDIE(GVContext); 153 154 // Add to map. 155 DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV); 156 DIScope *DeclContext; 157 if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) { 158 DeclContext = SDMDecl->getScope(); 159 assert(SDMDecl->isStaticMember() && "Expected static member decl"); 160 assert(GV->isDefinition()); 161 // We need the declaration DIE that is in the static member's class. 162 DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl); 163 addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE); 164 // If the global variable's type is different from the one in the class 165 // member type, assume that it's more specific and also emit it. 166 if (GTy != SDMDecl->getBaseType()) 167 addType(*VariableDIE, GTy); 168 } else { 169 DeclContext = GV->getScope(); 170 // Add name and type. 171 addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName()); 172 if (GTy) 173 addType(*VariableDIE, GTy); 174 175 // Add scoping info. 176 if (!GV->isLocalToUnit()) 177 addFlag(*VariableDIE, dwarf::DW_AT_external); 178 179 // Add line number info. 180 addSourceLine(*VariableDIE, GV); 181 } 182 183 if (!GV->isDefinition()) 184 addFlag(*VariableDIE, dwarf::DW_AT_declaration); 185 else 186 addGlobalName(GV->getName(), *VariableDIE, DeclContext); 187 188 if (uint32_t AlignInBytes = GV->getAlignInBytes()) 189 addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata, 190 AlignInBytes); 191 192 if (MDTuple *TP = GV->getTemplateParams()) 193 addTemplateParams(*VariableDIE, DINodeArray(TP)); 194 195 // Add location. 196 addLocationAttribute(VariableDIE, GV, GlobalExprs); 197 198 return VariableDIE; 199 } 200 201 void DwarfCompileUnit::addLocationAttribute( 202 DIE *VariableDIE, const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) { 203 bool addToAccelTable = false; 204 DIELoc *Loc = nullptr; 205 Optional<unsigned> NVPTXAddressSpace; 206 std::unique_ptr<DIEDwarfExpression> DwarfExpr; 207 for (const auto &GE : GlobalExprs) { 208 const GlobalVariable *Global = GE.Var; 209 const DIExpression *Expr = GE.Expr; 210 211 // For compatibility with DWARF 3 and earlier, 212 // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) becomes 213 // DW_AT_const_value(X). 214 if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) { 215 addToAccelTable = true; 216 addConstantValue(*VariableDIE, /*Unsigned=*/true, Expr->getElement(1)); 217 break; 218 } 219 220 // We cannot describe the location of dllimport'd variables: the 221 // computation of their address requires loads from the IAT. 222 if (Global && Global->hasDLLImportStorageClass()) 223 continue; 224 225 // Nothing to describe without address or constant. 226 if (!Global && (!Expr || !Expr->isConstant())) 227 continue; 228 229 if (Global && Global->isThreadLocal() && 230 !Asm->getObjFileLowering().supportDebugThreadLocalLocation()) 231 continue; 232 233 if (!Loc) { 234 addToAccelTable = true; 235 Loc = new (DIEValueAllocator) DIELoc; 236 DwarfExpr = std::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc); 237 } 238 239 if (Expr) { 240 // According to 241 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf 242 // cuda-gdb requires DW_AT_address_class for all variables to be able to 243 // correctly interpret address space of the variable address. 244 // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef 245 // sequence for the NVPTX + gdb target. 246 unsigned LocalNVPTXAddressSpace; 247 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) { 248 const DIExpression *NewExpr = 249 DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace); 250 if (NewExpr != Expr) { 251 Expr = NewExpr; 252 NVPTXAddressSpace = LocalNVPTXAddressSpace; 253 } 254 } 255 DwarfExpr->addFragmentOffset(Expr); 256 } 257 258 if (Global) { 259 const MCSymbol *Sym = Asm->getSymbol(Global); 260 if (Global->isThreadLocal()) { 261 if (Asm->TM.useEmulatedTLS()) { 262 // TODO: add debug info for emulated thread local mode. 263 } else { 264 // FIXME: Make this work with -gsplit-dwarf. 265 unsigned PointerSize = Asm->getDataLayout().getPointerSize(); 266 assert((PointerSize == 4 || PointerSize == 8) && 267 "Add support for other sizes if necessary"); 268 // Based on GCC's support for TLS: 269 if (!DD->useSplitDwarf()) { 270 // 1) Start with a constNu of the appropriate pointer size 271 addUInt(*Loc, dwarf::DW_FORM_data1, 272 PointerSize == 4 ? dwarf::DW_OP_const4u 273 : dwarf::DW_OP_const8u); 274 // 2) containing the (relocated) offset of the TLS variable 275 // within the module's TLS block. 276 addExpr(*Loc, 277 PointerSize == 4 ? dwarf::DW_FORM_data4 278 : dwarf::DW_FORM_data8, 279 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym)); 280 } else { 281 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index); 282 addUInt(*Loc, dwarf::DW_FORM_udata, 283 DD->getAddressPool().getIndex(Sym, /* TLS */ true)); 284 } 285 // 3) followed by an OP to make the debugger do a TLS lookup. 286 addUInt(*Loc, dwarf::DW_FORM_data1, 287 DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address 288 : dwarf::DW_OP_form_tls_address); 289 } 290 } else { 291 DD->addArangeLabel(SymbolCU(this, Sym)); 292 addOpAddress(*Loc, Sym); 293 } 294 } 295 // Global variables attached to symbols are memory locations. 296 // It would be better if this were unconditional, but malformed input that 297 // mixes non-fragments and fragments for the same variable is too expensive 298 // to detect in the verifier. 299 if (DwarfExpr->isUnknownLocation()) 300 DwarfExpr->setMemoryLocationKind(); 301 DwarfExpr->addExpression(Expr); 302 } 303 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) { 304 // According to 305 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf 306 // cuda-gdb requires DW_AT_address_class for all variables to be able to 307 // correctly interpret address space of the variable address. 308 const unsigned NVPTX_ADDR_global_space = 5; 309 addUInt(*VariableDIE, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1, 310 NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_global_space); 311 } 312 if (Loc) 313 addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize()); 314 315 if (DD->useAllLinkageNames()) 316 addLinkageName(*VariableDIE, GV->getLinkageName()); 317 318 if (addToAccelTable) { 319 DD->addAccelName(*CUNode, GV->getName(), *VariableDIE); 320 321 // If the linkage name is different than the name, go ahead and output 322 // that as well into the name table. 323 if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() && 324 DD->useAllLinkageNames()) 325 DD->addAccelName(*CUNode, GV->getLinkageName(), *VariableDIE); 326 } 327 } 328 329 DIE *DwarfCompileUnit::getOrCreateCommonBlock( 330 const DICommonBlock *CB, ArrayRef<GlobalExpr> GlobalExprs) { 331 // Construct the context before querying for the existence of the DIE in case 332 // such construction creates the DIE. 333 DIE *ContextDIE = getOrCreateContextDIE(CB->getScope()); 334 335 if (DIE *NDie = getDIE(CB)) 336 return NDie; 337 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_common_block, *ContextDIE, CB); 338 StringRef Name = CB->getName().empty() ? "_BLNK_" : CB->getName(); 339 addString(NDie, dwarf::DW_AT_name, Name); 340 addGlobalName(Name, NDie, CB->getScope()); 341 if (CB->getFile()) 342 addSourceLine(NDie, CB->getLineNo(), CB->getFile()); 343 if (DIGlobalVariable *V = CB->getDecl()) 344 getCU().addLocationAttribute(&NDie, V, GlobalExprs); 345 return &NDie; 346 } 347 348 void DwarfCompileUnit::addRange(RangeSpan Range) { 349 DD->insertSectionLabel(Range.Begin); 350 351 bool SameAsPrevCU = this == DD->getPrevCU(); 352 DD->setPrevCU(this); 353 // If we have no current ranges just add the range and return, otherwise, 354 // check the current section and CU against the previous section and CU we 355 // emitted into and the subprogram was contained within. If these are the 356 // same then extend our current range, otherwise add this as a new range. 357 if (CURanges.empty() || !SameAsPrevCU || 358 (&CURanges.back().End->getSection() != 359 &Range.End->getSection())) { 360 CURanges.push_back(Range); 361 return; 362 } 363 364 CURanges.back().End = Range.End; 365 } 366 367 void DwarfCompileUnit::initStmtList() { 368 if (CUNode->isDebugDirectivesOnly()) 369 return; 370 371 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 372 if (DD->useSectionsAsReferences()) { 373 LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol(); 374 } else { 375 LineTableStartSym = 376 Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID()); 377 } 378 379 // DW_AT_stmt_list is a offset of line number information for this 380 // compile unit in debug_line section. For split dwarf this is 381 // left in the skeleton CU and so not included. 382 // The line table entries are not always emitted in assembly, so it 383 // is not okay to use line_table_start here. 384 addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym, 385 TLOF.getDwarfLineSection()->getBeginSymbol()); 386 } 387 388 void DwarfCompileUnit::applyStmtList(DIE &D) { 389 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 390 addSectionLabel(D, dwarf::DW_AT_stmt_list, LineTableStartSym, 391 TLOF.getDwarfLineSection()->getBeginSymbol()); 392 } 393 394 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin, 395 const MCSymbol *End) { 396 assert(Begin && "Begin label should not be null!"); 397 assert(End && "End label should not be null!"); 398 assert(Begin->isDefined() && "Invalid starting label"); 399 assert(End->isDefined() && "Invalid end label"); 400 401 addLabelAddress(D, dwarf::DW_AT_low_pc, Begin); 402 if (DD->getDwarfVersion() < 4) 403 addLabelAddress(D, dwarf::DW_AT_high_pc, End); 404 else 405 addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin); 406 } 407 408 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc 409 // and DW_AT_high_pc attributes. If there are global variables in this 410 // scope then create and insert DIEs for these variables. 411 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) { 412 DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes()); 413 414 SmallVector<RangeSpan, 2> BB_List; 415 // If basic block sections are on, ranges for each basic block section has 416 // to be emitted separately. 417 for (const auto &R : Asm->MBBSectionRanges) 418 BB_List.push_back({R.second.BeginLabel, R.second.EndLabel}); 419 420 attachRangesOrLowHighPC(*SPDie, BB_List); 421 422 if (DD->useAppleExtensionAttributes() && 423 !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim( 424 *DD->getCurrentFunction())) 425 addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr); 426 427 // Only include DW_AT_frame_base in full debug info 428 if (!includeMinimalInlineScopes()) { 429 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering(); 430 TargetFrameLowering::DwarfFrameBase FrameBase = 431 TFI->getDwarfFrameBase(*Asm->MF); 432 switch (FrameBase.Kind) { 433 case TargetFrameLowering::DwarfFrameBase::Register: { 434 if (Register::isPhysicalRegister(FrameBase.Location.Reg)) { 435 MachineLocation Location(FrameBase.Location.Reg); 436 addAddress(*SPDie, dwarf::DW_AT_frame_base, Location); 437 } 438 break; 439 } 440 case TargetFrameLowering::DwarfFrameBase::CFA: { 441 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 442 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa); 443 addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc); 444 break; 445 } 446 case TargetFrameLowering::DwarfFrameBase::WasmFrameBase: { 447 // FIXME: duplicated from Target/WebAssembly/WebAssembly.h 448 // don't want to depend on target specific headers in this code? 449 const unsigned TI_GLOBAL_RELOC = 3; 450 // FIXME: when writing dwo, we need to avoid relocations. Probably 451 // the "right" solution is to treat globals the way func and data symbols 452 // are (with entries in .debug_addr). 453 if (FrameBase.Location.WasmLoc.Kind == TI_GLOBAL_RELOC && !isDwoUnit()) { 454 // These need to be relocatable. 455 assert(FrameBase.Location.WasmLoc.Index == 0); // Only SP so far. 456 auto SPSym = cast<MCSymbolWasm>( 457 Asm->GetExternalSymbolSymbol("__stack_pointer")); 458 // FIXME: this repeats what WebAssemblyMCInstLower:: 459 // GetExternalSymbolSymbol does, since if there's no code that 460 // refers to this symbol, we have to set it here. 461 SPSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL); 462 SPSym->setGlobalType(wasm::WasmGlobalType{ 463 uint8_t(Asm->getSubtargetInfo().getTargetTriple().getArch() == 464 Triple::wasm64 465 ? wasm::WASM_TYPE_I64 466 : wasm::WASM_TYPE_I32), 467 true}); 468 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 469 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_WASM_location); 470 addSInt(*Loc, dwarf::DW_FORM_sdata, TI_GLOBAL_RELOC); 471 addLabel(*Loc, dwarf::DW_FORM_data4, SPSym); 472 DD->addArangeLabel(SymbolCU(this, SPSym)); 473 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value); 474 addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc); 475 } else { 476 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 477 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 478 DIExpressionCursor Cursor({}); 479 DwarfExpr.addWasmLocation(FrameBase.Location.WasmLoc.Kind, 480 FrameBase.Location.WasmLoc.Index); 481 DwarfExpr.addExpression(std::move(Cursor)); 482 addBlock(*SPDie, dwarf::DW_AT_frame_base, DwarfExpr.finalize()); 483 } 484 break; 485 } 486 } 487 } 488 489 // Add name to the name table, we do this here because we're guaranteed 490 // to have concrete versions of our DW_TAG_subprogram nodes. 491 DD->addSubprogramNames(*CUNode, SP, *SPDie); 492 493 return *SPDie; 494 } 495 496 // Construct a DIE for this scope. 497 void DwarfCompileUnit::constructScopeDIE( 498 LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) { 499 if (!Scope || !Scope->getScopeNode()) 500 return; 501 502 auto *DS = Scope->getScopeNode(); 503 504 assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) && 505 "Only handle inlined subprograms here, use " 506 "constructSubprogramScopeDIE for non-inlined " 507 "subprograms"); 508 509 SmallVector<DIE *, 8> Children; 510 511 // We try to create the scope DIE first, then the children DIEs. This will 512 // avoid creating un-used children then removing them later when we find out 513 // the scope DIE is null. 514 DIE *ScopeDIE; 515 if (Scope->getParent() && isa<DISubprogram>(DS)) { 516 ScopeDIE = constructInlinedScopeDIE(Scope); 517 if (!ScopeDIE) 518 return; 519 // We create children when the scope DIE is not null. 520 createScopeChildrenDIE(Scope, Children); 521 } else { 522 // Early exit when we know the scope DIE is going to be null. 523 if (DD->isLexicalScopeDIENull(Scope)) 524 return; 525 526 bool HasNonScopeChildren = false; 527 528 // We create children here when we know the scope DIE is not going to be 529 // null and the children will be added to the scope DIE. 530 createScopeChildrenDIE(Scope, Children, &HasNonScopeChildren); 531 532 // If there are only other scopes as children, put them directly in the 533 // parent instead, as this scope would serve no purpose. 534 if (!HasNonScopeChildren) { 535 FinalChildren.insert(FinalChildren.end(), 536 std::make_move_iterator(Children.begin()), 537 std::make_move_iterator(Children.end())); 538 return; 539 } 540 ScopeDIE = constructLexicalScopeDIE(Scope); 541 assert(ScopeDIE && "Scope DIE should not be null."); 542 } 543 544 // Add children 545 for (auto &I : Children) 546 ScopeDIE->addChild(std::move(I)); 547 548 FinalChildren.push_back(std::move(ScopeDIE)); 549 } 550 551 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE, 552 SmallVector<RangeSpan, 2> Range) { 553 554 HasRangeLists = true; 555 556 // Add the range list to the set of ranges to be emitted. 557 auto IndexAndList = 558 (DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU) 559 ->addRange(*(Skeleton ? Skeleton : this), std::move(Range)); 560 561 uint32_t Index = IndexAndList.first; 562 auto &List = *IndexAndList.second; 563 564 // Under fission, ranges are specified by constant offsets relative to the 565 // CU's DW_AT_GNU_ranges_base. 566 // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under 567 // fission until we support the forms using the .debug_addr section 568 // (DW_RLE_startx_endx etc.). 569 if (DD->getDwarfVersion() >= 5) 570 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_rnglistx, Index); 571 else { 572 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 573 const MCSymbol *RangeSectionSym = 574 TLOF.getDwarfRangesSection()->getBeginSymbol(); 575 if (isDwoUnit()) 576 addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.Label, 577 RangeSectionSym); 578 else 579 addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.Label, 580 RangeSectionSym); 581 } 582 } 583 584 void DwarfCompileUnit::attachRangesOrLowHighPC( 585 DIE &Die, SmallVector<RangeSpan, 2> Ranges) { 586 assert(!Ranges.empty()); 587 if (!DD->useRangesSection() || 588 (Ranges.size() == 1 && 589 (!DD->alwaysUseRanges() || 590 DD->getSectionLabel(&Ranges.front().Begin->getSection()) == 591 Ranges.front().Begin))) { 592 const RangeSpan &Front = Ranges.front(); 593 const RangeSpan &Back = Ranges.back(); 594 attachLowHighPC(Die, Front.Begin, Back.End); 595 } else 596 addScopeRangeList(Die, std::move(Ranges)); 597 } 598 599 void DwarfCompileUnit::attachRangesOrLowHighPC( 600 DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) { 601 SmallVector<RangeSpan, 2> List; 602 List.reserve(Ranges.size()); 603 for (const InsnRange &R : Ranges) { 604 auto *BeginLabel = DD->getLabelBeforeInsn(R.first); 605 auto *EndLabel = DD->getLabelAfterInsn(R.second); 606 607 const auto *BeginMBB = R.first->getParent(); 608 const auto *EndMBB = R.second->getParent(); 609 610 const auto *MBB = BeginMBB; 611 // Basic block sections allows basic block subsets to be placed in unique 612 // sections. For each section, the begin and end label must be added to the 613 // list. If there is more than one range, debug ranges must be used. 614 // Otherwise, low/high PC can be used. 615 // FIXME: Debug Info Emission depends on block order and this assumes that 616 // the order of blocks will be frozen beyond this point. 617 do { 618 if (MBB->sameSection(EndMBB) || MBB->isEndSection()) { 619 auto MBBSectionRange = Asm->MBBSectionRanges[MBB->getSectionIDNum()]; 620 List.push_back( 621 {MBB->sameSection(BeginMBB) ? BeginLabel 622 : MBBSectionRange.BeginLabel, 623 MBB->sameSection(EndMBB) ? EndLabel : MBBSectionRange.EndLabel}); 624 } 625 if (MBB->sameSection(EndMBB)) 626 break; 627 MBB = MBB->getNextNode(); 628 } while (true); 629 } 630 attachRangesOrLowHighPC(Die, std::move(List)); 631 } 632 633 // This scope represents inlined body of a function. Construct DIE to 634 // represent this concrete inlined copy of the function. 635 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) { 636 assert(Scope->getScopeNode()); 637 auto *DS = Scope->getScopeNode(); 638 auto *InlinedSP = getDISubprogram(DS); 639 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram 640 // was inlined from another compile unit. 641 DIE *OriginDIE = getAbstractSPDies()[InlinedSP]; 642 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram."); 643 644 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine); 645 addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE); 646 647 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges()); 648 649 // Add the call site information to the DIE. 650 const DILocation *IA = Scope->getInlinedAt(); 651 addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None, 652 getOrCreateSourceID(IA->getFile())); 653 addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine()); 654 if (IA->getColumn()) 655 addUInt(*ScopeDIE, dwarf::DW_AT_call_column, None, IA->getColumn()); 656 if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4) 657 addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None, 658 IA->getDiscriminator()); 659 660 // Add name to the name table, we do this here because we're guaranteed 661 // to have concrete versions of our DW_TAG_inlined_subprogram nodes. 662 DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE); 663 664 return ScopeDIE; 665 } 666 667 // Construct new DW_TAG_lexical_block for this scope and attach 668 // DW_AT_low_pc/DW_AT_high_pc labels. 669 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) { 670 if (DD->isLexicalScopeDIENull(Scope)) 671 return nullptr; 672 673 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block); 674 if (Scope->isAbstractScope()) 675 return ScopeDIE; 676 677 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges()); 678 679 return ScopeDIE; 680 } 681 682 /// constructVariableDIE - Construct a DIE for the given DbgVariable. 683 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) { 684 auto D = constructVariableDIEImpl(DV, Abstract); 685 DV.setDIE(*D); 686 return D; 687 } 688 689 DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL, 690 const LexicalScope &Scope) { 691 auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag()); 692 insertDIE(DL.getLabel(), LabelDie); 693 DL.setDIE(*LabelDie); 694 695 if (Scope.isAbstractScope()) 696 applyLabelAttributes(DL, *LabelDie); 697 698 return LabelDie; 699 } 700 701 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV, 702 bool Abstract) { 703 // Define variable debug information entry. 704 auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag()); 705 insertDIE(DV.getVariable(), VariableDie); 706 707 if (Abstract) { 708 applyVariableAttributes(DV, *VariableDie); 709 return VariableDie; 710 } 711 712 // Add variable address. 713 714 unsigned Index = DV.getDebugLocListIndex(); 715 if (Index != ~0U) { 716 addLocationList(*VariableDie, dwarf::DW_AT_location, Index); 717 auto TagOffset = DV.getDebugLocListTagOffset(); 718 if (TagOffset) 719 addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1, 720 *TagOffset); 721 return VariableDie; 722 } 723 724 // Check if variable has a single location description. 725 if (auto *DVal = DV.getValueLoc()) { 726 if (DVal->isLocation()) 727 addVariableAddress(DV, *VariableDie, DVal->getLoc()); 728 else if (DVal->isInt()) { 729 auto *Expr = DV.getSingleExpression(); 730 if (Expr && Expr->getNumElements()) { 731 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 732 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 733 // If there is an expression, emit raw unsigned bytes. 734 DwarfExpr.addFragmentOffset(Expr); 735 DwarfExpr.addUnsignedConstant(DVal->getInt()); 736 DwarfExpr.addExpression(Expr); 737 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize()); 738 if (DwarfExpr.TagOffset) 739 addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, 740 dwarf::DW_FORM_data1, *DwarfExpr.TagOffset); 741 742 } else 743 addConstantValue(*VariableDie, DVal->getInt(), DV.getType()); 744 } else if (DVal->isConstantFP()) { 745 addConstantFPValue(*VariableDie, DVal->getConstantFP()); 746 } else if (DVal->isConstantInt()) { 747 addConstantValue(*VariableDie, DVal->getConstantInt(), DV.getType()); 748 } else if (DVal->isTargetIndexLocation()) { 749 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 750 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 751 const DIBasicType *BT = dyn_cast<DIBasicType>( 752 static_cast<const Metadata *>(DV.getVariable()->getType())); 753 DwarfDebug::emitDebugLocValue(*Asm, BT, *DVal, DwarfExpr); 754 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize()); 755 } 756 return VariableDie; 757 } 758 759 // .. else use frame index. 760 if (!DV.hasFrameIndexExprs()) 761 return VariableDie; 762 763 Optional<unsigned> NVPTXAddressSpace; 764 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 765 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 766 for (auto &Fragment : DV.getFrameIndexExprs()) { 767 Register FrameReg; 768 const DIExpression *Expr = Fragment.Expr; 769 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering(); 770 StackOffset Offset = 771 TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg); 772 DwarfExpr.addFragmentOffset(Expr); 773 774 auto *TRI = Asm->MF->getSubtarget().getRegisterInfo(); 775 SmallVector<uint64_t, 8> Ops; 776 TRI->getOffsetOpcodes(Offset, Ops); 777 778 // According to 779 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf 780 // cuda-gdb requires DW_AT_address_class for all variables to be able to 781 // correctly interpret address space of the variable address. 782 // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef 783 // sequence for the NVPTX + gdb target. 784 unsigned LocalNVPTXAddressSpace; 785 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) { 786 const DIExpression *NewExpr = 787 DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace); 788 if (NewExpr != Expr) { 789 Expr = NewExpr; 790 NVPTXAddressSpace = LocalNVPTXAddressSpace; 791 } 792 } 793 if (Expr) 794 Ops.append(Expr->elements_begin(), Expr->elements_end()); 795 DIExpressionCursor Cursor(Ops); 796 DwarfExpr.setMemoryLocationKind(); 797 if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol()) 798 addOpAddress(*Loc, FrameSymbol); 799 else 800 DwarfExpr.addMachineRegExpression( 801 *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg); 802 DwarfExpr.addExpression(std::move(Cursor)); 803 } 804 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) { 805 // According to 806 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf 807 // cuda-gdb requires DW_AT_address_class for all variables to be able to 808 // correctly interpret address space of the variable address. 809 const unsigned NVPTX_ADDR_local_space = 6; 810 addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1, 811 NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space); 812 } 813 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize()); 814 if (DwarfExpr.TagOffset) 815 addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1, 816 *DwarfExpr.TagOffset); 817 818 return VariableDie; 819 } 820 821 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, 822 const LexicalScope &Scope, 823 DIE *&ObjectPointer) { 824 auto Var = constructVariableDIE(DV, Scope.isAbstractScope()); 825 if (DV.isObjectPointer()) 826 ObjectPointer = Var; 827 return Var; 828 } 829 830 /// Return all DIVariables that appear in count: expressions. 831 static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) { 832 SmallVector<const DIVariable *, 2> Result; 833 auto *Array = dyn_cast<DICompositeType>(Var->getType()); 834 if (!Array || Array->getTag() != dwarf::DW_TAG_array_type) 835 return Result; 836 if (auto *DLVar = Array->getDataLocation()) 837 Result.push_back(DLVar); 838 if (auto *AsVar = Array->getAssociated()) 839 Result.push_back(AsVar); 840 if (auto *AlVar = Array->getAllocated()) 841 Result.push_back(AlVar); 842 for (auto *El : Array->getElements()) { 843 if (auto *Subrange = dyn_cast<DISubrange>(El)) { 844 if (auto Count = Subrange->getCount()) 845 if (auto *Dependency = Count.dyn_cast<DIVariable *>()) 846 Result.push_back(Dependency); 847 if (auto LB = Subrange->getLowerBound()) 848 if (auto *Dependency = LB.dyn_cast<DIVariable *>()) 849 Result.push_back(Dependency); 850 if (auto UB = Subrange->getUpperBound()) 851 if (auto *Dependency = UB.dyn_cast<DIVariable *>()) 852 Result.push_back(Dependency); 853 if (auto ST = Subrange->getStride()) 854 if (auto *Dependency = ST.dyn_cast<DIVariable *>()) 855 Result.push_back(Dependency); 856 } else if (auto *GenericSubrange = dyn_cast<DIGenericSubrange>(El)) { 857 if (auto Count = GenericSubrange->getCount()) 858 if (auto *Dependency = Count.dyn_cast<DIVariable *>()) 859 Result.push_back(Dependency); 860 if (auto LB = GenericSubrange->getLowerBound()) 861 if (auto *Dependency = LB.dyn_cast<DIVariable *>()) 862 Result.push_back(Dependency); 863 if (auto UB = GenericSubrange->getUpperBound()) 864 if (auto *Dependency = UB.dyn_cast<DIVariable *>()) 865 Result.push_back(Dependency); 866 if (auto ST = GenericSubrange->getStride()) 867 if (auto *Dependency = ST.dyn_cast<DIVariable *>()) 868 Result.push_back(Dependency); 869 } 870 } 871 return Result; 872 } 873 874 /// Sort local variables so that variables appearing inside of helper 875 /// expressions come first. 876 static SmallVector<DbgVariable *, 8> 877 sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) { 878 SmallVector<DbgVariable *, 8> Result; 879 SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList; 880 // Map back from a DIVariable to its containing DbgVariable. 881 SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar; 882 // Set of DbgVariables in Result. 883 SmallDenseSet<DbgVariable *, 8> Visited; 884 // For cycle detection. 885 SmallDenseSet<DbgVariable *, 8> Visiting; 886 887 // Initialize the worklist and the DIVariable lookup table. 888 for (auto Var : reverse(Input)) { 889 DbgVar.insert({Var->getVariable(), Var}); 890 WorkList.push_back({Var, 0}); 891 } 892 893 // Perform a stable topological sort by doing a DFS. 894 while (!WorkList.empty()) { 895 auto Item = WorkList.back(); 896 DbgVariable *Var = Item.getPointer(); 897 bool visitedAllDependencies = Item.getInt(); 898 WorkList.pop_back(); 899 900 // Dependency is in a different lexical scope or a global. 901 if (!Var) 902 continue; 903 904 // Already handled. 905 if (Visited.count(Var)) 906 continue; 907 908 // Add to Result if all dependencies are visited. 909 if (visitedAllDependencies) { 910 Visited.insert(Var); 911 Result.push_back(Var); 912 continue; 913 } 914 915 // Detect cycles. 916 auto Res = Visiting.insert(Var); 917 if (!Res.second) { 918 assert(false && "dependency cycle in local variables"); 919 return Result; 920 } 921 922 // Push dependencies and this node onto the worklist, so that this node is 923 // visited again after all of its dependencies are handled. 924 WorkList.push_back({Var, 1}); 925 for (auto *Dependency : dependencies(Var)) { 926 auto Dep = dyn_cast_or_null<const DILocalVariable>(Dependency); 927 WorkList.push_back({DbgVar[Dep], 0}); 928 } 929 } 930 return Result; 931 } 932 933 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope, 934 SmallVectorImpl<DIE *> &Children, 935 bool *HasNonScopeChildren) { 936 assert(Children.empty()); 937 DIE *ObjectPointer = nullptr; 938 939 // Emit function arguments (order is significant). 940 auto Vars = DU->getScopeVariables().lookup(Scope); 941 for (auto &DV : Vars.Args) 942 Children.push_back(constructVariableDIE(*DV.second, *Scope, ObjectPointer)); 943 944 // Emit local variables. 945 auto Locals = sortLocalVars(Vars.Locals); 946 for (DbgVariable *DV : Locals) 947 Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer)); 948 949 // Skip imported directives in gmlt-like data. 950 if (!includeMinimalInlineScopes()) { 951 // There is no need to emit empty lexical block DIE. 952 for (const auto *IE : ImportedEntities[Scope->getScopeNode()]) 953 Children.push_back( 954 constructImportedEntityDIE(cast<DIImportedEntity>(IE))); 955 } 956 957 if (HasNonScopeChildren) 958 *HasNonScopeChildren = !Children.empty(); 959 960 for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope)) 961 Children.push_back(constructLabelDIE(*DL, *Scope)); 962 963 for (LexicalScope *LS : Scope->getChildren()) 964 constructScopeDIE(LS, Children); 965 966 return ObjectPointer; 967 } 968 969 DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub, 970 LexicalScope *Scope) { 971 DIE &ScopeDIE = updateSubprogramScopeDIE(Sub); 972 973 if (Scope) { 974 assert(!Scope->getInlinedAt()); 975 assert(!Scope->isAbstractScope()); 976 // Collect lexical scope children first. 977 // ObjectPointer might be a local (non-argument) local variable if it's a 978 // block's synthetic this pointer. 979 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE)) 980 addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer); 981 } 982 983 // If this is a variadic function, add an unspecified parameter. 984 DITypeRefArray FnArgs = Sub->getType()->getTypeArray(); 985 986 // If we have a single element of null, it is a function that returns void. 987 // If we have more than one elements and the last one is null, it is a 988 // variadic function. 989 if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] && 990 !includeMinimalInlineScopes()) 991 ScopeDIE.addChild( 992 DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters)); 993 994 return ScopeDIE; 995 } 996 997 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope, 998 DIE &ScopeDIE) { 999 // We create children when the scope DIE is not null. 1000 SmallVector<DIE *, 8> Children; 1001 DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children); 1002 1003 // Add children 1004 for (auto &I : Children) 1005 ScopeDIE.addChild(std::move(I)); 1006 1007 return ObjectPointer; 1008 } 1009 1010 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE( 1011 LexicalScope *Scope) { 1012 DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()]; 1013 if (AbsDef) 1014 return; 1015 1016 auto *SP = cast<DISubprogram>(Scope->getScopeNode()); 1017 1018 DIE *ContextDIE; 1019 DwarfCompileUnit *ContextCU = this; 1020 1021 if (includeMinimalInlineScopes()) 1022 ContextDIE = &getUnitDie(); 1023 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with 1024 // the important distinction that the debug node is not associated with the 1025 // DIE (since the debug node will be associated with the concrete DIE, if 1026 // any). It could be refactored to some common utility function. 1027 else if (auto *SPDecl = SP->getDeclaration()) { 1028 ContextDIE = &getUnitDie(); 1029 getOrCreateSubprogramDIE(SPDecl); 1030 } else { 1031 ContextDIE = getOrCreateContextDIE(SP->getScope()); 1032 // The scope may be shared with a subprogram that has already been 1033 // constructed in another CU, in which case we need to construct this 1034 // subprogram in the same CU. 1035 ContextCU = DD->lookupCU(ContextDIE->getUnitDie()); 1036 } 1037 1038 // Passing null as the associated node because the abstract definition 1039 // shouldn't be found by lookup. 1040 AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr); 1041 ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef); 1042 1043 if (!ContextCU->includeMinimalInlineScopes()) 1044 ContextCU->addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined); 1045 if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef)) 1046 ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer); 1047 } 1048 1049 bool DwarfCompileUnit::useGNUAnalogForDwarf5Feature() const { 1050 return DD->getDwarfVersion() == 4 && !DD->tuneForLLDB(); 1051 } 1052 1053 dwarf::Tag DwarfCompileUnit::getDwarf5OrGNUTag(dwarf::Tag Tag) const { 1054 if (!useGNUAnalogForDwarf5Feature()) 1055 return Tag; 1056 switch (Tag) { 1057 case dwarf::DW_TAG_call_site: 1058 return dwarf::DW_TAG_GNU_call_site; 1059 case dwarf::DW_TAG_call_site_parameter: 1060 return dwarf::DW_TAG_GNU_call_site_parameter; 1061 default: 1062 llvm_unreachable("DWARF5 tag with no GNU analog"); 1063 } 1064 } 1065 1066 dwarf::Attribute 1067 DwarfCompileUnit::getDwarf5OrGNUAttr(dwarf::Attribute Attr) const { 1068 if (!useGNUAnalogForDwarf5Feature()) 1069 return Attr; 1070 switch (Attr) { 1071 case dwarf::DW_AT_call_all_calls: 1072 return dwarf::DW_AT_GNU_all_call_sites; 1073 case dwarf::DW_AT_call_target: 1074 return dwarf::DW_AT_GNU_call_site_target; 1075 case dwarf::DW_AT_call_origin: 1076 return dwarf::DW_AT_abstract_origin; 1077 case dwarf::DW_AT_call_return_pc: 1078 return dwarf::DW_AT_low_pc; 1079 case dwarf::DW_AT_call_value: 1080 return dwarf::DW_AT_GNU_call_site_value; 1081 case dwarf::DW_AT_call_tail_call: 1082 return dwarf::DW_AT_GNU_tail_call; 1083 default: 1084 llvm_unreachable("DWARF5 attribute with no GNU analog"); 1085 } 1086 } 1087 1088 dwarf::LocationAtom 1089 DwarfCompileUnit::getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const { 1090 if (!useGNUAnalogForDwarf5Feature()) 1091 return Loc; 1092 switch (Loc) { 1093 case dwarf::DW_OP_entry_value: 1094 return dwarf::DW_OP_GNU_entry_value; 1095 default: 1096 llvm_unreachable("DWARF5 location atom with no GNU analog"); 1097 } 1098 } 1099 1100 DIE &DwarfCompileUnit::constructCallSiteEntryDIE(DIE &ScopeDIE, 1101 DIE *CalleeDIE, 1102 bool IsTail, 1103 const MCSymbol *PCAddr, 1104 const MCSymbol *CallAddr, 1105 unsigned CallReg) { 1106 // Insert a call site entry DIE within ScopeDIE. 1107 DIE &CallSiteDIE = createAndAddDIE(getDwarf5OrGNUTag(dwarf::DW_TAG_call_site), 1108 ScopeDIE, nullptr); 1109 1110 if (CallReg) { 1111 // Indirect call. 1112 addAddress(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_target), 1113 MachineLocation(CallReg)); 1114 } else { 1115 assert(CalleeDIE && "No DIE for call site entry origin"); 1116 addDIEEntry(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_origin), 1117 *CalleeDIE); 1118 } 1119 1120 if (IsTail) { 1121 // Attach DW_AT_call_tail_call to tail calls for standards compliance. 1122 addFlag(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_tail_call)); 1123 1124 // Attach the address of the branch instruction to allow the debugger to 1125 // show where the tail call occurred. This attribute has no GNU analog. 1126 // 1127 // GDB works backwards from non-standard usage of DW_AT_low_pc (in DWARF4 1128 // mode -- equivalently, in DWARF5 mode, DW_AT_call_return_pc) at tail-call 1129 // site entries to figure out the PC of tail-calling branch instructions. 1130 // This means it doesn't need the compiler to emit DW_AT_call_pc, so we 1131 // don't emit it here. 1132 // 1133 // There's no need to tie non-GDB debuggers to this non-standardness, as it 1134 // adds unnecessary complexity to the debugger. For non-GDB debuggers, emit 1135 // the standard DW_AT_call_pc info. 1136 if (!useGNUAnalogForDwarf5Feature()) 1137 addLabelAddress(CallSiteDIE, dwarf::DW_AT_call_pc, CallAddr); 1138 } 1139 1140 // Attach the return PC to allow the debugger to disambiguate call paths 1141 // from one function to another. 1142 // 1143 // The return PC is only really needed when the call /isn't/ a tail call, but 1144 // GDB expects it in DWARF4 mode, even for tail calls (see the comment above 1145 // the DW_AT_call_pc emission logic for an explanation). 1146 if (!IsTail || useGNUAnalogForDwarf5Feature()) { 1147 assert(PCAddr && "Missing return PC information for a call"); 1148 addLabelAddress(CallSiteDIE, 1149 getDwarf5OrGNUAttr(dwarf::DW_AT_call_return_pc), PCAddr); 1150 } 1151 1152 return CallSiteDIE; 1153 } 1154 1155 void DwarfCompileUnit::constructCallSiteParmEntryDIEs( 1156 DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) { 1157 for (const auto &Param : Params) { 1158 unsigned Register = Param.getRegister(); 1159 auto CallSiteDieParam = 1160 DIE::get(DIEValueAllocator, 1161 getDwarf5OrGNUTag(dwarf::DW_TAG_call_site_parameter)); 1162 insertDIE(CallSiteDieParam); 1163 addAddress(*CallSiteDieParam, dwarf::DW_AT_location, 1164 MachineLocation(Register)); 1165 1166 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1167 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 1168 DwarfExpr.setCallSiteParamValueFlag(); 1169 1170 DwarfDebug::emitDebugLocValue(*Asm, nullptr, Param.getValue(), DwarfExpr); 1171 1172 addBlock(*CallSiteDieParam, getDwarf5OrGNUAttr(dwarf::DW_AT_call_value), 1173 DwarfExpr.finalize()); 1174 1175 CallSiteDIE.addChild(CallSiteDieParam); 1176 } 1177 } 1178 1179 DIE *DwarfCompileUnit::constructImportedEntityDIE( 1180 const DIImportedEntity *Module) { 1181 DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag()); 1182 insertDIE(Module, IMDie); 1183 DIE *EntityDie; 1184 auto *Entity = Module->getEntity(); 1185 if (auto *NS = dyn_cast<DINamespace>(Entity)) 1186 EntityDie = getOrCreateNameSpace(NS); 1187 else if (auto *M = dyn_cast<DIModule>(Entity)) 1188 EntityDie = getOrCreateModule(M); 1189 else if (auto *SP = dyn_cast<DISubprogram>(Entity)) 1190 EntityDie = getOrCreateSubprogramDIE(SP); 1191 else if (auto *T = dyn_cast<DIType>(Entity)) 1192 EntityDie = getOrCreateTypeDIE(T); 1193 else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity)) 1194 EntityDie = getOrCreateGlobalVariableDIE(GV, {}); 1195 else 1196 EntityDie = getDIE(Entity); 1197 assert(EntityDie); 1198 addSourceLine(*IMDie, Module->getLine(), Module->getFile()); 1199 addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie); 1200 StringRef Name = Module->getName(); 1201 if (!Name.empty()) 1202 addString(*IMDie, dwarf::DW_AT_name, Name); 1203 1204 return IMDie; 1205 } 1206 1207 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) { 1208 DIE *D = getDIE(SP); 1209 if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) { 1210 if (D) 1211 // If this subprogram has an abstract definition, reference that 1212 addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE); 1213 } else { 1214 assert(D || includeMinimalInlineScopes()); 1215 if (D) 1216 // And attach the attributes 1217 applySubprogramAttributesToDefinition(SP, *D); 1218 } 1219 } 1220 1221 void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) { 1222 DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity()); 1223 1224 auto *Die = Entity->getDIE(); 1225 /// Label may be used to generate DW_AT_low_pc, so put it outside 1226 /// if/else block. 1227 const DbgLabel *Label = nullptr; 1228 if (AbsEntity && AbsEntity->getDIE()) { 1229 addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE()); 1230 Label = dyn_cast<const DbgLabel>(Entity); 1231 } else { 1232 if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity)) 1233 applyVariableAttributes(*Var, *Die); 1234 else if ((Label = dyn_cast<const DbgLabel>(Entity))) 1235 applyLabelAttributes(*Label, *Die); 1236 else 1237 llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel."); 1238 } 1239 1240 if (Label) 1241 if (const auto *Sym = Label->getSymbol()) 1242 addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym); 1243 } 1244 1245 DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) { 1246 auto &AbstractEntities = getAbstractEntities(); 1247 auto I = AbstractEntities.find(Node); 1248 if (I != AbstractEntities.end()) 1249 return I->second.get(); 1250 return nullptr; 1251 } 1252 1253 void DwarfCompileUnit::createAbstractEntity(const DINode *Node, 1254 LexicalScope *Scope) { 1255 assert(Scope && Scope->isAbstractScope()); 1256 auto &Entity = getAbstractEntities()[Node]; 1257 if (isa<const DILocalVariable>(Node)) { 1258 Entity = std::make_unique<DbgVariable>( 1259 cast<const DILocalVariable>(Node), nullptr /* IA */);; 1260 DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get())); 1261 } else if (isa<const DILabel>(Node)) { 1262 Entity = std::make_unique<DbgLabel>( 1263 cast<const DILabel>(Node), nullptr /* IA */); 1264 DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get())); 1265 } 1266 } 1267 1268 void DwarfCompileUnit::emitHeader(bool UseOffsets) { 1269 // Don't bother labeling the .dwo unit, as its offset isn't used. 1270 if (!Skeleton && !DD->useSectionsAsReferences()) { 1271 LabelBegin = Asm->createTempSymbol("cu_begin"); 1272 Asm->OutStreamer->emitLabel(LabelBegin); 1273 } 1274 1275 dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile 1276 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton 1277 : dwarf::DW_UT_compile; 1278 DwarfUnit::emitCommonHeader(UseOffsets, UT); 1279 if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile) 1280 Asm->emitInt64(getDWOId()); 1281 } 1282 1283 bool DwarfCompileUnit::hasDwarfPubSections() const { 1284 switch (CUNode->getNameTableKind()) { 1285 case DICompileUnit::DebugNameTableKind::None: 1286 return false; 1287 // Opting in to GNU Pubnames/types overrides the default to ensure these are 1288 // generated for things like Gold's gdb_index generation. 1289 case DICompileUnit::DebugNameTableKind::GNU: 1290 return true; 1291 case DICompileUnit::DebugNameTableKind::Default: 1292 return DD->tuneForGDB() && !includeMinimalInlineScopes() && 1293 !CUNode->isDebugDirectivesOnly() && 1294 DD->getAccelTableKind() != AccelTableKind::Apple && 1295 DD->getDwarfVersion() < 5; 1296 } 1297 llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum"); 1298 } 1299 1300 /// addGlobalName - Add a new global name to the compile unit. 1301 void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die, 1302 const DIScope *Context) { 1303 if (!hasDwarfPubSections()) 1304 return; 1305 std::string FullName = getParentContextString(Context) + Name.str(); 1306 GlobalNames[FullName] = &Die; 1307 } 1308 1309 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name, 1310 const DIScope *Context) { 1311 if (!hasDwarfPubSections()) 1312 return; 1313 std::string FullName = getParentContextString(Context) + Name.str(); 1314 // Insert, allowing the entry to remain as-is if it's already present 1315 // This way the CU-level type DIE is preferred over the "can't describe this 1316 // type as a unit offset because it's not really in the CU at all, it's only 1317 // in a type unit" 1318 GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie())); 1319 } 1320 1321 /// Add a new global type to the unit. 1322 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die, 1323 const DIScope *Context) { 1324 if (!hasDwarfPubSections()) 1325 return; 1326 std::string FullName = getParentContextString(Context) + Ty->getName().str(); 1327 GlobalTypes[FullName] = &Die; 1328 } 1329 1330 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty, 1331 const DIScope *Context) { 1332 if (!hasDwarfPubSections()) 1333 return; 1334 std::string FullName = getParentContextString(Context) + Ty->getName().str(); 1335 // Insert, allowing the entry to remain as-is if it's already present 1336 // This way the CU-level type DIE is preferred over the "can't describe this 1337 // type as a unit offset because it's not really in the CU at all, it's only 1338 // in a type unit" 1339 GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie())); 1340 } 1341 1342 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die, 1343 MachineLocation Location) { 1344 if (DV.hasComplexAddress()) 1345 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location); 1346 else 1347 addAddress(Die, dwarf::DW_AT_location, Location); 1348 } 1349 1350 /// Add an address attribute to a die based on the location provided. 1351 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute, 1352 const MachineLocation &Location) { 1353 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1354 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 1355 if (Location.isIndirect()) 1356 DwarfExpr.setMemoryLocationKind(); 1357 1358 DIExpressionCursor Cursor({}); 1359 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo(); 1360 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 1361 return; 1362 DwarfExpr.addExpression(std::move(Cursor)); 1363 1364 // Now attach the location information to the DIE. 1365 addBlock(Die, Attribute, DwarfExpr.finalize()); 1366 1367 if (DwarfExpr.TagOffset) 1368 addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1, 1369 *DwarfExpr.TagOffset); 1370 } 1371 1372 /// Start with the address based on the location provided, and generate the 1373 /// DWARF information necessary to find the actual variable given the extra 1374 /// address information encoded in the DbgVariable, starting from the starting 1375 /// location. Add the DWARF information to the die. 1376 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die, 1377 dwarf::Attribute Attribute, 1378 const MachineLocation &Location) { 1379 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1380 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 1381 const DIExpression *DIExpr = DV.getSingleExpression(); 1382 DwarfExpr.addFragmentOffset(DIExpr); 1383 DwarfExpr.setLocation(Location, DIExpr); 1384 1385 DIExpressionCursor Cursor(DIExpr); 1386 1387 if (DIExpr->isEntryValue()) 1388 DwarfExpr.beginEntryValueExpression(Cursor); 1389 1390 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo(); 1391 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 1392 return; 1393 DwarfExpr.addExpression(std::move(Cursor)); 1394 1395 // Now attach the location information to the DIE. 1396 addBlock(Die, Attribute, DwarfExpr.finalize()); 1397 1398 if (DwarfExpr.TagOffset) 1399 addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1, 1400 *DwarfExpr.TagOffset); 1401 } 1402 1403 /// Add a Dwarf loclistptr attribute data and value. 1404 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute, 1405 unsigned Index) { 1406 dwarf::Form Form = (DD->getDwarfVersion() >= 5) 1407 ? dwarf::DW_FORM_loclistx 1408 : DD->getDwarfSectionOffsetForm(); 1409 Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index)); 1410 } 1411 1412 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var, 1413 DIE &VariableDie) { 1414 StringRef Name = Var.getName(); 1415 if (!Name.empty()) 1416 addString(VariableDie, dwarf::DW_AT_name, Name); 1417 const auto *DIVar = Var.getVariable(); 1418 if (DIVar) 1419 if (uint32_t AlignInBytes = DIVar->getAlignInBytes()) 1420 addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata, 1421 AlignInBytes); 1422 1423 addSourceLine(VariableDie, DIVar); 1424 addType(VariableDie, Var.getType()); 1425 if (Var.isArtificial()) 1426 addFlag(VariableDie, dwarf::DW_AT_artificial); 1427 } 1428 1429 void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label, 1430 DIE &LabelDie) { 1431 StringRef Name = Label.getName(); 1432 if (!Name.empty()) 1433 addString(LabelDie, dwarf::DW_AT_name, Name); 1434 const auto *DILabel = Label.getLabel(); 1435 addSourceLine(LabelDie, DILabel); 1436 } 1437 1438 /// Add a Dwarf expression attribute data and value. 1439 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form, 1440 const MCExpr *Expr) { 1441 Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr)); 1442 } 1443 1444 void DwarfCompileUnit::applySubprogramAttributesToDefinition( 1445 const DISubprogram *SP, DIE &SPDie) { 1446 auto *SPDecl = SP->getDeclaration(); 1447 auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope(); 1448 applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes()); 1449 addGlobalName(SP->getName(), SPDie, Context); 1450 } 1451 1452 bool DwarfCompileUnit::isDwoUnit() const { 1453 return DD->useSplitDwarf() && Skeleton; 1454 } 1455 1456 void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) { 1457 constructTypeDIE(D, CTy); 1458 } 1459 1460 bool DwarfCompileUnit::includeMinimalInlineScopes() const { 1461 return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly || 1462 (DD->useSplitDwarf() && !Skeleton); 1463 } 1464 1465 void DwarfCompileUnit::addAddrTableBase() { 1466 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 1467 MCSymbol *Label = DD->getAddressPool().getLabel(); 1468 addSectionLabel(getUnitDie(), 1469 DD->getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base 1470 : dwarf::DW_AT_GNU_addr_base, 1471 Label, TLOF.getDwarfAddrSection()->getBeginSymbol()); 1472 } 1473 1474 void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) { 1475 Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, dwarf::DW_FORM_udata, 1476 new (DIEValueAllocator) DIEBaseTypeRef(this, Idx)); 1477 } 1478 1479 void DwarfCompileUnit::createBaseTypeDIEs() { 1480 // Insert the base_type DIEs directly after the CU so that their offsets will 1481 // fit in the fixed size ULEB128 used inside the location expressions. 1482 // Maintain order by iterating backwards and inserting to the front of CU 1483 // child list. 1484 for (auto &Btr : reverse(ExprRefedBaseTypes)) { 1485 DIE &Die = getUnitDie().addChildFront( 1486 DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type)); 1487 SmallString<32> Str; 1488 addString(Die, dwarf::DW_AT_name, 1489 Twine(dwarf::AttributeEncodingString(Btr.Encoding) + 1490 "_" + Twine(Btr.BitSize)).toStringRef(Str)); 1491 addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding); 1492 addUInt(Die, dwarf::DW_AT_byte_size, None, Btr.BitSize / 8); 1493 1494 Btr.Die = &Die; 1495 } 1496 } 1497