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