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 assert(!Ranges.empty()); 562 if (!DD->useRangesSection() || 563 (Ranges.size() == 1 && 564 (!DD->alwaysUseRanges() || 565 DD->getSectionLabel(&Ranges.front().Begin->getSection()) == 566 Ranges.front().Begin))) { 567 const RangeSpan &Front = Ranges.front(); 568 const RangeSpan &Back = Ranges.back(); 569 attachLowHighPC(Die, Front.Begin, Back.End); 570 } else 571 addScopeRangeList(Die, std::move(Ranges)); 572 } 573 574 void DwarfCompileUnit::attachRangesOrLowHighPC( 575 DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) { 576 SmallVector<RangeSpan, 2> List; 577 List.reserve(Ranges.size()); 578 for (const InsnRange &R : Ranges) { 579 auto *BeginLabel = DD->getLabelBeforeInsn(R.first); 580 auto *EndLabel = DD->getLabelAfterInsn(R.second); 581 582 const auto *BeginMBB = R.first->getParent(); 583 const auto *EndMBB = R.second->getParent(); 584 585 const auto *MBB = BeginMBB; 586 // Basic block sections allows basic block subsets to be placed in unique 587 // sections. For each section, the begin and end label must be added to the 588 // list. If there is more than one range, debug ranges must be used. 589 // Otherwise, low/high PC can be used. 590 // FIXME: Debug Info Emission depends on block order and this assumes that 591 // the order of blocks will be frozen beyond this point. 592 do { 593 if (MBB->sameSection(EndMBB) || MBB->isEndSection()) { 594 auto MBBSectionRange = Asm->MBBSectionRanges[MBB->getSectionIDNum()]; 595 List.push_back( 596 {MBB->sameSection(BeginMBB) ? BeginLabel 597 : MBBSectionRange.BeginLabel, 598 MBB->sameSection(EndMBB) ? EndLabel : MBBSectionRange.EndLabel}); 599 } 600 if (MBB->sameSection(EndMBB)) 601 break; 602 MBB = MBB->getNextNode(); 603 } while (true); 604 } 605 attachRangesOrLowHighPC(Die, std::move(List)); 606 } 607 608 // This scope represents inlined body of a function. Construct DIE to 609 // represent this concrete inlined copy of the function. 610 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) { 611 assert(Scope->getScopeNode()); 612 auto *DS = Scope->getScopeNode(); 613 auto *InlinedSP = getDISubprogram(DS); 614 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram 615 // was inlined from another compile unit. 616 DIE *OriginDIE = getAbstractSPDies()[InlinedSP]; 617 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram."); 618 619 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine); 620 addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE); 621 622 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges()); 623 624 // Add the call site information to the DIE. 625 const DILocation *IA = Scope->getInlinedAt(); 626 addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None, 627 getOrCreateSourceID(IA->getFile())); 628 addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine()); 629 if (IA->getColumn()) 630 addUInt(*ScopeDIE, dwarf::DW_AT_call_column, None, IA->getColumn()); 631 if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4) 632 addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None, 633 IA->getDiscriminator()); 634 635 // Add name to the name table, we do this here because we're guaranteed 636 // to have concrete versions of our DW_TAG_inlined_subprogram nodes. 637 DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE); 638 639 return ScopeDIE; 640 } 641 642 // Construct new DW_TAG_lexical_block for this scope and attach 643 // DW_AT_low_pc/DW_AT_high_pc labels. 644 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) { 645 if (DD->isLexicalScopeDIENull(Scope)) 646 return nullptr; 647 648 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block); 649 if (Scope->isAbstractScope()) 650 return ScopeDIE; 651 652 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges()); 653 654 return ScopeDIE; 655 } 656 657 /// constructVariableDIE - Construct a DIE for the given DbgVariable. 658 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) { 659 auto D = constructVariableDIEImpl(DV, Abstract); 660 DV.setDIE(*D); 661 return D; 662 } 663 664 DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL, 665 const LexicalScope &Scope) { 666 auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag()); 667 insertDIE(DL.getLabel(), LabelDie); 668 DL.setDIE(*LabelDie); 669 670 if (Scope.isAbstractScope()) 671 applyLabelAttributes(DL, *LabelDie); 672 673 return LabelDie; 674 } 675 676 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV, 677 bool Abstract) { 678 // Define variable debug information entry. 679 auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag()); 680 insertDIE(DV.getVariable(), VariableDie); 681 682 if (Abstract) { 683 applyVariableAttributes(DV, *VariableDie); 684 return VariableDie; 685 } 686 687 // Add variable address. 688 689 unsigned Index = DV.getDebugLocListIndex(); 690 if (Index != ~0U) { 691 addLocationList(*VariableDie, dwarf::DW_AT_location, Index); 692 auto TagOffset = DV.getDebugLocListTagOffset(); 693 if (TagOffset) 694 addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1, 695 *TagOffset); 696 return VariableDie; 697 } 698 699 // Check if variable has a single location description. 700 if (auto *DVal = DV.getValueLoc()) { 701 if (DVal->isLocation()) 702 addVariableAddress(DV, *VariableDie, DVal->getLoc()); 703 else if (DVal->isInt()) { 704 auto *Expr = DV.getSingleExpression(); 705 if (Expr && Expr->getNumElements()) { 706 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 707 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 708 // If there is an expression, emit raw unsigned bytes. 709 DwarfExpr.addFragmentOffset(Expr); 710 DwarfExpr.addUnsignedConstant(DVal->getInt()); 711 DwarfExpr.addExpression(Expr); 712 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize()); 713 if (DwarfExpr.TagOffset) 714 addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, 715 dwarf::DW_FORM_data1, *DwarfExpr.TagOffset); 716 717 } else 718 addConstantValue(*VariableDie, DVal->getInt(), DV.getType()); 719 } else if (DVal->isConstantFP()) { 720 addConstantFPValue(*VariableDie, DVal->getConstantFP()); 721 } else if (DVal->isConstantInt()) { 722 addConstantValue(*VariableDie, DVal->getConstantInt(), DV.getType()); 723 } 724 return VariableDie; 725 } 726 727 // .. else use frame index. 728 if (!DV.hasFrameIndexExprs()) 729 return VariableDie; 730 731 Optional<unsigned> NVPTXAddressSpace; 732 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 733 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 734 for (auto &Fragment : DV.getFrameIndexExprs()) { 735 Register FrameReg; 736 const DIExpression *Expr = Fragment.Expr; 737 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering(); 738 StackOffset Offset = 739 TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg); 740 DwarfExpr.addFragmentOffset(Expr); 741 742 auto *TRI = Asm->MF->getSubtarget().getRegisterInfo(); 743 SmallVector<uint64_t, 8> Ops; 744 TRI->getOffsetOpcodes(Offset, Ops); 745 746 // According to 747 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf 748 // cuda-gdb requires DW_AT_address_class for all variables to be able to 749 // correctly interpret address space of the variable address. 750 // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef 751 // sequence for the NVPTX + gdb target. 752 unsigned LocalNVPTXAddressSpace; 753 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) { 754 const DIExpression *NewExpr = 755 DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace); 756 if (NewExpr != Expr) { 757 Expr = NewExpr; 758 NVPTXAddressSpace = LocalNVPTXAddressSpace; 759 } 760 } 761 if (Expr) 762 Ops.append(Expr->elements_begin(), Expr->elements_end()); 763 DIExpressionCursor Cursor(Ops); 764 DwarfExpr.setMemoryLocationKind(); 765 if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol()) 766 addOpAddress(*Loc, FrameSymbol); 767 else 768 DwarfExpr.addMachineRegExpression( 769 *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg); 770 DwarfExpr.addExpression(std::move(Cursor)); 771 } 772 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) { 773 // According to 774 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf 775 // cuda-gdb requires DW_AT_address_class for all variables to be able to 776 // correctly interpret address space of the variable address. 777 const unsigned NVPTX_ADDR_local_space = 6; 778 addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1, 779 NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space); 780 } 781 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize()); 782 if (DwarfExpr.TagOffset) 783 addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1, 784 *DwarfExpr.TagOffset); 785 786 return VariableDie; 787 } 788 789 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, 790 const LexicalScope &Scope, 791 DIE *&ObjectPointer) { 792 auto Var = constructVariableDIE(DV, Scope.isAbstractScope()); 793 if (DV.isObjectPointer()) 794 ObjectPointer = Var; 795 return Var; 796 } 797 798 /// Return all DIVariables that appear in count: expressions. 799 static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) { 800 SmallVector<const DIVariable *, 2> Result; 801 auto *Array = dyn_cast<DICompositeType>(Var->getType()); 802 if (!Array || Array->getTag() != dwarf::DW_TAG_array_type) 803 return Result; 804 if (auto *DLVar = Array->getDataLocation()) 805 Result.push_back(DLVar); 806 if (auto *AsVar = Array->getAssociated()) 807 Result.push_back(AsVar); 808 if (auto *AlVar = Array->getAllocated()) 809 Result.push_back(AlVar); 810 for (auto *El : Array->getElements()) { 811 if (auto *Subrange = dyn_cast<DISubrange>(El)) { 812 if (auto Count = Subrange->getCount()) 813 if (auto *Dependency = Count.dyn_cast<DIVariable *>()) 814 Result.push_back(Dependency); 815 if (auto LB = Subrange->getLowerBound()) 816 if (auto *Dependency = LB.dyn_cast<DIVariable *>()) 817 Result.push_back(Dependency); 818 if (auto UB = Subrange->getUpperBound()) 819 if (auto *Dependency = UB.dyn_cast<DIVariable *>()) 820 Result.push_back(Dependency); 821 if (auto ST = Subrange->getStride()) 822 if (auto *Dependency = ST.dyn_cast<DIVariable *>()) 823 Result.push_back(Dependency); 824 } else if (auto *GenericSubrange = dyn_cast<DIGenericSubrange>(El)) { 825 if (auto Count = GenericSubrange->getCount()) 826 if (auto *Dependency = Count.dyn_cast<DIVariable *>()) 827 Result.push_back(Dependency); 828 if (auto LB = GenericSubrange->getLowerBound()) 829 if (auto *Dependency = LB.dyn_cast<DIVariable *>()) 830 Result.push_back(Dependency); 831 if (auto UB = GenericSubrange->getUpperBound()) 832 if (auto *Dependency = UB.dyn_cast<DIVariable *>()) 833 Result.push_back(Dependency); 834 if (auto ST = GenericSubrange->getStride()) 835 if (auto *Dependency = ST.dyn_cast<DIVariable *>()) 836 Result.push_back(Dependency); 837 } 838 } 839 return Result; 840 } 841 842 /// Sort local variables so that variables appearing inside of helper 843 /// expressions come first. 844 static SmallVector<DbgVariable *, 8> 845 sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) { 846 SmallVector<DbgVariable *, 8> Result; 847 SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList; 848 // Map back from a DIVariable to its containing DbgVariable. 849 SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar; 850 // Set of DbgVariables in Result. 851 SmallDenseSet<DbgVariable *, 8> Visited; 852 // For cycle detection. 853 SmallDenseSet<DbgVariable *, 8> Visiting; 854 855 // Initialize the worklist and the DIVariable lookup table. 856 for (auto Var : reverse(Input)) { 857 DbgVar.insert({Var->getVariable(), Var}); 858 WorkList.push_back({Var, 0}); 859 } 860 861 // Perform a stable topological sort by doing a DFS. 862 while (!WorkList.empty()) { 863 auto Item = WorkList.back(); 864 DbgVariable *Var = Item.getPointer(); 865 bool visitedAllDependencies = Item.getInt(); 866 WorkList.pop_back(); 867 868 // Dependency is in a different lexical scope or a global. 869 if (!Var) 870 continue; 871 872 // Already handled. 873 if (Visited.count(Var)) 874 continue; 875 876 // Add to Result if all dependencies are visited. 877 if (visitedAllDependencies) { 878 Visited.insert(Var); 879 Result.push_back(Var); 880 continue; 881 } 882 883 // Detect cycles. 884 auto Res = Visiting.insert(Var); 885 if (!Res.second) { 886 assert(false && "dependency cycle in local variables"); 887 return Result; 888 } 889 890 // Push dependencies and this node onto the worklist, so that this node is 891 // visited again after all of its dependencies are handled. 892 WorkList.push_back({Var, 1}); 893 for (auto *Dependency : dependencies(Var)) { 894 auto Dep = dyn_cast_or_null<const DILocalVariable>(Dependency); 895 WorkList.push_back({DbgVar[Dep], 0}); 896 } 897 } 898 return Result; 899 } 900 901 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope, 902 SmallVectorImpl<DIE *> &Children, 903 bool *HasNonScopeChildren) { 904 assert(Children.empty()); 905 DIE *ObjectPointer = nullptr; 906 907 // Emit function arguments (order is significant). 908 auto Vars = DU->getScopeVariables().lookup(Scope); 909 for (auto &DV : Vars.Args) 910 Children.push_back(constructVariableDIE(*DV.second, *Scope, ObjectPointer)); 911 912 // Emit local variables. 913 auto Locals = sortLocalVars(Vars.Locals); 914 for (DbgVariable *DV : Locals) 915 Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer)); 916 917 // Skip imported directives in gmlt-like data. 918 if (!includeMinimalInlineScopes()) { 919 // There is no need to emit empty lexical block DIE. 920 for (const auto *IE : ImportedEntities[Scope->getScopeNode()]) 921 Children.push_back( 922 constructImportedEntityDIE(cast<DIImportedEntity>(IE))); 923 } 924 925 if (HasNonScopeChildren) 926 *HasNonScopeChildren = !Children.empty(); 927 928 for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope)) 929 Children.push_back(constructLabelDIE(*DL, *Scope)); 930 931 for (LexicalScope *LS : Scope->getChildren()) 932 constructScopeDIE(LS, Children); 933 934 return ObjectPointer; 935 } 936 937 DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub, 938 LexicalScope *Scope) { 939 DIE &ScopeDIE = updateSubprogramScopeDIE(Sub); 940 941 if (Scope) { 942 assert(!Scope->getInlinedAt()); 943 assert(!Scope->isAbstractScope()); 944 // Collect lexical scope children first. 945 // ObjectPointer might be a local (non-argument) local variable if it's a 946 // block's synthetic this pointer. 947 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE)) 948 addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer); 949 } 950 951 // If this is a variadic function, add an unspecified parameter. 952 DITypeRefArray FnArgs = Sub->getType()->getTypeArray(); 953 954 // If we have a single element of null, it is a function that returns void. 955 // If we have more than one elements and the last one is null, it is a 956 // variadic function. 957 if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] && 958 !includeMinimalInlineScopes()) 959 ScopeDIE.addChild( 960 DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters)); 961 962 return ScopeDIE; 963 } 964 965 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope, 966 DIE &ScopeDIE) { 967 // We create children when the scope DIE is not null. 968 SmallVector<DIE *, 8> Children; 969 DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children); 970 971 // Add children 972 for (auto &I : Children) 973 ScopeDIE.addChild(std::move(I)); 974 975 return ObjectPointer; 976 } 977 978 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE( 979 LexicalScope *Scope) { 980 DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()]; 981 if (AbsDef) 982 return; 983 984 auto *SP = cast<DISubprogram>(Scope->getScopeNode()); 985 986 DIE *ContextDIE; 987 DwarfCompileUnit *ContextCU = this; 988 989 if (includeMinimalInlineScopes()) 990 ContextDIE = &getUnitDie(); 991 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with 992 // the important distinction that the debug node is not associated with the 993 // DIE (since the debug node will be associated with the concrete DIE, if 994 // any). It could be refactored to some common utility function. 995 else if (auto *SPDecl = SP->getDeclaration()) { 996 ContextDIE = &getUnitDie(); 997 getOrCreateSubprogramDIE(SPDecl); 998 } else { 999 ContextDIE = getOrCreateContextDIE(SP->getScope()); 1000 // The scope may be shared with a subprogram that has already been 1001 // constructed in another CU, in which case we need to construct this 1002 // subprogram in the same CU. 1003 ContextCU = DD->lookupCU(ContextDIE->getUnitDie()); 1004 } 1005 1006 // Passing null as the associated node because the abstract definition 1007 // shouldn't be found by lookup. 1008 AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr); 1009 ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef); 1010 1011 if (!ContextCU->includeMinimalInlineScopes()) 1012 ContextCU->addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined); 1013 if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef)) 1014 ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer); 1015 } 1016 1017 bool DwarfCompileUnit::useGNUAnalogForDwarf5Feature() const { 1018 return DD->getDwarfVersion() == 4 && !DD->tuneForLLDB(); 1019 } 1020 1021 dwarf::Tag DwarfCompileUnit::getDwarf5OrGNUTag(dwarf::Tag Tag) const { 1022 if (!useGNUAnalogForDwarf5Feature()) 1023 return Tag; 1024 switch (Tag) { 1025 case dwarf::DW_TAG_call_site: 1026 return dwarf::DW_TAG_GNU_call_site; 1027 case dwarf::DW_TAG_call_site_parameter: 1028 return dwarf::DW_TAG_GNU_call_site_parameter; 1029 default: 1030 llvm_unreachable("DWARF5 tag with no GNU analog"); 1031 } 1032 } 1033 1034 dwarf::Attribute 1035 DwarfCompileUnit::getDwarf5OrGNUAttr(dwarf::Attribute Attr) const { 1036 if (!useGNUAnalogForDwarf5Feature()) 1037 return Attr; 1038 switch (Attr) { 1039 case dwarf::DW_AT_call_all_calls: 1040 return dwarf::DW_AT_GNU_all_call_sites; 1041 case dwarf::DW_AT_call_target: 1042 return dwarf::DW_AT_GNU_call_site_target; 1043 case dwarf::DW_AT_call_origin: 1044 return dwarf::DW_AT_abstract_origin; 1045 case dwarf::DW_AT_call_return_pc: 1046 return dwarf::DW_AT_low_pc; 1047 case dwarf::DW_AT_call_value: 1048 return dwarf::DW_AT_GNU_call_site_value; 1049 case dwarf::DW_AT_call_tail_call: 1050 return dwarf::DW_AT_GNU_tail_call; 1051 default: 1052 llvm_unreachable("DWARF5 attribute with no GNU analog"); 1053 } 1054 } 1055 1056 dwarf::LocationAtom 1057 DwarfCompileUnit::getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const { 1058 if (!useGNUAnalogForDwarf5Feature()) 1059 return Loc; 1060 switch (Loc) { 1061 case dwarf::DW_OP_entry_value: 1062 return dwarf::DW_OP_GNU_entry_value; 1063 default: 1064 llvm_unreachable("DWARF5 location atom with no GNU analog"); 1065 } 1066 } 1067 1068 DIE &DwarfCompileUnit::constructCallSiteEntryDIE(DIE &ScopeDIE, 1069 DIE *CalleeDIE, 1070 bool IsTail, 1071 const MCSymbol *PCAddr, 1072 const MCSymbol *CallAddr, 1073 unsigned CallReg) { 1074 // Insert a call site entry DIE within ScopeDIE. 1075 DIE &CallSiteDIE = createAndAddDIE(getDwarf5OrGNUTag(dwarf::DW_TAG_call_site), 1076 ScopeDIE, nullptr); 1077 1078 if (CallReg) { 1079 // Indirect call. 1080 addAddress(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_target), 1081 MachineLocation(CallReg)); 1082 } else { 1083 assert(CalleeDIE && "No DIE for call site entry origin"); 1084 addDIEEntry(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_origin), 1085 *CalleeDIE); 1086 } 1087 1088 if (IsTail) { 1089 // Attach DW_AT_call_tail_call to tail calls for standards compliance. 1090 addFlag(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_tail_call)); 1091 1092 // Attach the address of the branch instruction to allow the debugger to 1093 // show where the tail call occurred. This attribute has no GNU analog. 1094 // 1095 // GDB works backwards from non-standard usage of DW_AT_low_pc (in DWARF4 1096 // mode -- equivalently, in DWARF5 mode, DW_AT_call_return_pc) at tail-call 1097 // site entries to figure out the PC of tail-calling branch instructions. 1098 // This means it doesn't need the compiler to emit DW_AT_call_pc, so we 1099 // don't emit it here. 1100 // 1101 // There's no need to tie non-GDB debuggers to this non-standardness, as it 1102 // adds unnecessary complexity to the debugger. For non-GDB debuggers, emit 1103 // the standard DW_AT_call_pc info. 1104 if (!useGNUAnalogForDwarf5Feature()) 1105 addLabelAddress(CallSiteDIE, dwarf::DW_AT_call_pc, CallAddr); 1106 } 1107 1108 // Attach the return PC to allow the debugger to disambiguate call paths 1109 // from one function to another. 1110 // 1111 // The return PC is only really needed when the call /isn't/ a tail call, but 1112 // GDB expects it in DWARF4 mode, even for tail calls (see the comment above 1113 // the DW_AT_call_pc emission logic for an explanation). 1114 if (!IsTail || useGNUAnalogForDwarf5Feature()) { 1115 assert(PCAddr && "Missing return PC information for a call"); 1116 addLabelAddress(CallSiteDIE, 1117 getDwarf5OrGNUAttr(dwarf::DW_AT_call_return_pc), PCAddr); 1118 } 1119 1120 return CallSiteDIE; 1121 } 1122 1123 void DwarfCompileUnit::constructCallSiteParmEntryDIEs( 1124 DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) { 1125 for (const auto &Param : Params) { 1126 unsigned Register = Param.getRegister(); 1127 auto CallSiteDieParam = 1128 DIE::get(DIEValueAllocator, 1129 getDwarf5OrGNUTag(dwarf::DW_TAG_call_site_parameter)); 1130 insertDIE(CallSiteDieParam); 1131 addAddress(*CallSiteDieParam, dwarf::DW_AT_location, 1132 MachineLocation(Register)); 1133 1134 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1135 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 1136 DwarfExpr.setCallSiteParamValueFlag(); 1137 1138 DwarfDebug::emitDebugLocValue(*Asm, nullptr, Param.getValue(), DwarfExpr); 1139 1140 addBlock(*CallSiteDieParam, getDwarf5OrGNUAttr(dwarf::DW_AT_call_value), 1141 DwarfExpr.finalize()); 1142 1143 CallSiteDIE.addChild(CallSiteDieParam); 1144 } 1145 } 1146 1147 DIE *DwarfCompileUnit::constructImportedEntityDIE( 1148 const DIImportedEntity *Module) { 1149 DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag()); 1150 insertDIE(Module, IMDie); 1151 DIE *EntityDie; 1152 auto *Entity = Module->getEntity(); 1153 if (auto *NS = dyn_cast<DINamespace>(Entity)) 1154 EntityDie = getOrCreateNameSpace(NS); 1155 else if (auto *M = dyn_cast<DIModule>(Entity)) 1156 EntityDie = getOrCreateModule(M); 1157 else if (auto *SP = dyn_cast<DISubprogram>(Entity)) 1158 EntityDie = getOrCreateSubprogramDIE(SP); 1159 else if (auto *T = dyn_cast<DIType>(Entity)) 1160 EntityDie = getOrCreateTypeDIE(T); 1161 else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity)) 1162 EntityDie = getOrCreateGlobalVariableDIE(GV, {}); 1163 else 1164 EntityDie = getDIE(Entity); 1165 assert(EntityDie); 1166 addSourceLine(*IMDie, Module->getLine(), Module->getFile()); 1167 addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie); 1168 StringRef Name = Module->getName(); 1169 if (!Name.empty()) 1170 addString(*IMDie, dwarf::DW_AT_name, Name); 1171 1172 return IMDie; 1173 } 1174 1175 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) { 1176 DIE *D = getDIE(SP); 1177 if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) { 1178 if (D) 1179 // If this subprogram has an abstract definition, reference that 1180 addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE); 1181 } else { 1182 assert(D || includeMinimalInlineScopes()); 1183 if (D) 1184 // And attach the attributes 1185 applySubprogramAttributesToDefinition(SP, *D); 1186 } 1187 } 1188 1189 void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) { 1190 DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity()); 1191 1192 auto *Die = Entity->getDIE(); 1193 /// Label may be used to generate DW_AT_low_pc, so put it outside 1194 /// if/else block. 1195 const DbgLabel *Label = nullptr; 1196 if (AbsEntity && AbsEntity->getDIE()) { 1197 addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE()); 1198 Label = dyn_cast<const DbgLabel>(Entity); 1199 } else { 1200 if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity)) 1201 applyVariableAttributes(*Var, *Die); 1202 else if ((Label = dyn_cast<const DbgLabel>(Entity))) 1203 applyLabelAttributes(*Label, *Die); 1204 else 1205 llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel."); 1206 } 1207 1208 if (Label) 1209 if (const auto *Sym = Label->getSymbol()) 1210 addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym); 1211 } 1212 1213 DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) { 1214 auto &AbstractEntities = getAbstractEntities(); 1215 auto I = AbstractEntities.find(Node); 1216 if (I != AbstractEntities.end()) 1217 return I->second.get(); 1218 return nullptr; 1219 } 1220 1221 void DwarfCompileUnit::createAbstractEntity(const DINode *Node, 1222 LexicalScope *Scope) { 1223 assert(Scope && Scope->isAbstractScope()); 1224 auto &Entity = getAbstractEntities()[Node]; 1225 if (isa<const DILocalVariable>(Node)) { 1226 Entity = std::make_unique<DbgVariable>( 1227 cast<const DILocalVariable>(Node), nullptr /* IA */);; 1228 DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get())); 1229 } else if (isa<const DILabel>(Node)) { 1230 Entity = std::make_unique<DbgLabel>( 1231 cast<const DILabel>(Node), nullptr /* IA */); 1232 DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get())); 1233 } 1234 } 1235 1236 void DwarfCompileUnit::emitHeader(bool UseOffsets) { 1237 // Don't bother labeling the .dwo unit, as its offset isn't used. 1238 if (!Skeleton && !DD->useSectionsAsReferences()) { 1239 LabelBegin = Asm->createTempSymbol("cu_begin"); 1240 Asm->OutStreamer->emitLabel(LabelBegin); 1241 } 1242 1243 dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile 1244 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton 1245 : dwarf::DW_UT_compile; 1246 DwarfUnit::emitCommonHeader(UseOffsets, UT); 1247 if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile) 1248 Asm->emitInt64(getDWOId()); 1249 } 1250 1251 bool DwarfCompileUnit::hasDwarfPubSections() const { 1252 switch (CUNode->getNameTableKind()) { 1253 case DICompileUnit::DebugNameTableKind::None: 1254 return false; 1255 // Opting in to GNU Pubnames/types overrides the default to ensure these are 1256 // generated for things like Gold's gdb_index generation. 1257 case DICompileUnit::DebugNameTableKind::GNU: 1258 return true; 1259 case DICompileUnit::DebugNameTableKind::Default: 1260 return DD->tuneForGDB() && !includeMinimalInlineScopes() && 1261 !CUNode->isDebugDirectivesOnly() && 1262 DD->getAccelTableKind() != AccelTableKind::Apple && 1263 DD->getDwarfVersion() < 5; 1264 } 1265 llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum"); 1266 } 1267 1268 /// addGlobalName - Add a new global name to the compile unit. 1269 void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die, 1270 const DIScope *Context) { 1271 if (!hasDwarfPubSections()) 1272 return; 1273 std::string FullName = getParentContextString(Context) + Name.str(); 1274 GlobalNames[FullName] = &Die; 1275 } 1276 1277 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name, 1278 const DIScope *Context) { 1279 if (!hasDwarfPubSections()) 1280 return; 1281 std::string FullName = getParentContextString(Context) + Name.str(); 1282 // Insert, allowing the entry to remain as-is if it's already present 1283 // This way the CU-level type DIE is preferred over the "can't describe this 1284 // type as a unit offset because it's not really in the CU at all, it's only 1285 // in a type unit" 1286 GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie())); 1287 } 1288 1289 /// Add a new global type to the unit. 1290 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die, 1291 const DIScope *Context) { 1292 if (!hasDwarfPubSections()) 1293 return; 1294 std::string FullName = getParentContextString(Context) + Ty->getName().str(); 1295 GlobalTypes[FullName] = &Die; 1296 } 1297 1298 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty, 1299 const DIScope *Context) { 1300 if (!hasDwarfPubSections()) 1301 return; 1302 std::string FullName = getParentContextString(Context) + Ty->getName().str(); 1303 // Insert, allowing the entry to remain as-is if it's already present 1304 // This way the CU-level type DIE is preferred over the "can't describe this 1305 // type as a unit offset because it's not really in the CU at all, it's only 1306 // in a type unit" 1307 GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie())); 1308 } 1309 1310 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die, 1311 MachineLocation Location) { 1312 if (DV.hasComplexAddress()) 1313 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location); 1314 else 1315 addAddress(Die, dwarf::DW_AT_location, Location); 1316 } 1317 1318 /// Add an address attribute to a die based on the location provided. 1319 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute, 1320 const MachineLocation &Location) { 1321 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1322 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 1323 if (Location.isIndirect()) 1324 DwarfExpr.setMemoryLocationKind(); 1325 1326 DIExpressionCursor Cursor({}); 1327 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo(); 1328 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 1329 return; 1330 DwarfExpr.addExpression(std::move(Cursor)); 1331 1332 // Now attach the location information to the DIE. 1333 addBlock(Die, Attribute, DwarfExpr.finalize()); 1334 1335 if (DwarfExpr.TagOffset) 1336 addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1, 1337 *DwarfExpr.TagOffset); 1338 } 1339 1340 /// Start with the address based on the location provided, and generate the 1341 /// DWARF information necessary to find the actual variable given the extra 1342 /// address information encoded in the DbgVariable, starting from the starting 1343 /// location. Add the DWARF information to the die. 1344 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die, 1345 dwarf::Attribute Attribute, 1346 const MachineLocation &Location) { 1347 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1348 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 1349 const DIExpression *DIExpr = DV.getSingleExpression(); 1350 DwarfExpr.addFragmentOffset(DIExpr); 1351 DwarfExpr.setLocation(Location, DIExpr); 1352 1353 DIExpressionCursor Cursor(DIExpr); 1354 1355 if (DIExpr->isEntryValue()) 1356 DwarfExpr.beginEntryValueExpression(Cursor); 1357 1358 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo(); 1359 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 1360 return; 1361 DwarfExpr.addExpression(std::move(Cursor)); 1362 1363 // Now attach the location information to the DIE. 1364 addBlock(Die, Attribute, DwarfExpr.finalize()); 1365 1366 if (DwarfExpr.TagOffset) 1367 addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1, 1368 *DwarfExpr.TagOffset); 1369 } 1370 1371 /// Add a Dwarf loclistptr attribute data and value. 1372 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute, 1373 unsigned Index) { 1374 dwarf::Form Form = (DD->getDwarfVersion() >= 5) 1375 ? dwarf::DW_FORM_loclistx 1376 : DD->getDwarfSectionOffsetForm(); 1377 Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index)); 1378 } 1379 1380 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var, 1381 DIE &VariableDie) { 1382 StringRef Name = Var.getName(); 1383 if (!Name.empty()) 1384 addString(VariableDie, dwarf::DW_AT_name, Name); 1385 const auto *DIVar = Var.getVariable(); 1386 if (DIVar) 1387 if (uint32_t AlignInBytes = DIVar->getAlignInBytes()) 1388 addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata, 1389 AlignInBytes); 1390 1391 addSourceLine(VariableDie, DIVar); 1392 addType(VariableDie, Var.getType()); 1393 if (Var.isArtificial()) 1394 addFlag(VariableDie, dwarf::DW_AT_artificial); 1395 } 1396 1397 void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label, 1398 DIE &LabelDie) { 1399 StringRef Name = Label.getName(); 1400 if (!Name.empty()) 1401 addString(LabelDie, dwarf::DW_AT_name, Name); 1402 const auto *DILabel = Label.getLabel(); 1403 addSourceLine(LabelDie, DILabel); 1404 } 1405 1406 /// Add a Dwarf expression attribute data and value. 1407 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form, 1408 const MCExpr *Expr) { 1409 Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr)); 1410 } 1411 1412 void DwarfCompileUnit::applySubprogramAttributesToDefinition( 1413 const DISubprogram *SP, DIE &SPDie) { 1414 auto *SPDecl = SP->getDeclaration(); 1415 auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope(); 1416 applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes()); 1417 addGlobalName(SP->getName(), SPDie, Context); 1418 } 1419 1420 bool DwarfCompileUnit::isDwoUnit() const { 1421 return DD->useSplitDwarf() && Skeleton; 1422 } 1423 1424 void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) { 1425 constructTypeDIE(D, CTy); 1426 } 1427 1428 bool DwarfCompileUnit::includeMinimalInlineScopes() const { 1429 return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly || 1430 (DD->useSplitDwarf() && !Skeleton); 1431 } 1432 1433 void DwarfCompileUnit::addAddrTableBase() { 1434 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 1435 MCSymbol *Label = DD->getAddressPool().getLabel(); 1436 addSectionLabel(getUnitDie(), 1437 DD->getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base 1438 : dwarf::DW_AT_GNU_addr_base, 1439 Label, TLOF.getDwarfAddrSection()->getBeginSymbol()); 1440 } 1441 1442 void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) { 1443 Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, dwarf::DW_FORM_udata, 1444 new (DIEValueAllocator) DIEBaseTypeRef(this, Idx)); 1445 } 1446 1447 void DwarfCompileUnit::createBaseTypeDIEs() { 1448 // Insert the base_type DIEs directly after the CU so that their offsets will 1449 // fit in the fixed size ULEB128 used inside the location expressions. 1450 // Maintain order by iterating backwards and inserting to the front of CU 1451 // child list. 1452 for (auto &Btr : reverse(ExprRefedBaseTypes)) { 1453 DIE &Die = getUnitDie().addChildFront( 1454 DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type)); 1455 SmallString<32> Str; 1456 addString(Die, dwarf::DW_AT_name, 1457 Twine(dwarf::AttributeEncodingString(Btr.Encoding) + 1458 "_" + Twine(Btr.BitSize)).toStringRef(Str)); 1459 addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding); 1460 addUInt(Die, dwarf::DW_AT_byte_size, None, Btr.BitSize / 8); 1461 1462 Btr.Die = &Die; 1463 } 1464 } 1465