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