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