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