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->isMemoryLocation()) 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->addAccelName(GV->getLinkageName(), *VariableDIE); 254 } 255 256 return VariableDIE; 257 } 258 259 void DwarfCompileUnit::addRange(RangeSpan Range) { 260 bool SameAsPrevCU = this == DD->getPrevCU(); 261 DD->setPrevCU(this); 262 // If we have no current ranges just add the range and return, otherwise, 263 // check the current section and CU against the previous section and CU we 264 // emitted into and the subprogram was contained within. If these are the 265 // same then extend our current range, otherwise add this as a new range. 266 if (CURanges.empty() || !SameAsPrevCU || 267 (&CURanges.back().getEnd()->getSection() != 268 &Range.getEnd()->getSection())) { 269 CURanges.push_back(Range); 270 return; 271 } 272 273 CURanges.back().setEnd(Range.getEnd()); 274 } 275 276 void DwarfCompileUnit::initStmtList() { 277 // Define start line table label for each Compile Unit. 278 MCSymbol *LineTableStartSym; 279 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 280 if (DD->useSectionsAsReferences()) { 281 LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol(); 282 } else { 283 LineTableStartSym = 284 Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID()); 285 } 286 287 // DW_AT_stmt_list is a offset of line number information for this 288 // compile unit in debug_line section. For split dwarf this is 289 // left in the skeleton CU and so not included. 290 // The line table entries are not always emitted in assembly, so it 291 // is not okay to use line_table_start here. 292 StmtListValue = 293 addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym, 294 TLOF.getDwarfLineSection()->getBeginSymbol()); 295 } 296 297 void DwarfCompileUnit::applyStmtList(DIE &D) { 298 D.addValue(DIEValueAllocator, *StmtListValue); 299 } 300 301 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin, 302 const MCSymbol *End) { 303 assert(Begin && "Begin label should not be null!"); 304 assert(End && "End label should not be null!"); 305 assert(Begin->isDefined() && "Invalid starting label"); 306 assert(End->isDefined() && "Invalid end label"); 307 308 addLabelAddress(D, dwarf::DW_AT_low_pc, Begin); 309 if (DD->getDwarfVersion() < 4) 310 addLabelAddress(D, dwarf::DW_AT_high_pc, End); 311 else 312 addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin); 313 } 314 315 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc 316 // and DW_AT_high_pc attributes. If there are global variables in this 317 // scope then create and insert DIEs for these variables. 318 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) { 319 DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes()); 320 321 attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd()); 322 if (DD->useAppleExtensionAttributes() && 323 !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim( 324 *DD->getCurrentFunction())) 325 addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr); 326 327 // Only include DW_AT_frame_base in full debug info 328 if (!includeMinimalInlineScopes()) { 329 const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo(); 330 MachineLocation Location(RI->getFrameRegister(*Asm->MF)); 331 if (RI->isPhysicalRegister(Location.getReg())) 332 addAddress(*SPDie, dwarf::DW_AT_frame_base, Location); 333 } 334 335 // Add name to the name table, we do this here because we're guaranteed 336 // to have concrete versions of our DW_TAG_subprogram nodes. 337 DD->addSubprogramNames(SP, *SPDie); 338 339 return *SPDie; 340 } 341 342 // Construct a DIE for this scope. 343 void DwarfCompileUnit::constructScopeDIE( 344 LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) { 345 if (!Scope || !Scope->getScopeNode()) 346 return; 347 348 auto *DS = Scope->getScopeNode(); 349 350 assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) && 351 "Only handle inlined subprograms here, use " 352 "constructSubprogramScopeDIE for non-inlined " 353 "subprograms"); 354 355 SmallVector<DIE *, 8> Children; 356 357 // We try to create the scope DIE first, then the children DIEs. This will 358 // avoid creating un-used children then removing them later when we find out 359 // the scope DIE is null. 360 DIE *ScopeDIE; 361 if (Scope->getParent() && isa<DISubprogram>(DS)) { 362 ScopeDIE = constructInlinedScopeDIE(Scope); 363 if (!ScopeDIE) 364 return; 365 // We create children when the scope DIE is not null. 366 createScopeChildrenDIE(Scope, Children); 367 } else { 368 // Early exit when we know the scope DIE is going to be null. 369 if (DD->isLexicalScopeDIENull(Scope)) 370 return; 371 372 bool HasNonScopeChildren = false; 373 374 // We create children here when we know the scope DIE is not going to be 375 // null and the children will be added to the scope DIE. 376 createScopeChildrenDIE(Scope, Children, &HasNonScopeChildren); 377 378 // If there are only other scopes as children, put them directly in the 379 // parent instead, as this scope would serve no purpose. 380 if (!HasNonScopeChildren) { 381 FinalChildren.insert(FinalChildren.end(), 382 std::make_move_iterator(Children.begin()), 383 std::make_move_iterator(Children.end())); 384 return; 385 } 386 ScopeDIE = constructLexicalScopeDIE(Scope); 387 assert(ScopeDIE && "Scope DIE should not be null."); 388 } 389 390 // Add children 391 for (auto &I : Children) 392 ScopeDIE->addChild(std::move(I)); 393 394 FinalChildren.push_back(std::move(ScopeDIE)); 395 } 396 397 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE, 398 SmallVector<RangeSpan, 2> Range) { 399 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 400 401 // Emit offset in .debug_range as a relocatable label. emitDIE will handle 402 // emitting it appropriately. 403 const MCSymbol *RangeSectionSym = 404 TLOF.getDwarfRangesSection()->getBeginSymbol(); 405 406 RangeSpanList List(Asm->createTempSymbol("debug_ranges"), std::move(Range)); 407 408 // Under fission, ranges are specified by constant offsets relative to the 409 // CU's DW_AT_GNU_ranges_base. 410 if (isDwoUnit()) 411 addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(), 412 RangeSectionSym); 413 else 414 addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(), 415 RangeSectionSym); 416 417 // Add the range list to the set of ranges to be emitted. 418 (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List)); 419 } 420 421 void DwarfCompileUnit::attachRangesOrLowHighPC( 422 DIE &Die, SmallVector<RangeSpan, 2> Ranges) { 423 if (Ranges.size() == 1 || !DD->useRangesSection()) { 424 const RangeSpan &Front = Ranges.front(); 425 const RangeSpan &Back = Ranges.back(); 426 attachLowHighPC(Die, Front.getStart(), Back.getEnd()); 427 } else 428 addScopeRangeList(Die, std::move(Ranges)); 429 } 430 431 void DwarfCompileUnit::attachRangesOrLowHighPC( 432 DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) { 433 SmallVector<RangeSpan, 2> List; 434 List.reserve(Ranges.size()); 435 for (const InsnRange &R : Ranges) 436 List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first), 437 DD->getLabelAfterInsn(R.second))); 438 attachRangesOrLowHighPC(Die, std::move(List)); 439 } 440 441 // This scope represents inlined body of a function. Construct DIE to 442 // represent this concrete inlined copy of the function. 443 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) { 444 assert(Scope->getScopeNode()); 445 auto *DS = Scope->getScopeNode(); 446 auto *InlinedSP = getDISubprogram(DS); 447 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram 448 // was inlined from another compile unit. 449 DIE *OriginDIE = getAbstractSPDies()[InlinedSP]; 450 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram."); 451 452 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine); 453 addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE); 454 455 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges()); 456 457 // Add the call site information to the DIE. 458 const DILocation *IA = Scope->getInlinedAt(); 459 addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None, 460 getOrCreateSourceID(IA->getFile())); 461 addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine()); 462 if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4) 463 addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None, 464 IA->getDiscriminator()); 465 466 // Add name to the name table, we do this here because we're guaranteed 467 // to have concrete versions of our DW_TAG_inlined_subprogram nodes. 468 DD->addSubprogramNames(InlinedSP, *ScopeDIE); 469 470 return ScopeDIE; 471 } 472 473 // Construct new DW_TAG_lexical_block for this scope and attach 474 // DW_AT_low_pc/DW_AT_high_pc labels. 475 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) { 476 if (DD->isLexicalScopeDIENull(Scope)) 477 return nullptr; 478 479 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block); 480 if (Scope->isAbstractScope()) 481 return ScopeDIE; 482 483 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges()); 484 485 return ScopeDIE; 486 } 487 488 /// constructVariableDIE - Construct a DIE for the given DbgVariable. 489 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) { 490 auto D = constructVariableDIEImpl(DV, Abstract); 491 DV.setDIE(*D); 492 return D; 493 } 494 495 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV, 496 bool Abstract) { 497 // Define variable debug information entry. 498 auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag()); 499 insertDIE(DV.getVariable(), VariableDie); 500 501 if (Abstract) { 502 applyVariableAttributes(DV, *VariableDie); 503 return VariableDie; 504 } 505 506 // Add variable address. 507 508 unsigned Offset = DV.getDebugLocListIndex(); 509 if (Offset != ~0U) { 510 addLocationList(*VariableDie, dwarf::DW_AT_location, Offset); 511 return VariableDie; 512 } 513 514 // Check if variable is described by a DBG_VALUE instruction. 515 if (const MachineInstr *DVInsn = DV.getMInsn()) { 516 assert(DVInsn->getNumOperands() == 4); 517 if (DVInsn->getOperand(0).isReg()) { 518 auto RegOp = DVInsn->getOperand(0); 519 auto Op1 = DVInsn->getOperand(1); 520 // If the second operand is an immediate, this is an indirect value. 521 assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset"); 522 MachineLocation Location(RegOp.getReg(), Op1.isImm()); 523 addVariableAddress(DV, *VariableDie, Location); 524 } else if (DVInsn->getOperand(0).isImm()) { 525 // This variable is described by a single constant. 526 // Check whether it has a DIExpression. 527 auto *Expr = DV.getSingleExpression(); 528 if (Expr && Expr->getNumElements()) { 529 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 530 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 531 // If there is an expression, emit raw unsigned bytes. 532 DwarfExpr.addFragmentOffset(Expr); 533 DwarfExpr.addUnsignedConstant(DVInsn->getOperand(0).getImm()); 534 DwarfExpr.addExpression(Expr); 535 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize()); 536 } else 537 addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType()); 538 } else if (DVInsn->getOperand(0).isFPImm()) 539 addConstantFPValue(*VariableDie, DVInsn->getOperand(0)); 540 else if (DVInsn->getOperand(0).isCImm()) 541 addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(), 542 DV.getType()); 543 544 return VariableDie; 545 } 546 547 // .. else use frame index. 548 if (!DV.hasFrameIndexExprs()) 549 return VariableDie; 550 551 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 552 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 553 for (auto &Fragment : DV.getFrameIndexExprs()) { 554 unsigned FrameReg = 0; 555 const DIExpression *Expr = Fragment.Expr; 556 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering(); 557 int Offset = TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg); 558 DwarfExpr.addFragmentOffset(Expr); 559 SmallVector<uint64_t, 8> Ops; 560 Ops.push_back(dwarf::DW_OP_plus_uconst); 561 Ops.push_back(Offset); 562 Ops.append(Expr->elements_begin(), Expr->elements_end()); 563 DIExpressionCursor Cursor(Ops); 564 DwarfExpr.setMemoryLocationKind(); 565 DwarfExpr.addMachineRegExpression( 566 *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg); 567 DwarfExpr.addExpression(std::move(Cursor)); 568 } 569 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize()); 570 571 return VariableDie; 572 } 573 574 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, 575 const LexicalScope &Scope, 576 DIE *&ObjectPointer) { 577 auto Var = constructVariableDIE(DV, Scope.isAbstractScope()); 578 if (DV.isObjectPointer()) 579 ObjectPointer = Var; 580 return Var; 581 } 582 583 /// Return all DIVariables that appear in count: expressions. 584 static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) { 585 SmallVector<const DIVariable *, 2> Result; 586 auto *Array = dyn_cast<DICompositeType>(Var->getType()); 587 if (!Array || Array->getTag() != dwarf::DW_TAG_array_type) 588 return Result; 589 for (auto *El : Array->getElements()) { 590 if (auto *Subrange = dyn_cast<DISubrange>(El)) { 591 auto Count = Subrange->getCount(); 592 if (auto *Dependency = Count.dyn_cast<DIVariable *>()) 593 Result.push_back(Dependency); 594 } 595 } 596 return Result; 597 } 598 599 /// Sort local variables so that variables appearing inside of helper 600 /// expressions come first. 601 static SmallVector<DbgVariable *, 8> 602 sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) { 603 SmallVector<DbgVariable *, 8> Result; 604 SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList; 605 // Map back from a DIVariable to its containing DbgVariable. 606 SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar; 607 // Set of DbgVariables in Result. 608 SmallDenseSet<DbgVariable *, 8> Visited; 609 // For cycle detection. 610 SmallDenseSet<DbgVariable *, 8> Visiting; 611 612 // Initialize the worklist and the DIVariable lookup table. 613 for (auto Var : reverse(Input)) { 614 DbgVar.insert({Var->getVariable(), Var}); 615 WorkList.push_back({Var, 0}); 616 } 617 618 // Perform a stable topological sort by doing a DFS. 619 while (!WorkList.empty()) { 620 auto Item = WorkList.back(); 621 DbgVariable *Var = Item.getPointer(); 622 bool visitedAllDependencies = Item.getInt(); 623 WorkList.pop_back(); 624 625 // Dependency is in a different lexical scope or a global. 626 if (!Var) 627 continue; 628 629 // Already handled. 630 if (Visited.count(Var)) 631 continue; 632 633 // Add to Result if all dependencies are visited. 634 if (visitedAllDependencies) { 635 Visited.insert(Var); 636 Result.push_back(Var); 637 continue; 638 } 639 640 // Detect cycles. 641 auto Res = Visiting.insert(Var); 642 if (!Res.second) { 643 assert(false && "dependency cycle in local variables"); 644 return Result; 645 } 646 647 // Push dependencies and this node onto the worklist, so that this node is 648 // visited again after all of its dependencies are handled. 649 WorkList.push_back({Var, 1}); 650 for (auto *Dependency : dependencies(Var)) { 651 auto Dep = dyn_cast_or_null<const DILocalVariable>(Dependency); 652 WorkList.push_back({DbgVar[Dep], 0}); 653 } 654 } 655 return Result; 656 } 657 658 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope, 659 SmallVectorImpl<DIE *> &Children, 660 bool *HasNonScopeChildren) { 661 assert(Children.empty()); 662 DIE *ObjectPointer = nullptr; 663 664 // Emit function arguments (order is significant). 665 auto Vars = DU->getScopeVariables().lookup(Scope); 666 for (auto &DV : Vars.Args) 667 Children.push_back(constructVariableDIE(*DV.second, *Scope, ObjectPointer)); 668 669 // Emit local variables. 670 auto Locals = sortLocalVars(Vars.Locals); 671 for (DbgVariable *DV : Locals) 672 Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer)); 673 674 // Skip imported directives in gmlt-like data. 675 if (!includeMinimalInlineScopes()) { 676 // There is no need to emit empty lexical block DIE. 677 for (const auto *IE : ImportedEntities[Scope->getScopeNode()]) 678 Children.push_back( 679 constructImportedEntityDIE(cast<DIImportedEntity>(IE))); 680 } 681 682 if (HasNonScopeChildren) 683 *HasNonScopeChildren = !Children.empty(); 684 685 for (LexicalScope *LS : Scope->getChildren()) 686 constructScopeDIE(LS, Children); 687 688 return ObjectPointer; 689 } 690 691 void DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub, LexicalScope *Scope) { 692 DIE &ScopeDIE = updateSubprogramScopeDIE(Sub); 693 694 if (Scope) { 695 assert(!Scope->getInlinedAt()); 696 assert(!Scope->isAbstractScope()); 697 // Collect lexical scope children first. 698 // ObjectPointer might be a local (non-argument) local variable if it's a 699 // block's synthetic this pointer. 700 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE)) 701 addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer); 702 } 703 704 // If this is a variadic function, add an unspecified parameter. 705 DITypeRefArray FnArgs = Sub->getType()->getTypeArray(); 706 707 // If we have a single element of null, it is a function that returns void. 708 // If we have more than one elements and the last one is null, it is a 709 // variadic function. 710 if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] && 711 !includeMinimalInlineScopes()) 712 ScopeDIE.addChild( 713 DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters)); 714 } 715 716 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope, 717 DIE &ScopeDIE) { 718 // We create children when the scope DIE is not null. 719 SmallVector<DIE *, 8> Children; 720 DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children); 721 722 // Add children 723 for (auto &I : Children) 724 ScopeDIE.addChild(std::move(I)); 725 726 return ObjectPointer; 727 } 728 729 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE( 730 LexicalScope *Scope) { 731 DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()]; 732 if (AbsDef) 733 return; 734 735 auto *SP = cast<DISubprogram>(Scope->getScopeNode()); 736 737 DIE *ContextDIE; 738 DwarfCompileUnit *ContextCU = this; 739 740 if (includeMinimalInlineScopes()) 741 ContextDIE = &getUnitDie(); 742 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with 743 // the important distinction that the debug node is not associated with the 744 // DIE (since the debug node will be associated with the concrete DIE, if 745 // any). It could be refactored to some common utility function. 746 else if (auto *SPDecl = SP->getDeclaration()) { 747 ContextDIE = &getUnitDie(); 748 getOrCreateSubprogramDIE(SPDecl); 749 } else { 750 ContextDIE = getOrCreateContextDIE(resolve(SP->getScope())); 751 // The scope may be shared with a subprogram that has already been 752 // constructed in another CU, in which case we need to construct this 753 // subprogram in the same CU. 754 ContextCU = DD->lookupCU(ContextDIE->getUnitDie()); 755 } 756 757 // Passing null as the associated node because the abstract definition 758 // shouldn't be found by lookup. 759 AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr); 760 ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef); 761 762 if (!ContextCU->includeMinimalInlineScopes()) 763 ContextCU->addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined); 764 if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef)) 765 ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer); 766 } 767 768 DIE *DwarfCompileUnit::constructImportedEntityDIE( 769 const DIImportedEntity *Module) { 770 DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag()); 771 insertDIE(Module, IMDie); 772 DIE *EntityDie; 773 auto *Entity = resolve(Module->getEntity()); 774 if (auto *NS = dyn_cast<DINamespace>(Entity)) 775 EntityDie = getOrCreateNameSpace(NS); 776 else if (auto *M = dyn_cast<DIModule>(Entity)) 777 EntityDie = getOrCreateModule(M); 778 else if (auto *SP = dyn_cast<DISubprogram>(Entity)) 779 EntityDie = getOrCreateSubprogramDIE(SP); 780 else if (auto *T = dyn_cast<DIType>(Entity)) 781 EntityDie = getOrCreateTypeDIE(T); 782 else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity)) 783 EntityDie = getOrCreateGlobalVariableDIE(GV, {}); 784 else 785 EntityDie = getDIE(Entity); 786 assert(EntityDie); 787 addSourceLine(*IMDie, Module->getLine(), Module->getFile()); 788 addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie); 789 StringRef Name = Module->getName(); 790 if (!Name.empty()) 791 addString(*IMDie, dwarf::DW_AT_name, Name); 792 793 return IMDie; 794 } 795 796 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) { 797 DIE *D = getDIE(SP); 798 if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) { 799 if (D) 800 // If this subprogram has an abstract definition, reference that 801 addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE); 802 } else { 803 assert(D || includeMinimalInlineScopes()); 804 if (D) 805 // And attach the attributes 806 applySubprogramAttributesToDefinition(SP, *D); 807 } 808 } 809 810 void DwarfCompileUnit::finishVariableDefinition(const DbgVariable &Var) { 811 DbgVariable *AbsVar = getExistingAbstractVariable( 812 InlinedVariable(Var.getVariable(), Var.getInlinedAt())); 813 auto *VariableDie = Var.getDIE(); 814 if (AbsVar && AbsVar->getDIE()) { 815 addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin, 816 *AbsVar->getDIE()); 817 } else 818 applyVariableAttributes(Var, *VariableDie); 819 } 820 821 DbgVariable *DwarfCompileUnit::getExistingAbstractVariable(InlinedVariable IV) { 822 const DILocalVariable *Cleansed; 823 return getExistingAbstractVariable(IV, Cleansed); 824 } 825 826 // Find abstract variable, if any, associated with Var. 827 DbgVariable *DwarfCompileUnit::getExistingAbstractVariable( 828 InlinedVariable IV, const DILocalVariable *&Cleansed) { 829 // More then one inlined variable corresponds to one abstract variable. 830 Cleansed = IV.first; 831 auto &AbstractVariables = getAbstractVariables(); 832 auto I = AbstractVariables.find(Cleansed); 833 if (I != AbstractVariables.end()) 834 return I->second.get(); 835 return nullptr; 836 } 837 838 void DwarfCompileUnit::createAbstractVariable(const DILocalVariable *Var, 839 LexicalScope *Scope) { 840 assert(Scope && Scope->isAbstractScope()); 841 auto AbsDbgVariable = llvm::make_unique<DbgVariable>(Var, /* IA */ nullptr); 842 DU->addScopeVariable(Scope, AbsDbgVariable.get()); 843 getAbstractVariables()[Var] = std::move(AbsDbgVariable); 844 } 845 846 void DwarfCompileUnit::emitHeader(bool UseOffsets) { 847 // Don't bother labeling the .dwo unit, as its offset isn't used. 848 if (!Skeleton && !DD->useSectionsAsReferences()) { 849 LabelBegin = Asm->createTempSymbol("cu_begin"); 850 Asm->OutStreamer->EmitLabel(LabelBegin); 851 } 852 853 dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile 854 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton 855 : dwarf::DW_UT_compile; 856 DwarfUnit::emitCommonHeader(UseOffsets, UT); 857 } 858 859 bool DwarfCompileUnit::hasDwarfPubSections() const { 860 // Opting in to GNU Pubnames/types overrides the default to ensure these are 861 // generated for things like Gold's gdb_index generation. 862 if (CUNode->getGnuPubnames()) 863 return true; 864 865 return DD->tuneForGDB() && DD->usePubSections() && 866 !includeMinimalInlineScopes(); 867 } 868 869 /// addGlobalName - Add a new global name to the compile unit. 870 void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die, 871 const DIScope *Context) { 872 if (!hasDwarfPubSections()) 873 return; 874 std::string FullName = getParentContextString(Context) + Name.str(); 875 GlobalNames[FullName] = &Die; 876 } 877 878 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name, 879 const DIScope *Context) { 880 if (!hasDwarfPubSections()) 881 return; 882 std::string FullName = getParentContextString(Context) + Name.str(); 883 // Insert, allowing the entry to remain as-is if it's already present 884 // This way the CU-level type DIE is preferred over the "can't describe this 885 // type as a unit offset because it's not really in the CU at all, it's only 886 // in a type unit" 887 GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie())); 888 } 889 890 /// Add a new global type to the unit. 891 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die, 892 const DIScope *Context) { 893 if (!hasDwarfPubSections()) 894 return; 895 std::string FullName = getParentContextString(Context) + Ty->getName().str(); 896 GlobalTypes[FullName] = &Die; 897 } 898 899 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty, 900 const DIScope *Context) { 901 if (!hasDwarfPubSections()) 902 return; 903 std::string FullName = getParentContextString(Context) + Ty->getName().str(); 904 // Insert, allowing the entry to remain as-is if it's already present 905 // This way the CU-level type DIE is preferred over the "can't describe this 906 // type as a unit offset because it's not really in the CU at all, it's only 907 // in a type unit" 908 GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie())); 909 } 910 911 /// addVariableAddress - Add DW_AT_location attribute for a 912 /// DbgVariable based on provided MachineLocation. 913 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die, 914 MachineLocation Location) { 915 // addBlockByrefAddress is obsolete and will be removed soon. 916 // The clang frontend always generates block byref variables with a 917 // complex expression that encodes exactly what addBlockByrefAddress 918 // would do. 919 assert((!DV.isBlockByrefVariable() || DV.hasComplexAddress()) && 920 "block byref variable without a complex expression"); 921 if (DV.hasComplexAddress()) 922 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location); 923 else if (DV.isBlockByrefVariable()) 924 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location); 925 else 926 addAddress(Die, dwarf::DW_AT_location, Location); 927 } 928 929 /// Add an address attribute to a die based on the location provided. 930 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute, 931 const MachineLocation &Location) { 932 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 933 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 934 if (Location.isIndirect()) 935 DwarfExpr.setMemoryLocationKind(); 936 937 DIExpressionCursor Cursor({}); 938 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo(); 939 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 940 return; 941 DwarfExpr.addExpression(std::move(Cursor)); 942 943 // Now attach the location information to the DIE. 944 addBlock(Die, Attribute, DwarfExpr.finalize()); 945 } 946 947 /// Start with the address based on the location provided, and generate the 948 /// DWARF information necessary to find the actual variable given the extra 949 /// address information encoded in the DbgVariable, starting from the starting 950 /// location. Add the DWARF information to the die. 951 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die, 952 dwarf::Attribute Attribute, 953 const MachineLocation &Location) { 954 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 955 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); 956 const DIExpression *DIExpr = DV.getSingleExpression(); 957 DwarfExpr.addFragmentOffset(DIExpr); 958 if (Location.isIndirect()) 959 DwarfExpr.setMemoryLocationKind(); 960 961 DIExpressionCursor Cursor(DIExpr); 962 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo(); 963 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 964 return; 965 DwarfExpr.addExpression(std::move(Cursor)); 966 967 // Now attach the location information to the DIE. 968 addBlock(Die, Attribute, DwarfExpr.finalize()); 969 } 970 971 /// Add a Dwarf loclistptr attribute data and value. 972 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute, 973 unsigned Index) { 974 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset 975 : dwarf::DW_FORM_data4; 976 Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index)); 977 } 978 979 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var, 980 DIE &VariableDie) { 981 StringRef Name = Var.getName(); 982 if (!Name.empty()) 983 addString(VariableDie, dwarf::DW_AT_name, Name); 984 const auto *DIVar = Var.getVariable(); 985 if (DIVar) 986 if (uint32_t AlignInBytes = DIVar->getAlignInBytes()) 987 addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata, 988 AlignInBytes); 989 990 addSourceLine(VariableDie, DIVar); 991 addType(VariableDie, Var.getType()); 992 if (Var.isArtificial()) 993 addFlag(VariableDie, dwarf::DW_AT_artificial); 994 } 995 996 /// Add a Dwarf expression attribute data and value. 997 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form, 998 const MCExpr *Expr) { 999 Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr)); 1000 } 1001 1002 void DwarfCompileUnit::applySubprogramAttributesToDefinition( 1003 const DISubprogram *SP, DIE &SPDie) { 1004 auto *SPDecl = SP->getDeclaration(); 1005 auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope()); 1006 applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes()); 1007 addGlobalName(SP->getName(), SPDie, Context); 1008 } 1009 1010 bool DwarfCompileUnit::isDwoUnit() const { 1011 return DD->useSplitDwarf() && Skeleton; 1012 } 1013 1014 bool DwarfCompileUnit::includeMinimalInlineScopes() const { 1015 return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly || 1016 (DD->useSplitDwarf() && !Skeleton); 1017 } 1018