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