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