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