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 for (auto *El : Array->getElements()) { 807 if (auto *Subrange = dyn_cast<DISubrange>(El)) { 808 if (auto Count = Subrange->getCount()) 809 if (auto *Dependency = Count.dyn_cast<DIVariable *>()) 810 Result.push_back(Dependency); 811 if (auto LB = Subrange->getLowerBound()) 812 if (auto *Dependency = LB.dyn_cast<DIVariable *>()) 813 Result.push_back(Dependency); 814 if (auto UB = Subrange->getUpperBound()) 815 if (auto *Dependency = UB.dyn_cast<DIVariable *>()) 816 Result.push_back(Dependency); 817 if (auto ST = Subrange->getStride()) 818 if (auto *Dependency = ST.dyn_cast<DIVariable *>()) 819 Result.push_back(Dependency); 820 } 821 } 822 return Result; 823 } 824 825 /// Sort local variables so that variables appearing inside of helper 826 /// expressions come first. 827 static SmallVector<DbgVariable *, 8> 828 sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) { 829 SmallVector<DbgVariable *, 8> Result; 830 SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList; 831 // Map back from a DIVariable to its containing DbgVariable. 832 SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar; 833 // Set of DbgVariables in Result. 834 SmallDenseSet<DbgVariable *, 8> Visited; 835 // For cycle detection. 836 SmallDenseSet<DbgVariable *, 8> Visiting; 837 838 // Initialize the worklist and the DIVariable lookup table. 839 for (auto Var : reverse(Input)) { 840 DbgVar.insert({Var->getVariable(), Var}); 841 WorkList.push_back({Var, 0}); 842 } 843 844 // Perform a stable topological sort by doing a DFS. 845 while (!WorkList.empty()) { 846 auto Item = WorkList.back(); 847 DbgVariable *Var = Item.getPointer(); 848 bool visitedAllDependencies = Item.getInt(); 849 WorkList.pop_back(); 850 851 // Dependency is in a different lexical scope or a global. 852 if (!Var) 853 continue; 854 855 // Already handled. 856 if (Visited.count(Var)) 857 continue; 858 859 // Add to Result if all dependencies are visited. 860 if (visitedAllDependencies) { 861 Visited.insert(Var); 862 Result.push_back(Var); 863 continue; 864 } 865 866 // Detect cycles. 867 auto Res = Visiting.insert(Var); 868 if (!Res.second) { 869 assert(false && "dependency cycle in local variables"); 870 return Result; 871 } 872 873 // Push dependencies and this node onto the worklist, so that this node is 874 // visited again after all of its dependencies are handled. 875 WorkList.push_back({Var, 1}); 876 for (auto *Dependency : dependencies(Var)) { 877 auto Dep = dyn_cast_or_null<const DILocalVariable>(Dependency); 878 WorkList.push_back({DbgVar[Dep], 0}); 879 } 880 } 881 return Result; 882 } 883 884 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope, 885 SmallVectorImpl<DIE *> &Children, 886 bool *HasNonScopeChildren) { 887 assert(Children.empty()); 888 DIE *ObjectPointer = nullptr; 889 890 // Emit function arguments (order is significant). 891 auto Vars = DU->getScopeVariables().lookup(Scope); 892 for (auto &DV : Vars.Args) 893 Children.push_back(constructVariableDIE(*DV.second, *Scope, ObjectPointer)); 894 895 // Emit local variables. 896 auto Locals = sortLocalVars(Vars.Locals); 897 for (DbgVariable *DV : Locals) 898 Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer)); 899 900 // Skip imported directives in gmlt-like data. 901 if (!includeMinimalInlineScopes()) { 902 // There is no need to emit empty lexical block DIE. 903 for (const auto *IE : ImportedEntities[Scope->getScopeNode()]) 904 Children.push_back( 905 constructImportedEntityDIE(cast<DIImportedEntity>(IE))); 906 } 907 908 if (HasNonScopeChildren) 909 *HasNonScopeChildren = !Children.empty(); 910 911 for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope)) 912 Children.push_back(constructLabelDIE(*DL, *Scope)); 913 914 for (LexicalScope *LS : Scope->getChildren()) 915 constructScopeDIE(LS, Children); 916 917 return ObjectPointer; 918 } 919 920 DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub, 921 LexicalScope *Scope) { 922 DIE &ScopeDIE = updateSubprogramScopeDIE(Sub); 923 924 if (Scope) { 925 assert(!Scope->getInlinedAt()); 926 assert(!Scope->isAbstractScope()); 927 // Collect lexical scope children first. 928 // ObjectPointer might be a local (non-argument) local variable if it's a 929 // block's synthetic this pointer. 930 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE)) 931 addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer); 932 } 933 934 // If this is a variadic function, add an unspecified parameter. 935 DITypeRefArray FnArgs = Sub->getType()->getTypeArray(); 936 937 // If we have a single element of null, it is a function that returns void. 938 // If we have more than one elements and the last one is null, it is a 939 // variadic function. 940 if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] && 941 !includeMinimalInlineScopes()) 942 ScopeDIE.addChild( 943 DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters)); 944 945 return ScopeDIE; 946 } 947 948 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope, 949 DIE &ScopeDIE) { 950 // We create children when the scope DIE is not null. 951 SmallVector<DIE *, 8> Children; 952 DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children); 953 954 // Add children 955 for (auto &I : Children) 956 ScopeDIE.addChild(std::move(I)); 957 958 return ObjectPointer; 959 } 960 961 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE( 962 LexicalScope *Scope) { 963 DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()]; 964 if (AbsDef) 965 return; 966 967 auto *SP = cast<DISubprogram>(Scope->getScopeNode()); 968 969 DIE *ContextDIE; 970 DwarfCompileUnit *ContextCU = this; 971 972 if (includeMinimalInlineScopes()) 973 ContextDIE = &getUnitDie(); 974 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with 975 // the important distinction that the debug node is not associated with the 976 // DIE (since the debug node will be associated with the concrete DIE, if 977 // any). It could be refactored to some common utility function. 978 else if (auto *SPDecl = SP->getDeclaration()) { 979 ContextDIE = &getUnitDie(); 980 getOrCreateSubprogramDIE(SPDecl); 981 } else { 982 ContextDIE = getOrCreateContextDIE(SP->getScope()); 983 // The scope may be shared with a subprogram that has already been 984 // constructed in another CU, in which case we need to construct this 985 // subprogram in the same CU. 986 ContextCU = DD->lookupCU(ContextDIE->getUnitDie()); 987 } 988 989 // Passing null as the associated node because the abstract definition 990 // shouldn't be found by lookup. 991 AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr); 992 ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef); 993 994 if (!ContextCU->includeMinimalInlineScopes()) 995 ContextCU->addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined); 996 if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef)) 997 ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer); 998 } 999 1000 bool DwarfCompileUnit::useGNUAnalogForDwarf5Feature() const { 1001 return DD->getDwarfVersion() == 4 && DD->tuneForGDB(); 1002 } 1003 1004 dwarf::Tag DwarfCompileUnit::getDwarf5OrGNUTag(dwarf::Tag Tag) const { 1005 if (!useGNUAnalogForDwarf5Feature()) 1006 return Tag; 1007 switch (Tag) { 1008 case dwarf::DW_TAG_call_site: 1009 return dwarf::DW_TAG_GNU_call_site; 1010 case dwarf::DW_TAG_call_site_parameter: 1011 return dwarf::DW_TAG_GNU_call_site_parameter; 1012 default: 1013 llvm_unreachable("DWARF5 tag with no GNU analog"); 1014 } 1015 } 1016 1017 dwarf::Attribute 1018 DwarfCompileUnit::getDwarf5OrGNUAttr(dwarf::Attribute Attr) const { 1019 if (!useGNUAnalogForDwarf5Feature()) 1020 return Attr; 1021 switch (Attr) { 1022 case dwarf::DW_AT_call_all_calls: 1023 return dwarf::DW_AT_GNU_all_call_sites; 1024 case dwarf::DW_AT_call_target: 1025 return dwarf::DW_AT_GNU_call_site_target; 1026 case dwarf::DW_AT_call_origin: 1027 return dwarf::DW_AT_abstract_origin; 1028 case dwarf::DW_AT_call_return_pc: 1029 return dwarf::DW_AT_low_pc; 1030 case dwarf::DW_AT_call_value: 1031 return dwarf::DW_AT_GNU_call_site_value; 1032 case dwarf::DW_AT_call_tail_call: 1033 return dwarf::DW_AT_GNU_tail_call; 1034 default: 1035 llvm_unreachable("DWARF5 attribute with no GNU analog"); 1036 } 1037 } 1038 1039 dwarf::LocationAtom 1040 DwarfCompileUnit::getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const { 1041 if (!useGNUAnalogForDwarf5Feature()) 1042 return Loc; 1043 switch (Loc) { 1044 case dwarf::DW_OP_entry_value: 1045 return dwarf::DW_OP_GNU_entry_value; 1046 default: 1047 llvm_unreachable("DWARF5 location atom with no GNU analog"); 1048 } 1049 } 1050 1051 DIE &DwarfCompileUnit::constructCallSiteEntryDIE(DIE &ScopeDIE, 1052 DIE *CalleeDIE, 1053 bool IsTail, 1054 const MCSymbol *PCAddr, 1055 const MCSymbol *CallAddr, 1056 unsigned CallReg) { 1057 // Insert a call site entry DIE within ScopeDIE. 1058 DIE &CallSiteDIE = createAndAddDIE(getDwarf5OrGNUTag(dwarf::DW_TAG_call_site), 1059 ScopeDIE, nullptr); 1060 1061 if (CallReg) { 1062 // Indirect call. 1063 addAddress(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_target), 1064 MachineLocation(CallReg)); 1065 } else { 1066 assert(CalleeDIE && "No DIE for call site entry origin"); 1067 addDIEEntry(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_origin), 1068 *CalleeDIE); 1069 } 1070 1071 if (IsTail) { 1072 // Attach DW_AT_call_tail_call to tail calls for standards compliance. 1073 addFlag(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_tail_call)); 1074 1075 // Attach the address of the branch instruction to allow the debugger to 1076 // show where the tail call occurred. This attribute has no GNU analog. 1077 // 1078 // GDB works backwards from non-standard usage of DW_AT_low_pc (in DWARF4 1079 // mode -- equivalently, in DWARF5 mode, DW_AT_call_return_pc) at tail-call 1080 // site entries to figure out the PC of tail-calling branch instructions. 1081 // This means it doesn't need the compiler to emit DW_AT_call_pc, so we 1082 // don't emit it here. 1083 // 1084 // There's no need to tie non-GDB debuggers to this non-standardness, as it 1085 // adds unnecessary complexity to the debugger. For non-GDB debuggers, emit 1086 // the standard DW_AT_call_pc info. 1087 if (!useGNUAnalogForDwarf5Feature()) 1088 addLabelAddress(CallSiteDIE, dwarf::DW_AT_call_pc, CallAddr); 1089 } 1090 1091 // Attach the return PC to allow the debugger to disambiguate call paths 1092 // from one function to another. 1093 // 1094 // The return PC is only really needed when the call /isn't/ a tail call, but 1095 // GDB expects it in DWARF4 mode, even for tail calls (see the comment above 1096 // the DW_AT_call_pc emission logic for an explanation). 1097 if (!IsTail || useGNUAnalogForDwarf5Feature()) { 1098 assert(PCAddr && "Missing return PC information for a call"); 1099 addLabelAddress(CallSiteDIE, 1100 getDwarf5OrGNUAttr(dwarf::DW_AT_call_return_pc), PCAddr); 1101 } 1102 1103 return CallSiteDIE; 1104 } 1105 1106 void DwarfCompileUnit::constructCallSiteParmEntryDIEs( 1107 DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) { 1108 for (const auto &Param : Params) { 1109 unsigned Register = Param.getRegister(); 1110 auto CallSiteDieParam = 1111 DIE::get(DIEValueAllocator, 1112 getDwarf5OrGNUTag(dwarf::DW_TAG_call_site_parameter)); 1113 insertDIE(CallSiteDieParam); 1114 addAddress(*CallSiteDieParam, dwarf::DW_AT_location, 1115 MachineLocation(Register)); 1116 1117 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1118 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 1119 DwarfExpr.setCallSiteParamValueFlag(); 1120 1121 DwarfDebug::emitDebugLocValue(*Asm, nullptr, Param.getValue(), DwarfExpr); 1122 1123 addBlock(*CallSiteDieParam, getDwarf5OrGNUAttr(dwarf::DW_AT_call_value), 1124 DwarfExpr.finalize()); 1125 1126 CallSiteDIE.addChild(CallSiteDieParam); 1127 } 1128 } 1129 1130 DIE *DwarfCompileUnit::constructImportedEntityDIE( 1131 const DIImportedEntity *Module) { 1132 DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag()); 1133 insertDIE(Module, IMDie); 1134 DIE *EntityDie; 1135 auto *Entity = Module->getEntity(); 1136 if (auto *NS = dyn_cast<DINamespace>(Entity)) 1137 EntityDie = getOrCreateNameSpace(NS); 1138 else if (auto *M = dyn_cast<DIModule>(Entity)) 1139 EntityDie = getOrCreateModule(M); 1140 else if (auto *SP = dyn_cast<DISubprogram>(Entity)) 1141 EntityDie = getOrCreateSubprogramDIE(SP); 1142 else if (auto *T = dyn_cast<DIType>(Entity)) 1143 EntityDie = getOrCreateTypeDIE(T); 1144 else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity)) 1145 EntityDie = getOrCreateGlobalVariableDIE(GV, {}); 1146 else 1147 EntityDie = getDIE(Entity); 1148 assert(EntityDie); 1149 addSourceLine(*IMDie, Module->getLine(), Module->getFile()); 1150 addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie); 1151 StringRef Name = Module->getName(); 1152 if (!Name.empty()) 1153 addString(*IMDie, dwarf::DW_AT_name, Name); 1154 1155 return IMDie; 1156 } 1157 1158 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) { 1159 DIE *D = getDIE(SP); 1160 if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) { 1161 if (D) 1162 // If this subprogram has an abstract definition, reference that 1163 addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE); 1164 } else { 1165 assert(D || includeMinimalInlineScopes()); 1166 if (D) 1167 // And attach the attributes 1168 applySubprogramAttributesToDefinition(SP, *D); 1169 } 1170 } 1171 1172 void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) { 1173 DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity()); 1174 1175 auto *Die = Entity->getDIE(); 1176 /// Label may be used to generate DW_AT_low_pc, so put it outside 1177 /// if/else block. 1178 const DbgLabel *Label = nullptr; 1179 if (AbsEntity && AbsEntity->getDIE()) { 1180 addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE()); 1181 Label = dyn_cast<const DbgLabel>(Entity); 1182 } else { 1183 if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity)) 1184 applyVariableAttributes(*Var, *Die); 1185 else if ((Label = dyn_cast<const DbgLabel>(Entity))) 1186 applyLabelAttributes(*Label, *Die); 1187 else 1188 llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel."); 1189 } 1190 1191 if (Label) 1192 if (const auto *Sym = Label->getSymbol()) 1193 addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym); 1194 } 1195 1196 DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) { 1197 auto &AbstractEntities = getAbstractEntities(); 1198 auto I = AbstractEntities.find(Node); 1199 if (I != AbstractEntities.end()) 1200 return I->second.get(); 1201 return nullptr; 1202 } 1203 1204 void DwarfCompileUnit::createAbstractEntity(const DINode *Node, 1205 LexicalScope *Scope) { 1206 assert(Scope && Scope->isAbstractScope()); 1207 auto &Entity = getAbstractEntities()[Node]; 1208 if (isa<const DILocalVariable>(Node)) { 1209 Entity = std::make_unique<DbgVariable>( 1210 cast<const DILocalVariable>(Node), nullptr /* IA */);; 1211 DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get())); 1212 } else if (isa<const DILabel>(Node)) { 1213 Entity = std::make_unique<DbgLabel>( 1214 cast<const DILabel>(Node), nullptr /* IA */); 1215 DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get())); 1216 } 1217 } 1218 1219 void DwarfCompileUnit::emitHeader(bool UseOffsets) { 1220 // Don't bother labeling the .dwo unit, as its offset isn't used. 1221 if (!Skeleton && !DD->useSectionsAsReferences()) { 1222 LabelBegin = Asm->createTempSymbol("cu_begin"); 1223 Asm->OutStreamer->emitLabel(LabelBegin); 1224 } 1225 1226 dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile 1227 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton 1228 : dwarf::DW_UT_compile; 1229 DwarfUnit::emitCommonHeader(UseOffsets, UT); 1230 if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile) 1231 Asm->emitInt64(getDWOId()); 1232 } 1233 1234 bool DwarfCompileUnit::hasDwarfPubSections() const { 1235 switch (CUNode->getNameTableKind()) { 1236 case DICompileUnit::DebugNameTableKind::None: 1237 return false; 1238 // Opting in to GNU Pubnames/types overrides the default to ensure these are 1239 // generated for things like Gold's gdb_index generation. 1240 case DICompileUnit::DebugNameTableKind::GNU: 1241 return true; 1242 case DICompileUnit::DebugNameTableKind::Default: 1243 return DD->tuneForGDB() && !includeMinimalInlineScopes() && 1244 !CUNode->isDebugDirectivesOnly() && 1245 DD->getAccelTableKind() != AccelTableKind::Apple && 1246 DD->getDwarfVersion() < 5; 1247 } 1248 llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum"); 1249 } 1250 1251 /// addGlobalName - Add a new global name to the compile unit. 1252 void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die, 1253 const DIScope *Context) { 1254 if (!hasDwarfPubSections()) 1255 return; 1256 std::string FullName = getParentContextString(Context) + Name.str(); 1257 GlobalNames[FullName] = &Die; 1258 } 1259 1260 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name, 1261 const DIScope *Context) { 1262 if (!hasDwarfPubSections()) 1263 return; 1264 std::string FullName = getParentContextString(Context) + Name.str(); 1265 // Insert, allowing the entry to remain as-is if it's already present 1266 // This way the CU-level type DIE is preferred over the "can't describe this 1267 // type as a unit offset because it's not really in the CU at all, it's only 1268 // in a type unit" 1269 GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie())); 1270 } 1271 1272 /// Add a new global type to the unit. 1273 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die, 1274 const DIScope *Context) { 1275 if (!hasDwarfPubSections()) 1276 return; 1277 std::string FullName = getParentContextString(Context) + Ty->getName().str(); 1278 GlobalTypes[FullName] = &Die; 1279 } 1280 1281 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty, 1282 const DIScope *Context) { 1283 if (!hasDwarfPubSections()) 1284 return; 1285 std::string FullName = getParentContextString(Context) + Ty->getName().str(); 1286 // Insert, allowing the entry to remain as-is if it's already present 1287 // This way the CU-level type DIE is preferred over the "can't describe this 1288 // type as a unit offset because it's not really in the CU at all, it's only 1289 // in a type unit" 1290 GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie())); 1291 } 1292 1293 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die, 1294 MachineLocation Location) { 1295 if (DV.hasComplexAddress()) 1296 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location); 1297 else 1298 addAddress(Die, dwarf::DW_AT_location, Location); 1299 } 1300 1301 /// Add an address attribute to a die based on the location provided. 1302 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute, 1303 const MachineLocation &Location) { 1304 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1305 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 1306 if (Location.isIndirect()) 1307 DwarfExpr.setMemoryLocationKind(); 1308 1309 DIExpressionCursor Cursor({}); 1310 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo(); 1311 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 1312 return; 1313 DwarfExpr.addExpression(std::move(Cursor)); 1314 1315 // Now attach the location information to the DIE. 1316 addBlock(Die, Attribute, DwarfExpr.finalize()); 1317 1318 if (DwarfExpr.TagOffset) 1319 addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1, 1320 *DwarfExpr.TagOffset); 1321 } 1322 1323 /// Start with the address based on the location provided, and generate the 1324 /// DWARF information necessary to find the actual variable given the extra 1325 /// address information encoded in the DbgVariable, starting from the starting 1326 /// location. Add the DWARF information to the die. 1327 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die, 1328 dwarf::Attribute Attribute, 1329 const MachineLocation &Location) { 1330 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1331 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 1332 const DIExpression *DIExpr = DV.getSingleExpression(); 1333 DwarfExpr.addFragmentOffset(DIExpr); 1334 DwarfExpr.setLocation(Location, DIExpr); 1335 1336 DIExpressionCursor Cursor(DIExpr); 1337 1338 if (DIExpr->isEntryValue()) 1339 DwarfExpr.beginEntryValueExpression(Cursor); 1340 1341 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo(); 1342 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 1343 return; 1344 DwarfExpr.addExpression(std::move(Cursor)); 1345 1346 // Now attach the location information to the DIE. 1347 addBlock(Die, Attribute, DwarfExpr.finalize()); 1348 1349 if (DwarfExpr.TagOffset) 1350 addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1, 1351 *DwarfExpr.TagOffset); 1352 } 1353 1354 /// Add a Dwarf loclistptr attribute data and value. 1355 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute, 1356 unsigned Index) { 1357 dwarf::Form Form = dwarf::DW_FORM_data4; 1358 if (DD->getDwarfVersion() == 4) 1359 Form =dwarf::DW_FORM_sec_offset; 1360 if (DD->getDwarfVersion() >= 5) 1361 Form =dwarf::DW_FORM_loclistx; 1362 Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index)); 1363 } 1364 1365 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var, 1366 DIE &VariableDie) { 1367 StringRef Name = Var.getName(); 1368 if (!Name.empty()) 1369 addString(VariableDie, dwarf::DW_AT_name, Name); 1370 const auto *DIVar = Var.getVariable(); 1371 if (DIVar) 1372 if (uint32_t AlignInBytes = DIVar->getAlignInBytes()) 1373 addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata, 1374 AlignInBytes); 1375 1376 addSourceLine(VariableDie, DIVar); 1377 addType(VariableDie, Var.getType()); 1378 if (Var.isArtificial()) 1379 addFlag(VariableDie, dwarf::DW_AT_artificial); 1380 } 1381 1382 void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label, 1383 DIE &LabelDie) { 1384 StringRef Name = Label.getName(); 1385 if (!Name.empty()) 1386 addString(LabelDie, dwarf::DW_AT_name, Name); 1387 const auto *DILabel = Label.getLabel(); 1388 addSourceLine(LabelDie, DILabel); 1389 } 1390 1391 /// Add a Dwarf expression attribute data and value. 1392 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form, 1393 const MCExpr *Expr) { 1394 Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr)); 1395 } 1396 1397 void DwarfCompileUnit::applySubprogramAttributesToDefinition( 1398 const DISubprogram *SP, DIE &SPDie) { 1399 auto *SPDecl = SP->getDeclaration(); 1400 auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope(); 1401 applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes()); 1402 addGlobalName(SP->getName(), SPDie, Context); 1403 } 1404 1405 bool DwarfCompileUnit::isDwoUnit() const { 1406 return DD->useSplitDwarf() && Skeleton; 1407 } 1408 1409 void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) { 1410 constructTypeDIE(D, CTy); 1411 } 1412 1413 bool DwarfCompileUnit::includeMinimalInlineScopes() const { 1414 return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly || 1415 (DD->useSplitDwarf() && !Skeleton); 1416 } 1417 1418 void DwarfCompileUnit::addAddrTableBase() { 1419 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 1420 MCSymbol *Label = DD->getAddressPool().getLabel(); 1421 addSectionLabel(getUnitDie(), 1422 getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base 1423 : dwarf::DW_AT_GNU_addr_base, 1424 Label, TLOF.getDwarfAddrSection()->getBeginSymbol()); 1425 } 1426 1427 void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) { 1428 Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, dwarf::DW_FORM_udata, 1429 new (DIEValueAllocator) DIEBaseTypeRef(this, Idx)); 1430 } 1431 1432 void DwarfCompileUnit::createBaseTypeDIEs() { 1433 // Insert the base_type DIEs directly after the CU so that their offsets will 1434 // fit in the fixed size ULEB128 used inside the location expressions. 1435 // Maintain order by iterating backwards and inserting to the front of CU 1436 // child list. 1437 for (auto &Btr : reverse(ExprRefedBaseTypes)) { 1438 DIE &Die = getUnitDie().addChildFront( 1439 DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type)); 1440 SmallString<32> Str; 1441 addString(Die, dwarf::DW_AT_name, 1442 Twine(dwarf::AttributeEncodingString(Btr.Encoding) + 1443 "_" + Twine(Btr.BitSize)).toStringRef(Str)); 1444 addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding); 1445 addUInt(Die, dwarf::DW_AT_byte_size, None, Btr.BitSize / 8); 1446 1447 Btr.Die = &Die; 1448 } 1449 } 1450