1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains support for constructing a dwarf compile unit. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "DwarfUnit.h" 14 #include "AddressPool.h" 15 #include "DwarfCompileUnit.h" 16 #include "DwarfExpression.h" 17 #include "llvm/ADT/APFloat.h" 18 #include "llvm/ADT/APInt.h" 19 #include "llvm/CodeGen/TargetRegisterInfo.h" 20 #include "llvm/IR/Constants.h" 21 #include "llvm/IR/DataLayout.h" 22 #include "llvm/IR/GlobalValue.h" 23 #include "llvm/IR/Metadata.h" 24 #include "llvm/MC/MCAsmInfo.h" 25 #include "llvm/MC/MCContext.h" 26 #include "llvm/MC/MCDwarf.h" 27 #include "llvm/MC/MCSection.h" 28 #include "llvm/MC/MCStreamer.h" 29 #include "llvm/Support/Casting.h" 30 #include "llvm/Target/TargetLoweringObjectFile.h" 31 #include <cassert> 32 #include <cstdint> 33 #include <limits> 34 #include <string> 35 #include <utility> 36 37 using namespace llvm; 38 39 #define DEBUG_TYPE "dwarfdebug" 40 41 DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP, 42 DwarfCompileUnit &CU, DIELoc &DIE) 43 : DwarfExpression(AP.getDwarfVersion(), CU), AP(AP), OutDIE(DIE) {} 44 45 void DIEDwarfExpression::emitOp(uint8_t Op, const char* Comment) { 46 CU.addUInt(getActiveDIE(), dwarf::DW_FORM_data1, Op); 47 } 48 49 void DIEDwarfExpression::emitSigned(int64_t Value) { 50 CU.addSInt(getActiveDIE(), dwarf::DW_FORM_sdata, Value); 51 } 52 53 void DIEDwarfExpression::emitUnsigned(uint64_t Value) { 54 CU.addUInt(getActiveDIE(), dwarf::DW_FORM_udata, Value); 55 } 56 57 void DIEDwarfExpression::emitData1(uint8_t Value) { 58 CU.addUInt(getActiveDIE(), dwarf::DW_FORM_data1, Value); 59 } 60 61 void DIEDwarfExpression::emitBaseTypeRef(uint64_t Idx) { 62 CU.addBaseTypeRef(getActiveDIE(), Idx); 63 } 64 65 void DIEDwarfExpression::enableTemporaryBuffer() { 66 assert(!IsBuffering && "Already buffering?"); 67 IsBuffering = true; 68 } 69 70 void DIEDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; } 71 72 unsigned DIEDwarfExpression::getTemporaryBufferSize() { 73 return TmpDIE.computeSize(AP.getDwarfFormParams()); 74 } 75 76 void DIEDwarfExpression::commitTemporaryBuffer() { OutDIE.takeValues(TmpDIE); } 77 78 bool DIEDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI, 79 llvm::Register MachineReg) { 80 return MachineReg == TRI.getFrameRegister(*AP.MF); 81 } 82 83 DwarfUnit::DwarfUnit(dwarf::Tag UnitTag, const DICompileUnit *Node, 84 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU, 85 unsigned UniqueID) 86 : DIEUnit(UnitTag), UniqueID(UniqueID), CUNode(Node), Asm(A), DD(DW), 87 DU(DWU) {} 88 89 DwarfTypeUnit::DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A, 90 DwarfDebug *DW, DwarfFile *DWU, unsigned UniqueID, 91 MCDwarfDwoLineTable *SplitLineTable) 92 : DwarfUnit(dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU, UniqueID), 93 CU(CU), SplitLineTable(SplitLineTable) {} 94 95 DwarfUnit::~DwarfUnit() { 96 for (DIEBlock *B : DIEBlocks) 97 B->~DIEBlock(); 98 for (DIELoc *L : DIELocs) 99 L->~DIELoc(); 100 } 101 102 int64_t DwarfUnit::getDefaultLowerBound() const { 103 switch (getLanguage()) { 104 default: 105 break; 106 107 // The languages below have valid values in all DWARF versions. 108 case dwarf::DW_LANG_C: 109 case dwarf::DW_LANG_C89: 110 case dwarf::DW_LANG_C_plus_plus: 111 return 0; 112 113 case dwarf::DW_LANG_Fortran77: 114 case dwarf::DW_LANG_Fortran90: 115 return 1; 116 117 // The languages below have valid values only if the DWARF version >= 3. 118 case dwarf::DW_LANG_C99: 119 case dwarf::DW_LANG_ObjC: 120 case dwarf::DW_LANG_ObjC_plus_plus: 121 if (DD->getDwarfVersion() >= 3) 122 return 0; 123 break; 124 125 case dwarf::DW_LANG_Fortran95: 126 if (DD->getDwarfVersion() >= 3) 127 return 1; 128 break; 129 130 // Starting with DWARF v4, all defined languages have valid values. 131 case dwarf::DW_LANG_D: 132 case dwarf::DW_LANG_Java: 133 case dwarf::DW_LANG_Python: 134 case dwarf::DW_LANG_UPC: 135 if (DD->getDwarfVersion() >= 4) 136 return 0; 137 break; 138 139 case dwarf::DW_LANG_Ada83: 140 case dwarf::DW_LANG_Ada95: 141 case dwarf::DW_LANG_Cobol74: 142 case dwarf::DW_LANG_Cobol85: 143 case dwarf::DW_LANG_Modula2: 144 case dwarf::DW_LANG_Pascal83: 145 case dwarf::DW_LANG_PLI: 146 if (DD->getDwarfVersion() >= 4) 147 return 1; 148 break; 149 150 // The languages below are new in DWARF v5. 151 case dwarf::DW_LANG_BLISS: 152 case dwarf::DW_LANG_C11: 153 case dwarf::DW_LANG_C_plus_plus_03: 154 case dwarf::DW_LANG_C_plus_plus_11: 155 case dwarf::DW_LANG_C_plus_plus_14: 156 case dwarf::DW_LANG_Dylan: 157 case dwarf::DW_LANG_Go: 158 case dwarf::DW_LANG_Haskell: 159 case dwarf::DW_LANG_OCaml: 160 case dwarf::DW_LANG_OpenCL: 161 case dwarf::DW_LANG_RenderScript: 162 case dwarf::DW_LANG_Rust: 163 case dwarf::DW_LANG_Swift: 164 if (DD->getDwarfVersion() >= 5) 165 return 0; 166 break; 167 168 case dwarf::DW_LANG_Fortran03: 169 case dwarf::DW_LANG_Fortran08: 170 case dwarf::DW_LANG_Julia: 171 case dwarf::DW_LANG_Modula3: 172 if (DD->getDwarfVersion() >= 5) 173 return 1; 174 break; 175 } 176 177 return -1; 178 } 179 180 /// Check whether the DIE for this MDNode can be shared across CUs. 181 bool DwarfUnit::isShareableAcrossCUs(const DINode *D) const { 182 // When the MDNode can be part of the type system, the DIE can be shared 183 // across CUs. 184 // Combining type units and cross-CU DIE sharing is lower value (since 185 // cross-CU DIE sharing is used in LTO and removes type redundancy at that 186 // level already) but may be implementable for some value in projects 187 // building multiple independent libraries with LTO and then linking those 188 // together. 189 if (isDwoUnit() && !DD->shareAcrossDWOCUs()) 190 return false; 191 return (isa<DIType>(D) || 192 (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) && 193 !DD->generateTypeUnits(); 194 } 195 196 DIE *DwarfUnit::getDIE(const DINode *D) const { 197 if (isShareableAcrossCUs(D)) 198 return DU->getDIE(D); 199 return MDNodeToDieMap.lookup(D); 200 } 201 202 void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) { 203 if (isShareableAcrossCUs(Desc)) { 204 DU->insertDIE(Desc, D); 205 return; 206 } 207 MDNodeToDieMap.insert(std::make_pair(Desc, D)); 208 } 209 210 void DwarfUnit::insertDIE(DIE *D) { 211 MDNodeToDieMap.insert(std::make_pair(nullptr, D)); 212 } 213 214 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) { 215 if (DD->getDwarfVersion() >= 4) 216 addAttribute(Die, Attribute, dwarf::DW_FORM_flag_present, DIEInteger(1)); 217 else 218 addAttribute(Die, Attribute, dwarf::DW_FORM_flag, DIEInteger(1)); 219 } 220 221 void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute, 222 std::optional<dwarf::Form> Form, uint64_t Integer) { 223 if (!Form) 224 Form = DIEInteger::BestForm(false, Integer); 225 assert(Form != dwarf::DW_FORM_implicit_const && 226 "DW_FORM_implicit_const is used only for signed integers"); 227 addAttribute(Die, Attribute, *Form, DIEInteger(Integer)); 228 } 229 230 void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form, 231 uint64_t Integer) { 232 addUInt(Block, (dwarf::Attribute)0, Form, Integer); 233 } 234 235 void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute, 236 std::optional<dwarf::Form> Form, int64_t Integer) { 237 if (!Form) 238 Form = DIEInteger::BestForm(true, Integer); 239 addAttribute(Die, Attribute, *Form, DIEInteger(Integer)); 240 } 241 242 void DwarfUnit::addSInt(DIELoc &Die, std::optional<dwarf::Form> Form, 243 int64_t Integer) { 244 addSInt(Die, (dwarf::Attribute)0, Form, Integer); 245 } 246 247 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute, 248 StringRef String) { 249 if (CUNode->isDebugDirectivesOnly()) 250 return; 251 252 if (DD->useInlineStrings()) { 253 addAttribute(Die, Attribute, dwarf::DW_FORM_string, 254 new (DIEValueAllocator) 255 DIEInlineString(String, DIEValueAllocator)); 256 return; 257 } 258 dwarf::Form IxForm = 259 isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp; 260 261 auto StringPoolEntry = 262 useSegmentedStringOffsetsTable() || IxForm == dwarf::DW_FORM_GNU_str_index 263 ? DU->getStringPool().getIndexedEntry(*Asm, String) 264 : DU->getStringPool().getEntry(*Asm, String); 265 266 // For DWARF v5 and beyond, use the smallest strx? form possible. 267 if (useSegmentedStringOffsetsTable()) { 268 IxForm = dwarf::DW_FORM_strx1; 269 unsigned Index = StringPoolEntry.getIndex(); 270 if (Index > 0xffffff) 271 IxForm = dwarf::DW_FORM_strx4; 272 else if (Index > 0xffff) 273 IxForm = dwarf::DW_FORM_strx3; 274 else if (Index > 0xff) 275 IxForm = dwarf::DW_FORM_strx2; 276 } 277 addAttribute(Die, Attribute, IxForm, DIEString(StringPoolEntry)); 278 } 279 280 void DwarfUnit::addLabel(DIEValueList &Die, dwarf::Attribute Attribute, 281 dwarf::Form Form, const MCSymbol *Label) { 282 addAttribute(Die, Attribute, Form, DIELabel(Label)); 283 } 284 285 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) { 286 addLabel(Die, (dwarf::Attribute)0, Form, Label); 287 } 288 289 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute, 290 uint64_t Integer) { 291 addUInt(Die, Attribute, DD->getDwarfSectionOffsetForm(), Integer); 292 } 293 294 unsigned DwarfTypeUnit::getOrCreateSourceID(const DIFile *File) { 295 if (!SplitLineTable) 296 return getCU().getOrCreateSourceID(File); 297 if (!UsedLineTable) { 298 UsedLineTable = true; 299 // This is a split type unit that needs a line table. 300 addSectionOffset(getUnitDie(), dwarf::DW_AT_stmt_list, 0); 301 } 302 return SplitLineTable->getFile( 303 File->getDirectory(), File->getFilename(), DD->getMD5AsBytes(File), 304 Asm->OutContext.getDwarfVersion(), File->getSource()); 305 } 306 307 void DwarfUnit::addPoolOpAddress(DIEValueList &Die, const MCSymbol *Label) { 308 bool UseAddrOffsetFormOrExpressions = 309 DD->useAddrOffsetForm() || DD->useAddrOffsetExpressions(); 310 311 const MCSymbol *Base = nullptr; 312 if (Label->isInSection() && UseAddrOffsetFormOrExpressions) 313 Base = DD->getSectionLabel(&Label->getSection()); 314 315 uint32_t Index = DD->getAddressPool().getIndex(Base ? Base : Label); 316 317 if (DD->getDwarfVersion() >= 5) { 318 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addrx); 319 addUInt(Die, dwarf::DW_FORM_addrx, Index); 320 } else { 321 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index); 322 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, Index); 323 } 324 325 if (Base && Base != Label) { 326 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_const4u); 327 addLabelDelta(Die, (dwarf::Attribute)0, Label, Base); 328 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_plus); 329 } 330 } 331 332 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) { 333 if (DD->getDwarfVersion() >= 5) { 334 addPoolOpAddress(Die, Sym); 335 return; 336 } 337 338 if (DD->useSplitDwarf()) { 339 addPoolOpAddress(Die, Sym); 340 return; 341 } 342 343 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr); 344 addLabel(Die, dwarf::DW_FORM_addr, Sym); 345 } 346 347 void DwarfUnit::addLabelDelta(DIEValueList &Die, dwarf::Attribute Attribute, 348 const MCSymbol *Hi, const MCSymbol *Lo) { 349 addAttribute(Die, Attribute, dwarf::DW_FORM_data4, 350 new (DIEValueAllocator) DIEDelta(Hi, Lo)); 351 } 352 353 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) { 354 addDIEEntry(Die, Attribute, DIEEntry(Entry)); 355 } 356 357 void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) { 358 // Flag the type unit reference as a declaration so that if it contains 359 // members (implicit special members, static data member definitions, member 360 // declarations for definitions in this CU, etc) consumers don't get confused 361 // and think this is a full definition. 362 addFlag(Die, dwarf::DW_AT_declaration); 363 364 addAttribute(Die, dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8, 365 DIEInteger(Signature)); 366 } 367 368 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, 369 DIEEntry Entry) { 370 const DIEUnit *CU = Die.getUnit(); 371 const DIEUnit *EntryCU = Entry.getEntry().getUnit(); 372 if (!CU) 373 // We assume that Die belongs to this CU, if it is not linked to any CU yet. 374 CU = getUnitDie().getUnit(); 375 if (!EntryCU) 376 EntryCU = getUnitDie().getUnit(); 377 assert(EntryCU == CU || !DD->useSplitDwarf() || DD->shareAcrossDWOCUs() || 378 !static_cast<const DwarfUnit*>(CU)->isDwoUnit()); 379 addAttribute(Die, Attribute, 380 EntryCU == CU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr, 381 Entry); 382 } 383 384 DIE &DwarfUnit::createAndAddDIE(dwarf::Tag Tag, DIE &Parent, const DINode *N) { 385 DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, Tag)); 386 if (N) 387 insertDIE(N, &Die); 388 return Die; 389 } 390 391 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) { 392 Loc->computeSize(Asm->getDwarfFormParams()); 393 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on. 394 addAttribute(Die, Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc); 395 } 396 397 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form, 398 DIEBlock *Block) { 399 Block->computeSize(Asm->getDwarfFormParams()); 400 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on. 401 addAttribute(Die, Attribute, Form, Block); 402 } 403 404 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, 405 DIEBlock *Block) { 406 addBlock(Die, Attribute, Block->BestForm(), Block); 407 } 408 409 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, const DIFile *File) { 410 if (Line == 0) 411 return; 412 413 unsigned FileID = getOrCreateSourceID(File); 414 addUInt(Die, dwarf::DW_AT_decl_file, std::nullopt, FileID); 415 addUInt(Die, dwarf::DW_AT_decl_line, std::nullopt, Line); 416 } 417 418 void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) { 419 assert(V); 420 421 addSourceLine(Die, V->getLine(), V->getFile()); 422 } 423 424 void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) { 425 assert(G); 426 427 addSourceLine(Die, G->getLine(), G->getFile()); 428 } 429 430 void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) { 431 assert(SP); 432 433 addSourceLine(Die, SP->getLine(), SP->getFile()); 434 } 435 436 void DwarfUnit::addSourceLine(DIE &Die, const DILabel *L) { 437 assert(L); 438 439 addSourceLine(Die, L->getLine(), L->getFile()); 440 } 441 442 void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) { 443 assert(Ty); 444 445 addSourceLine(Die, Ty->getLine(), Ty->getFile()); 446 } 447 448 void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) { 449 assert(Ty); 450 451 addSourceLine(Die, Ty->getLine(), Ty->getFile()); 452 } 453 454 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) { 455 // Pass this down to addConstantValue as an unsigned bag of bits. 456 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true); 457 } 458 459 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, 460 const DIType *Ty) { 461 addConstantValue(Die, CI->getValue(), Ty); 462 } 463 464 void DwarfUnit::addConstantValue(DIE &Die, uint64_t Val, const DIType *Ty) { 465 addConstantValue(Die, DD->isUnsignedDIType(Ty), Val); 466 } 467 468 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) { 469 // FIXME: This is a bit conservative/simple - it emits negative values always 470 // sign extended to 64 bits rather than minimizing the number of bytes. 471 addUInt(Die, dwarf::DW_AT_const_value, 472 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val); 473 } 474 475 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) { 476 addConstantValue(Die, Val, DD->isUnsignedDIType(Ty)); 477 } 478 479 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) { 480 unsigned CIBitWidth = Val.getBitWidth(); 481 if (CIBitWidth <= 64) { 482 addConstantValue(Die, Unsigned, 483 Unsigned ? Val.getZExtValue() : Val.getSExtValue()); 484 return; 485 } 486 487 DIEBlock *Block = new (DIEValueAllocator) DIEBlock; 488 489 // Get the raw data form of the large APInt. 490 const uint64_t *Ptr64 = Val.getRawData(); 491 492 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte. 493 bool LittleEndian = Asm->getDataLayout().isLittleEndian(); 494 495 // Output the constant to DWARF one byte at a time. 496 for (int i = 0; i < NumBytes; i++) { 497 uint8_t c; 498 if (LittleEndian) 499 c = Ptr64[i / 8] >> (8 * (i & 7)); 500 else 501 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7)); 502 addUInt(*Block, dwarf::DW_FORM_data1, c); 503 } 504 505 addBlock(Die, dwarf::DW_AT_const_value, Block); 506 } 507 508 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) { 509 if (!LinkageName.empty()) 510 addString(Die, 511 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name 512 : dwarf::DW_AT_MIPS_linkage_name, 513 GlobalValue::dropLLVMManglingEscape(LinkageName)); 514 } 515 516 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) { 517 // Add template parameters. 518 for (const auto *Element : TParams) { 519 if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element)) 520 constructTemplateTypeParameterDIE(Buffer, TTP); 521 else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element)) 522 constructTemplateValueParameterDIE(Buffer, TVP); 523 } 524 } 525 526 /// Add thrown types. 527 void DwarfUnit::addThrownTypes(DIE &Die, DINodeArray ThrownTypes) { 528 for (const auto *Ty : ThrownTypes) { 529 DIE &TT = createAndAddDIE(dwarf::DW_TAG_thrown_type, Die); 530 addType(TT, cast<DIType>(Ty)); 531 } 532 } 533 534 void DwarfUnit::addAccess(DIE &Die, DINode::DIFlags Flags) { 535 if ((Flags & DINode::FlagAccessibility) == DINode::FlagProtected) 536 addUInt(Die, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 537 dwarf::DW_ACCESS_protected); 538 else if ((Flags & DINode::FlagAccessibility) == DINode::FlagPrivate) 539 addUInt(Die, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 540 dwarf::DW_ACCESS_private); 541 else if ((Flags & DINode::FlagAccessibility) == DINode::FlagPublic) 542 addUInt(Die, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 543 dwarf::DW_ACCESS_public); 544 } 545 546 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) { 547 if (!Context || isa<DIFile>(Context) || isa<DICompileUnit>(Context)) 548 return &getUnitDie(); 549 if (auto *T = dyn_cast<DIType>(Context)) 550 return getOrCreateTypeDIE(T); 551 if (auto *NS = dyn_cast<DINamespace>(Context)) 552 return getOrCreateNameSpace(NS); 553 if (auto *SP = dyn_cast<DISubprogram>(Context)) 554 return getOrCreateSubprogramDIE(SP); 555 if (auto *M = dyn_cast<DIModule>(Context)) 556 return getOrCreateModule(M); 557 return getDIE(Context); 558 } 559 560 DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) { 561 auto *Context = Ty->getScope(); 562 DIE *ContextDIE = getOrCreateContextDIE(Context); 563 564 if (DIE *TyDIE = getDIE(Ty)) 565 return TyDIE; 566 567 // Create new type. 568 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty); 569 570 constructTypeDIE(TyDIE, cast<DICompositeType>(Ty)); 571 572 updateAcceleratorTables(Context, Ty, TyDIE); 573 return &TyDIE; 574 } 575 576 DIE *DwarfUnit::createTypeDIE(const DIScope *Context, DIE &ContextDIE, 577 const DIType *Ty) { 578 // Create new type. 579 DIE &TyDIE = createAndAddDIE(Ty->getTag(), ContextDIE, Ty); 580 581 auto construct = [&](const auto *Ty) { 582 updateAcceleratorTables(Context, Ty, TyDIE); 583 constructTypeDIE(TyDIE, Ty); 584 }; 585 586 if (auto *CTy = dyn_cast<DICompositeType>(Ty)) { 587 if (DD->generateTypeUnits() && !Ty->isForwardDecl() && 588 (Ty->getRawName() || CTy->getRawIdentifier())) { 589 // Skip updating the accelerator tables since this is not the full type. 590 if (MDString *TypeId = CTy->getRawIdentifier()) { 591 addGlobalType(Ty, TyDIE, Context); 592 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy); 593 } else { 594 updateAcceleratorTables(Context, Ty, TyDIE); 595 finishNonUnitTypeDIE(TyDIE, CTy); 596 } 597 return &TyDIE; 598 } 599 construct(CTy); 600 } else if (auto *BT = dyn_cast<DIBasicType>(Ty)) 601 construct(BT); 602 else if (auto *ST = dyn_cast<DIStringType>(Ty)) 603 construct(ST); 604 else if (auto *STy = dyn_cast<DISubroutineType>(Ty)) 605 construct(STy); 606 else 607 construct(cast<DIDerivedType>(Ty)); 608 609 return &TyDIE; 610 } 611 612 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) { 613 if (!TyNode) 614 return nullptr; 615 616 auto *Ty = cast<DIType>(TyNode); 617 618 // DW_TAG_restrict_type is not supported in DWARF2 619 if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2) 620 return getOrCreateTypeDIE(cast<DIDerivedType>(Ty)->getBaseType()); 621 622 // DW_TAG_atomic_type is not supported in DWARF < 5 623 if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5) 624 return getOrCreateTypeDIE(cast<DIDerivedType>(Ty)->getBaseType()); 625 626 // Construct the context before querying for the existence of the DIE in case 627 // such construction creates the DIE. 628 auto *Context = Ty->getScope(); 629 DIE *ContextDIE = getOrCreateContextDIE(Context); 630 assert(ContextDIE); 631 632 if (DIE *TyDIE = getDIE(Ty)) 633 return TyDIE; 634 635 return static_cast<DwarfUnit *>(ContextDIE->getUnit()) 636 ->createTypeDIE(Context, *ContextDIE, Ty); 637 } 638 639 void DwarfUnit::updateAcceleratorTables(const DIScope *Context, 640 const DIType *Ty, const DIE &TyDIE) { 641 if (Ty->getName().empty()) 642 return; 643 if (Ty->isForwardDecl()) 644 return; 645 646 // add temporary record for this type to be added later 647 648 unsigned Flags = 0; 649 if (auto *CT = dyn_cast<DICompositeType>(Ty)) { 650 // A runtime language of 0 actually means C/C++ and that any 651 // non-negative value is some version of Objective-C/C++. 652 if (CT->getRuntimeLang() == 0 || CT->isObjcClassComplete()) 653 Flags = dwarf::DW_FLAG_type_implementation; 654 } 655 656 DD->addAccelType(*this, CUNode->getNameTableKind(), Ty->getName(), TyDIE, 657 Flags); 658 659 if (auto *CT = dyn_cast<DICompositeType>(Ty)) 660 if (Ty->getName() != CT->getIdentifier() && 661 CT->getRuntimeLang() == dwarf::DW_LANG_Swift) 662 DD->addAccelType(*this, CUNode->getNameTableKind(), CT->getIdentifier(), 663 TyDIE, Flags); 664 665 addGlobalType(Ty, TyDIE, Context); 666 } 667 668 void DwarfUnit::addGlobalType(const DIType *Ty, const DIE &TyDIE, 669 const DIScope *Context) { 670 if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) || 671 isa<DINamespace>(Context) || isa<DICommonBlock>(Context)) 672 addGlobalTypeImpl(Ty, TyDIE, Context); 673 } 674 675 void DwarfUnit::addType(DIE &Entity, const DIType *Ty, 676 dwarf::Attribute Attribute) { 677 assert(Ty && "Trying to add a type that doesn't exist?"); 678 addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty))); 679 } 680 681 std::string DwarfUnit::getParentContextString(const DIScope *Context) const { 682 if (!Context) 683 return ""; 684 685 // FIXME: Decide whether to implement this for non-C++ languages. 686 if (!dwarf::isCPlusPlus((dwarf::SourceLanguage)getLanguage())) 687 return ""; 688 689 std::string CS; 690 SmallVector<const DIScope *, 1> Parents; 691 while (!isa<DICompileUnit>(Context)) { 692 Parents.push_back(Context); 693 if (const DIScope *S = Context->getScope()) 694 Context = S; 695 else 696 // Structure, etc types will have a NULL context if they're at the top 697 // level. 698 break; 699 } 700 701 // Reverse iterate over our list to go from the outermost construct to the 702 // innermost. 703 for (const DIScope *Ctx : llvm::reverse(Parents)) { 704 StringRef Name = Ctx->getName(); 705 if (Name.empty() && isa<DINamespace>(Ctx)) 706 Name = "(anonymous namespace)"; 707 if (!Name.empty()) { 708 CS += Name; 709 CS += "::"; 710 } 711 } 712 return CS; 713 } 714 715 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) { 716 // Get core information. 717 StringRef Name = BTy->getName(); 718 // Add name if not anonymous or intermediate type. 719 if (!Name.empty()) 720 addString(Buffer, dwarf::DW_AT_name, Name); 721 722 // An unspecified type only has a name attribute. 723 if (BTy->getTag() == dwarf::DW_TAG_unspecified_type) 724 return; 725 726 if (BTy->getTag() != dwarf::DW_TAG_string_type) 727 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, 728 BTy->getEncoding()); 729 730 uint64_t Size = BTy->getSizeInBits() >> 3; 731 addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt, Size); 732 733 if (BTy->isBigEndian()) 734 addUInt(Buffer, dwarf::DW_AT_endianity, std::nullopt, dwarf::DW_END_big); 735 else if (BTy->isLittleEndian()) 736 addUInt(Buffer, dwarf::DW_AT_endianity, std::nullopt, dwarf::DW_END_little); 737 738 if (uint32_t NumExtraInhabitants = BTy->getNumExtraInhabitants()) 739 addUInt(Buffer, dwarf::DW_AT_LLVM_num_extra_inhabitants, std::nullopt, 740 NumExtraInhabitants); 741 } 742 743 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIStringType *STy) { 744 // Get core information. 745 StringRef Name = STy->getName(); 746 // Add name if not anonymous or intermediate type. 747 if (!Name.empty()) 748 addString(Buffer, dwarf::DW_AT_name, Name); 749 750 if (DIVariable *Var = STy->getStringLength()) { 751 if (auto *VarDIE = getDIE(Var)) 752 addDIEEntry(Buffer, dwarf::DW_AT_string_length, *VarDIE); 753 } else if (DIExpression *Expr = STy->getStringLengthExp()) { 754 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 755 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc); 756 // This is to describe the memory location of the 757 // length of a Fortran deferred length string, so 758 // lock it down as such. 759 DwarfExpr.setMemoryLocationKind(); 760 DwarfExpr.addExpression(Expr); 761 addBlock(Buffer, dwarf::DW_AT_string_length, DwarfExpr.finalize()); 762 } else { 763 uint64_t Size = STy->getSizeInBits() >> 3; 764 addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt, Size); 765 } 766 767 if (DIExpression *Expr = STy->getStringLocationExp()) { 768 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 769 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc); 770 // This is to describe the memory location of the 771 // string, so lock it down as such. 772 DwarfExpr.setMemoryLocationKind(); 773 DwarfExpr.addExpression(Expr); 774 addBlock(Buffer, dwarf::DW_AT_data_location, DwarfExpr.finalize()); 775 } 776 777 if (STy->getEncoding()) { 778 // For eventual Unicode support. 779 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, 780 STy->getEncoding()); 781 } 782 } 783 784 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) { 785 // Get core information. 786 StringRef Name = DTy->getName(); 787 uint64_t Size = DTy->getSizeInBits() >> 3; 788 uint16_t Tag = Buffer.getTag(); 789 790 // Map to main type, void will not have a type. 791 const DIType *FromTy = DTy->getBaseType(); 792 if (FromTy) 793 addType(Buffer, FromTy); 794 795 // Add name if not anonymous or intermediate type. 796 if (!Name.empty()) 797 addString(Buffer, dwarf::DW_AT_name, Name); 798 799 addAnnotation(Buffer, DTy->getAnnotations()); 800 801 // If alignment is specified for a typedef , create and insert DW_AT_alignment 802 // attribute in DW_TAG_typedef DIE. 803 if (Tag == dwarf::DW_TAG_typedef && DD->getDwarfVersion() >= 5) { 804 uint32_t AlignInBytes = DTy->getAlignInBytes(); 805 if (AlignInBytes > 0) 806 addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata, 807 AlignInBytes); 808 } 809 810 // Add size if non-zero (derived types might be zero-sized.) 811 if (Size && Tag != dwarf::DW_TAG_pointer_type 812 && Tag != dwarf::DW_TAG_ptr_to_member_type 813 && Tag != dwarf::DW_TAG_reference_type 814 && Tag != dwarf::DW_TAG_rvalue_reference_type) 815 addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt, Size); 816 817 if (Tag == dwarf::DW_TAG_ptr_to_member_type) 818 addDIEEntry(Buffer, dwarf::DW_AT_containing_type, 819 *getOrCreateTypeDIE(cast<DIDerivedType>(DTy)->getClassType())); 820 821 addAccess(Buffer, DTy->getFlags()); 822 823 // Add source line info if available and TyDesc is not a forward declaration. 824 if (!DTy->isForwardDecl()) 825 addSourceLine(Buffer, DTy); 826 827 // If DWARF address space value is other than None, add it. The IR 828 // verifier checks that DWARF address space only exists for pointer 829 // or reference types. 830 if (DTy->getDWARFAddressSpace()) 831 addUInt(Buffer, dwarf::DW_AT_address_class, dwarf::DW_FORM_data4, 832 *DTy->getDWARFAddressSpace()); 833 834 // Add template alias template parameters. 835 if (Tag == dwarf::DW_TAG_template_alias) 836 addTemplateParams(Buffer, DTy->getTemplateParams()); 837 838 if (auto PtrAuthData = DTy->getPtrAuthData()) { 839 addUInt(Buffer, dwarf::DW_AT_LLVM_ptrauth_key, dwarf::DW_FORM_data1, 840 PtrAuthData->key()); 841 if (PtrAuthData->isAddressDiscriminated()) 842 addFlag(Buffer, dwarf::DW_AT_LLVM_ptrauth_address_discriminated); 843 addUInt(Buffer, dwarf::DW_AT_LLVM_ptrauth_extra_discriminator, 844 dwarf::DW_FORM_data2, PtrAuthData->extraDiscriminator()); 845 if (PtrAuthData->isaPointer()) 846 addFlag(Buffer, dwarf::DW_AT_LLVM_ptrauth_isa_pointer); 847 if (PtrAuthData->authenticatesNullValues()) 848 addFlag(Buffer, dwarf::DW_AT_LLVM_ptrauth_authenticates_null_values); 849 } 850 } 851 852 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) { 853 for (unsigned i = 1, N = Args.size(); i < N; ++i) { 854 const DIType *Ty = Args[i]; 855 if (!Ty) { 856 assert(i == N-1 && "Unspecified parameter must be the last argument"); 857 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer); 858 } else { 859 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer); 860 addType(Arg, Ty); 861 if (Ty->isArtificial()) 862 addFlag(Arg, dwarf::DW_AT_artificial); 863 } 864 } 865 } 866 867 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) { 868 // Add return type. A void return won't have a type. 869 auto Elements = cast<DISubroutineType>(CTy)->getTypeArray(); 870 if (Elements.size()) 871 if (auto RTy = Elements[0]) 872 addType(Buffer, RTy); 873 874 bool isPrototyped = true; 875 if (Elements.size() == 2 && !Elements[1]) 876 isPrototyped = false; 877 878 constructSubprogramArguments(Buffer, Elements); 879 880 // Add prototype flag if we're dealing with a C language and the function has 881 // been prototyped. 882 if (isPrototyped && dwarf::isC((dwarf::SourceLanguage)getLanguage())) 883 addFlag(Buffer, dwarf::DW_AT_prototyped); 884 885 // Add a DW_AT_calling_convention if this has an explicit convention. 886 if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal) 887 addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, 888 CTy->getCC()); 889 890 if (CTy->isLValueReference()) 891 addFlag(Buffer, dwarf::DW_AT_reference); 892 893 if (CTy->isRValueReference()) 894 addFlag(Buffer, dwarf::DW_AT_rvalue_reference); 895 } 896 897 void DwarfUnit::addAnnotation(DIE &Buffer, DINodeArray Annotations) { 898 if (!Annotations) 899 return; 900 901 for (const Metadata *Annotation : Annotations->operands()) { 902 const MDNode *MD = cast<MDNode>(Annotation); 903 const MDString *Name = cast<MDString>(MD->getOperand(0)); 904 const auto &Value = MD->getOperand(1); 905 906 DIE &AnnotationDie = createAndAddDIE(dwarf::DW_TAG_LLVM_annotation, Buffer); 907 addString(AnnotationDie, dwarf::DW_AT_name, Name->getString()); 908 if (const auto *Data = dyn_cast<MDString>(Value)) 909 addString(AnnotationDie, dwarf::DW_AT_const_value, Data->getString()); 910 else if (const auto *Data = dyn_cast<ConstantAsMetadata>(Value)) 911 addConstantValue(AnnotationDie, Data->getValue()->getUniqueInteger(), 912 /*Unsigned=*/true); 913 else 914 assert(false && "Unsupported annotation value type"); 915 } 916 } 917 918 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) { 919 // Add name if not anonymous or intermediate type. 920 StringRef Name = CTy->getName(); 921 922 uint64_t Size = CTy->getSizeInBits() >> 3; 923 uint16_t Tag = Buffer.getTag(); 924 925 switch (Tag) { 926 case dwarf::DW_TAG_array_type: 927 constructArrayTypeDIE(Buffer, CTy); 928 break; 929 case dwarf::DW_TAG_enumeration_type: 930 constructEnumTypeDIE(Buffer, CTy); 931 break; 932 case dwarf::DW_TAG_variant_part: 933 case dwarf::DW_TAG_structure_type: 934 case dwarf::DW_TAG_union_type: 935 case dwarf::DW_TAG_class_type: 936 case dwarf::DW_TAG_namelist: { 937 // Emit the discriminator for a variant part. 938 DIDerivedType *Discriminator = nullptr; 939 if (Tag == dwarf::DW_TAG_variant_part) { 940 Discriminator = CTy->getDiscriminator(); 941 if (Discriminator) { 942 // DWARF says: 943 // If the variant part has a discriminant, the discriminant is 944 // represented by a separate debugging information entry which is 945 // a child of the variant part entry. 946 DIE &DiscMember = constructMemberDIE(Buffer, Discriminator); 947 addDIEEntry(Buffer, dwarf::DW_AT_discr, DiscMember); 948 } 949 } 950 951 // Add template parameters to a class, structure or union types. 952 if (Tag == dwarf::DW_TAG_class_type || 953 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) 954 addTemplateParams(Buffer, CTy->getTemplateParams()); 955 956 // Add elements to structure type. 957 DINodeArray Elements = CTy->getElements(); 958 for (const auto *Element : Elements) { 959 if (!Element) 960 continue; 961 if (auto *SP = dyn_cast<DISubprogram>(Element)) 962 getOrCreateSubprogramDIE(SP); 963 else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) { 964 if (DDTy->getTag() == dwarf::DW_TAG_friend) { 965 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer); 966 addType(ElemDie, DDTy->getBaseType(), dwarf::DW_AT_friend); 967 } else if (DDTy->isStaticMember()) { 968 getOrCreateStaticMemberDIE(DDTy); 969 } else if (Tag == dwarf::DW_TAG_variant_part) { 970 // When emitting a variant part, wrap each member in 971 // DW_TAG_variant. 972 DIE &Variant = createAndAddDIE(dwarf::DW_TAG_variant, Buffer); 973 if (const ConstantInt *CI = 974 dyn_cast_or_null<ConstantInt>(DDTy->getDiscriminantValue())) { 975 if (DD->isUnsignedDIType(Discriminator->getBaseType())) 976 addUInt(Variant, dwarf::DW_AT_discr_value, std::nullopt, 977 CI->getZExtValue()); 978 else 979 addSInt(Variant, dwarf::DW_AT_discr_value, std::nullopt, 980 CI->getSExtValue()); 981 } 982 constructMemberDIE(Variant, DDTy); 983 } else { 984 constructMemberDIE(Buffer, DDTy); 985 } 986 } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) { 987 DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer); 988 StringRef PropertyName = Property->getName(); 989 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName); 990 if (Property->getType()) 991 addType(ElemDie, Property->getType()); 992 addSourceLine(ElemDie, Property); 993 StringRef GetterName = Property->getGetterName(); 994 if (!GetterName.empty()) 995 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName); 996 StringRef SetterName = Property->getSetterName(); 997 if (!SetterName.empty()) 998 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName); 999 if (unsigned PropertyAttributes = Property->getAttributes()) 1000 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, std::nullopt, 1001 PropertyAttributes); 1002 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) { 1003 if (Composite->getTag() == dwarf::DW_TAG_variant_part) { 1004 DIE &VariantPart = createAndAddDIE(Composite->getTag(), Buffer); 1005 constructTypeDIE(VariantPart, Composite); 1006 } 1007 } else if (Tag == dwarf::DW_TAG_namelist) { 1008 auto *Var = dyn_cast<DINode>(Element); 1009 auto *VarDIE = getDIE(Var); 1010 if (VarDIE) { 1011 DIE &ItemDie = createAndAddDIE(dwarf::DW_TAG_namelist_item, Buffer); 1012 addDIEEntry(ItemDie, dwarf::DW_AT_namelist_item, *VarDIE); 1013 } 1014 } 1015 } 1016 1017 if (CTy->isAppleBlockExtension()) 1018 addFlag(Buffer, dwarf::DW_AT_APPLE_block); 1019 1020 if (CTy->getExportSymbols()) 1021 addFlag(Buffer, dwarf::DW_AT_export_symbols); 1022 1023 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type 1024 // inside C++ composite types to point to the base class with the vtable. 1025 // Rust uses DW_AT_containing_type to link a vtable to the type 1026 // for which it was created. 1027 if (auto *ContainingType = CTy->getVTableHolder()) 1028 addDIEEntry(Buffer, dwarf::DW_AT_containing_type, 1029 *getOrCreateTypeDIE(ContainingType)); 1030 1031 if (CTy->isObjcClassComplete()) 1032 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type); 1033 1034 // Add the type's non-standard calling convention. 1035 // DW_CC_pass_by_value/DW_CC_pass_by_reference are introduced in DWARF 5. 1036 if (!Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= 5) { 1037 uint8_t CC = 0; 1038 if (CTy->isTypePassByValue()) 1039 CC = dwarf::DW_CC_pass_by_value; 1040 else if (CTy->isTypePassByReference()) 1041 CC = dwarf::DW_CC_pass_by_reference; 1042 if (CC) 1043 addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, 1044 CC); 1045 } 1046 1047 if (auto *SpecifiedFrom = CTy->getSpecification()) 1048 addDIEEntry(Buffer, dwarf::DW_AT_specification, 1049 *getOrCreateContextDIE(SpecifiedFrom)); 1050 1051 break; 1052 } 1053 default: 1054 break; 1055 } 1056 1057 // Add name if not anonymous or intermediate type. 1058 if (!Name.empty()) 1059 addString(Buffer, dwarf::DW_AT_name, Name); 1060 1061 // For Swift, mangled names are put into DW_AT_linkage_name. 1062 if (CTy->getRuntimeLang() == dwarf::DW_LANG_Swift && CTy->getRawIdentifier()) 1063 addString(Buffer, dwarf::DW_AT_linkage_name, CTy->getIdentifier()); 1064 1065 addAnnotation(Buffer, CTy->getAnnotations()); 1066 1067 if (Tag == dwarf::DW_TAG_enumeration_type || 1068 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type || 1069 Tag == dwarf::DW_TAG_union_type) { 1070 // Add size if non-zero (derived types might be zero-sized.) 1071 // Ignore the size if it's a non-enum forward decl. 1072 // TODO: Do we care about size for enum forward declarations? 1073 if (Size && 1074 (!CTy->isForwardDecl() || Tag == dwarf::DW_TAG_enumeration_type)) 1075 addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt, Size); 1076 else if (!CTy->isForwardDecl()) 1077 // Add zero size if it is not a forward declaration. 1078 addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt, 0); 1079 1080 // If we're a forward decl, say so. 1081 if (CTy->isForwardDecl()) 1082 addFlag(Buffer, dwarf::DW_AT_declaration); 1083 1084 // Add accessibility info if available. 1085 addAccess(Buffer, CTy->getFlags()); 1086 1087 // Add source line info if available. 1088 if (!CTy->isForwardDecl()) 1089 addSourceLine(Buffer, CTy); 1090 1091 // No harm in adding the runtime language to the declaration. 1092 unsigned RLang = CTy->getRuntimeLang(); 1093 if (RLang) 1094 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1, 1095 RLang); 1096 1097 // Add align info if available. 1098 if (uint32_t AlignInBytes = CTy->getAlignInBytes()) 1099 addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata, 1100 AlignInBytes); 1101 1102 if (uint32_t NumExtraInhabitants = CTy->getNumExtraInhabitants()) 1103 addUInt(Buffer, dwarf::DW_AT_LLVM_num_extra_inhabitants, std::nullopt, 1104 NumExtraInhabitants); 1105 } 1106 } 1107 1108 void DwarfUnit::constructTemplateTypeParameterDIE( 1109 DIE &Buffer, const DITemplateTypeParameter *TP) { 1110 DIE &ParamDIE = 1111 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer); 1112 // Add the type if it exists, it could be void and therefore no type. 1113 if (TP->getType()) 1114 addType(ParamDIE, TP->getType()); 1115 if (!TP->getName().empty()) 1116 addString(ParamDIE, dwarf::DW_AT_name, TP->getName()); 1117 if (TP->isDefault() && isCompatibleWithVersion(5)) 1118 addFlag(ParamDIE, dwarf::DW_AT_default_value); 1119 } 1120 1121 void DwarfUnit::constructTemplateValueParameterDIE( 1122 DIE &Buffer, const DITemplateValueParameter *VP) { 1123 DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer); 1124 1125 // Add the type if there is one, template template and template parameter 1126 // packs will not have a type. 1127 if (VP->getTag() == dwarf::DW_TAG_template_value_parameter) 1128 addType(ParamDIE, VP->getType()); 1129 if (!VP->getName().empty()) 1130 addString(ParamDIE, dwarf::DW_AT_name, VP->getName()); 1131 if (VP->isDefault() && isCompatibleWithVersion(5)) 1132 addFlag(ParamDIE, dwarf::DW_AT_default_value); 1133 if (Metadata *Val = VP->getValue()) { 1134 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val)) 1135 addConstantValue(ParamDIE, CI, VP->getType()); 1136 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) { 1137 // We cannot describe the location of dllimport'd entities: the 1138 // computation of their address requires loads from the IAT. 1139 if (!GV->hasDLLImportStorageClass()) { 1140 // For declaration non-type template parameters (such as global values 1141 // and functions) 1142 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1143 addOpAddress(*Loc, Asm->getSymbol(GV)); 1144 // Emit DW_OP_stack_value to use the address as the immediate value of 1145 // the parameter, rather than a pointer to it. 1146 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value); 1147 addBlock(ParamDIE, dwarf::DW_AT_location, Loc); 1148 } 1149 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) { 1150 assert(isa<MDString>(Val)); 1151 addString(ParamDIE, dwarf::DW_AT_GNU_template_name, 1152 cast<MDString>(Val)->getString()); 1153 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) { 1154 addTemplateParams(ParamDIE, cast<MDTuple>(Val)); 1155 } 1156 } 1157 } 1158 1159 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) { 1160 // Construct the context before querying for the existence of the DIE in case 1161 // such construction creates the DIE. 1162 DIE *ContextDIE = getOrCreateContextDIE(NS->getScope()); 1163 1164 if (DIE *NDie = getDIE(NS)) 1165 return NDie; 1166 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS); 1167 1168 StringRef Name = NS->getName(); 1169 if (!Name.empty()) 1170 addString(NDie, dwarf::DW_AT_name, NS->getName()); 1171 else 1172 Name = "(anonymous namespace)"; 1173 DD->addAccelNamespace(*this, CUNode->getNameTableKind(), Name, NDie); 1174 addGlobalName(Name, NDie, NS->getScope()); 1175 if (NS->getExportSymbols()) 1176 addFlag(NDie, dwarf::DW_AT_export_symbols); 1177 return &NDie; 1178 } 1179 1180 DIE *DwarfUnit::getOrCreateModule(const DIModule *M) { 1181 // Construct the context before querying for the existence of the DIE in case 1182 // such construction creates the DIE. 1183 DIE *ContextDIE = getOrCreateContextDIE(M->getScope()); 1184 1185 if (DIE *MDie = getDIE(M)) 1186 return MDie; 1187 DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M); 1188 1189 if (!M->getName().empty()) { 1190 addString(MDie, dwarf::DW_AT_name, M->getName()); 1191 addGlobalName(M->getName(), MDie, M->getScope()); 1192 } 1193 if (!M->getConfigurationMacros().empty()) 1194 addString(MDie, dwarf::DW_AT_LLVM_config_macros, 1195 M->getConfigurationMacros()); 1196 if (!M->getIncludePath().empty()) 1197 addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath()); 1198 if (!M->getAPINotesFile().empty()) 1199 addString(MDie, dwarf::DW_AT_LLVM_apinotes, M->getAPINotesFile()); 1200 if (M->getFile()) 1201 addUInt(MDie, dwarf::DW_AT_decl_file, std::nullopt, 1202 getOrCreateSourceID(M->getFile())); 1203 if (M->getLineNo()) 1204 addUInt(MDie, dwarf::DW_AT_decl_line, std::nullopt, M->getLineNo()); 1205 if (M->getIsDecl()) 1206 addFlag(MDie, dwarf::DW_AT_declaration); 1207 1208 return &MDie; 1209 } 1210 1211 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) { 1212 // Construct the context before querying for the existence of the DIE in case 1213 // such construction creates the DIE (as is the case for member function 1214 // declarations). 1215 DIE *ContextDIE = 1216 Minimal ? &getUnitDie() : getOrCreateContextDIE(SP->getScope()); 1217 1218 if (DIE *SPDie = getDIE(SP)) 1219 return SPDie; 1220 1221 if (auto *SPDecl = SP->getDeclaration()) { 1222 if (!Minimal) { 1223 // Add subprogram definitions to the CU die directly. 1224 ContextDIE = &getUnitDie(); 1225 // Build the decl now to ensure it precedes the definition. 1226 getOrCreateSubprogramDIE(SPDecl); 1227 } 1228 } 1229 1230 // DW_TAG_inlined_subroutine may refer to this DIE. 1231 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP); 1232 1233 // Stop here and fill this in later, depending on whether or not this 1234 // subprogram turns out to have inlined instances or not. 1235 if (SP->isDefinition()) 1236 return &SPDie; 1237 1238 static_cast<DwarfUnit *>(SPDie.getUnit()) 1239 ->applySubprogramAttributes(SP, SPDie); 1240 return &SPDie; 1241 } 1242 1243 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP, 1244 DIE &SPDie, bool Minimal) { 1245 DIE *DeclDie = nullptr; 1246 StringRef DeclLinkageName; 1247 if (auto *SPDecl = SP->getDeclaration()) { 1248 if (!Minimal) { 1249 DITypeRefArray DeclArgs, DefinitionArgs; 1250 DeclArgs = SPDecl->getType()->getTypeArray(); 1251 DefinitionArgs = SP->getType()->getTypeArray(); 1252 1253 if (DeclArgs.size() && DefinitionArgs.size()) 1254 if (DefinitionArgs[0] != nullptr && DeclArgs[0] != DefinitionArgs[0]) 1255 addType(SPDie, DefinitionArgs[0]); 1256 1257 DeclDie = getDIE(SPDecl); 1258 assert(DeclDie && "This DIE should've already been constructed when the " 1259 "definition DIE was created in " 1260 "getOrCreateSubprogramDIE"); 1261 // Look at the Decl's linkage name only if we emitted it. 1262 if (DD->useAllLinkageNames()) 1263 DeclLinkageName = SPDecl->getLinkageName(); 1264 unsigned DeclID = getOrCreateSourceID(SPDecl->getFile()); 1265 unsigned DefID = getOrCreateSourceID(SP->getFile()); 1266 if (DeclID != DefID) 1267 addUInt(SPDie, dwarf::DW_AT_decl_file, std::nullopt, DefID); 1268 1269 if (SP->getLine() != SPDecl->getLine()) 1270 addUInt(SPDie, dwarf::DW_AT_decl_line, std::nullopt, SP->getLine()); 1271 } 1272 } 1273 1274 // Add function template parameters. 1275 addTemplateParams(SPDie, SP->getTemplateParams()); 1276 1277 // Add the linkage name if we have one and it isn't in the Decl. 1278 StringRef LinkageName = SP->getLinkageName(); 1279 assert(((LinkageName.empty() || DeclLinkageName.empty()) || 1280 LinkageName == DeclLinkageName) && 1281 "decl has a linkage name and it is different"); 1282 if (DeclLinkageName.empty() && 1283 // Always emit it for abstract subprograms. 1284 (DD->useAllLinkageNames() || DU->getAbstractScopeDIEs().lookup(SP))) 1285 addLinkageName(SPDie, LinkageName); 1286 1287 if (!DeclDie) 1288 return false; 1289 1290 // Refer to the function declaration where all the other attributes will be 1291 // found. 1292 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie); 1293 return true; 1294 } 1295 1296 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie, 1297 bool SkipSPAttributes) { 1298 // If -fdebug-info-for-profiling is enabled, need to emit the subprogram 1299 // and its source location. 1300 bool SkipSPSourceLocation = SkipSPAttributes && 1301 !CUNode->getDebugInfoForProfiling(); 1302 if (!SkipSPSourceLocation) 1303 if (applySubprogramDefinitionAttributes(SP, SPDie, SkipSPAttributes)) 1304 return; 1305 1306 // Constructors and operators for anonymous aggregates do not have names. 1307 if (!SP->getName().empty()) 1308 addString(SPDie, dwarf::DW_AT_name, SP->getName()); 1309 1310 addAnnotation(SPDie, SP->getAnnotations()); 1311 1312 if (!SkipSPSourceLocation) 1313 addSourceLine(SPDie, SP); 1314 1315 // Skip the rest of the attributes under -gmlt to save space. 1316 if (SkipSPAttributes) 1317 return; 1318 1319 // Add the prototype if we have a prototype and we have a C like 1320 // language. 1321 if (SP->isPrototyped() && dwarf::isC((dwarf::SourceLanguage)getLanguage())) 1322 addFlag(SPDie, dwarf::DW_AT_prototyped); 1323 1324 if (SP->isObjCDirect()) 1325 addFlag(SPDie, dwarf::DW_AT_APPLE_objc_direct); 1326 1327 unsigned CC = 0; 1328 DITypeRefArray Args; 1329 if (const DISubroutineType *SPTy = SP->getType()) { 1330 Args = SPTy->getTypeArray(); 1331 CC = SPTy->getCC(); 1332 } 1333 1334 // Add a DW_AT_calling_convention if this has an explicit convention. 1335 if (CC && CC != dwarf::DW_CC_normal) 1336 addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC); 1337 1338 // Add a return type. If this is a type like a C/C++ void type we don't add a 1339 // return type. 1340 if (Args.size()) 1341 if (auto Ty = Args[0]) 1342 addType(SPDie, Ty); 1343 1344 unsigned VK = SP->getVirtuality(); 1345 if (VK) { 1346 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK); 1347 if (SP->getVirtualIndex() != -1u) { 1348 DIELoc *Block = getDIELoc(); 1349 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 1350 addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex()); 1351 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block); 1352 } 1353 ContainingTypeMap.insert(std::make_pair(&SPDie, SP->getContainingType())); 1354 } 1355 1356 if (!SP->isDefinition()) { 1357 addFlag(SPDie, dwarf::DW_AT_declaration); 1358 1359 // Add arguments. Do not add arguments for subprogram definition. They will 1360 // be handled while processing variables. 1361 constructSubprogramArguments(SPDie, Args); 1362 } 1363 1364 addThrownTypes(SPDie, SP->getThrownTypes()); 1365 1366 if (SP->isArtificial()) 1367 addFlag(SPDie, dwarf::DW_AT_artificial); 1368 1369 if (!SP->isLocalToUnit()) 1370 addFlag(SPDie, dwarf::DW_AT_external); 1371 1372 if (DD->useAppleExtensionAttributes()) { 1373 if (SP->isOptimized()) 1374 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized); 1375 1376 if (unsigned isa = Asm->getISAEncoding()) 1377 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa); 1378 } 1379 1380 if (SP->isLValueReference()) 1381 addFlag(SPDie, dwarf::DW_AT_reference); 1382 1383 if (SP->isRValueReference()) 1384 addFlag(SPDie, dwarf::DW_AT_rvalue_reference); 1385 1386 if (SP->isNoReturn()) 1387 addFlag(SPDie, dwarf::DW_AT_noreturn); 1388 1389 addAccess(SPDie, SP->getFlags()); 1390 1391 if (SP->isExplicit()) 1392 addFlag(SPDie, dwarf::DW_AT_explicit); 1393 1394 if (SP->isMainSubprogram()) 1395 addFlag(SPDie, dwarf::DW_AT_main_subprogram); 1396 if (SP->isPure()) 1397 addFlag(SPDie, dwarf::DW_AT_pure); 1398 if (SP->isElemental()) 1399 addFlag(SPDie, dwarf::DW_AT_elemental); 1400 if (SP->isRecursive()) 1401 addFlag(SPDie, dwarf::DW_AT_recursive); 1402 1403 if (!SP->getTargetFuncName().empty()) 1404 addString(SPDie, dwarf::DW_AT_trampoline, SP->getTargetFuncName()); 1405 1406 if (DD->getDwarfVersion() >= 5 && SP->isDeleted()) 1407 addFlag(SPDie, dwarf::DW_AT_deleted); 1408 } 1409 1410 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR, 1411 DIE *IndexTy) { 1412 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer); 1413 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy); 1414 1415 // The LowerBound value defines the lower bounds which is typically zero for 1416 // C/C++. The Count value is the number of elements. Values are 64 bit. If 1417 // Count == -1 then the array is unbounded and we do not emit 1418 // DW_AT_lower_bound and DW_AT_count attributes. 1419 int64_t DefaultLowerBound = getDefaultLowerBound(); 1420 1421 auto AddBoundTypeEntry = [&](dwarf::Attribute Attr, 1422 DISubrange::BoundType Bound) -> void { 1423 if (auto *BV = dyn_cast_if_present<DIVariable *>(Bound)) { 1424 if (auto *VarDIE = getDIE(BV)) 1425 addDIEEntry(DW_Subrange, Attr, *VarDIE); 1426 } else if (auto *BE = dyn_cast_if_present<DIExpression *>(Bound)) { 1427 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1428 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc); 1429 DwarfExpr.setMemoryLocationKind(); 1430 DwarfExpr.addExpression(BE); 1431 addBlock(DW_Subrange, Attr, DwarfExpr.finalize()); 1432 } else if (auto *BI = dyn_cast_if_present<ConstantInt *>(Bound)) { 1433 if (Attr == dwarf::DW_AT_count) { 1434 if (BI->getSExtValue() != -1) 1435 addUInt(DW_Subrange, Attr, std::nullopt, BI->getSExtValue()); 1436 } else if (Attr != dwarf::DW_AT_lower_bound || DefaultLowerBound == -1 || 1437 BI->getSExtValue() != DefaultLowerBound) 1438 addSInt(DW_Subrange, Attr, dwarf::DW_FORM_sdata, BI->getSExtValue()); 1439 } 1440 }; 1441 1442 AddBoundTypeEntry(dwarf::DW_AT_lower_bound, SR->getLowerBound()); 1443 1444 AddBoundTypeEntry(dwarf::DW_AT_count, SR->getCount()); 1445 1446 AddBoundTypeEntry(dwarf::DW_AT_upper_bound, SR->getUpperBound()); 1447 1448 AddBoundTypeEntry(dwarf::DW_AT_byte_stride, SR->getStride()); 1449 } 1450 1451 void DwarfUnit::constructGenericSubrangeDIE(DIE &Buffer, 1452 const DIGenericSubrange *GSR, 1453 DIE *IndexTy) { 1454 DIE &DwGenericSubrange = 1455 createAndAddDIE(dwarf::DW_TAG_generic_subrange, Buffer); 1456 addDIEEntry(DwGenericSubrange, dwarf::DW_AT_type, *IndexTy); 1457 1458 int64_t DefaultLowerBound = getDefaultLowerBound(); 1459 1460 auto AddBoundTypeEntry = [&](dwarf::Attribute Attr, 1461 DIGenericSubrange::BoundType Bound) -> void { 1462 if (auto *BV = dyn_cast_if_present<DIVariable *>(Bound)) { 1463 if (auto *VarDIE = getDIE(BV)) 1464 addDIEEntry(DwGenericSubrange, Attr, *VarDIE); 1465 } else if (auto *BE = dyn_cast_if_present<DIExpression *>(Bound)) { 1466 if (BE->isConstant() && 1467 DIExpression::SignedOrUnsignedConstant::SignedConstant == 1468 *BE->isConstant()) { 1469 if (Attr != dwarf::DW_AT_lower_bound || DefaultLowerBound == -1 || 1470 static_cast<int64_t>(BE->getElement(1)) != DefaultLowerBound) 1471 addSInt(DwGenericSubrange, Attr, dwarf::DW_FORM_sdata, 1472 BE->getElement(1)); 1473 } else { 1474 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1475 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc); 1476 DwarfExpr.setMemoryLocationKind(); 1477 DwarfExpr.addExpression(BE); 1478 addBlock(DwGenericSubrange, Attr, DwarfExpr.finalize()); 1479 } 1480 } 1481 }; 1482 1483 AddBoundTypeEntry(dwarf::DW_AT_lower_bound, GSR->getLowerBound()); 1484 AddBoundTypeEntry(dwarf::DW_AT_count, GSR->getCount()); 1485 AddBoundTypeEntry(dwarf::DW_AT_upper_bound, GSR->getUpperBound()); 1486 AddBoundTypeEntry(dwarf::DW_AT_byte_stride, GSR->getStride()); 1487 } 1488 1489 DIE *DwarfUnit::getIndexTyDie() { 1490 if (IndexTyDie) 1491 return IndexTyDie; 1492 // Construct an integer type to use for indexes. 1493 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie()); 1494 StringRef Name = "__ARRAY_SIZE_TYPE__"; 1495 addString(*IndexTyDie, dwarf::DW_AT_name, Name); 1496 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, std::nullopt, sizeof(int64_t)); 1497 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, 1498 dwarf::getArrayIndexTypeEncoding( 1499 (dwarf::SourceLanguage)getLanguage())); 1500 DD->addAccelType(*this, CUNode->getNameTableKind(), Name, *IndexTyDie, 1501 /*Flags*/ 0); 1502 return IndexTyDie; 1503 } 1504 1505 /// Returns true if the vector's size differs from the sum of sizes of elements 1506 /// the user specified. This can occur if the vector has been rounded up to 1507 /// fit memory alignment constraints. 1508 static bool hasVectorBeenPadded(const DICompositeType *CTy) { 1509 assert(CTy && CTy->isVector() && "Composite type is not a vector"); 1510 const uint64_t ActualSize = CTy->getSizeInBits(); 1511 1512 // Obtain the size of each element in the vector. 1513 DIType *BaseTy = CTy->getBaseType(); 1514 assert(BaseTy && "Unknown vector element type."); 1515 const uint64_t ElementSize = BaseTy->getSizeInBits(); 1516 1517 // Locate the number of elements in the vector. 1518 const DINodeArray Elements = CTy->getElements(); 1519 assert(Elements.size() == 1 && 1520 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type && 1521 "Invalid vector element array, expected one element of type subrange"); 1522 const auto Subrange = cast<DISubrange>(Elements[0]); 1523 const auto NumVecElements = 1524 Subrange->getCount() 1525 ? cast<ConstantInt *>(Subrange->getCount())->getSExtValue() 1526 : 0; 1527 1528 // Ensure we found the element count and that the actual size is wide 1529 // enough to contain the requested size. 1530 assert(ActualSize >= (NumVecElements * ElementSize) && "Invalid vector size"); 1531 return ActualSize != (NumVecElements * ElementSize); 1532 } 1533 1534 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) { 1535 if (CTy->isVector()) { 1536 addFlag(Buffer, dwarf::DW_AT_GNU_vector); 1537 if (hasVectorBeenPadded(CTy)) 1538 addUInt(Buffer, dwarf::DW_AT_byte_size, std::nullopt, 1539 CTy->getSizeInBits() / CHAR_BIT); 1540 } 1541 1542 if (DIVariable *Var = CTy->getDataLocation()) { 1543 if (auto *VarDIE = getDIE(Var)) 1544 addDIEEntry(Buffer, dwarf::DW_AT_data_location, *VarDIE); 1545 } else if (DIExpression *Expr = CTy->getDataLocationExp()) { 1546 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1547 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc); 1548 DwarfExpr.setMemoryLocationKind(); 1549 DwarfExpr.addExpression(Expr); 1550 addBlock(Buffer, dwarf::DW_AT_data_location, DwarfExpr.finalize()); 1551 } 1552 1553 if (DIVariable *Var = CTy->getAssociated()) { 1554 if (auto *VarDIE = getDIE(Var)) 1555 addDIEEntry(Buffer, dwarf::DW_AT_associated, *VarDIE); 1556 } else if (DIExpression *Expr = CTy->getAssociatedExp()) { 1557 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1558 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc); 1559 DwarfExpr.setMemoryLocationKind(); 1560 DwarfExpr.addExpression(Expr); 1561 addBlock(Buffer, dwarf::DW_AT_associated, DwarfExpr.finalize()); 1562 } 1563 1564 if (DIVariable *Var = CTy->getAllocated()) { 1565 if (auto *VarDIE = getDIE(Var)) 1566 addDIEEntry(Buffer, dwarf::DW_AT_allocated, *VarDIE); 1567 } else if (DIExpression *Expr = CTy->getAllocatedExp()) { 1568 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1569 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc); 1570 DwarfExpr.setMemoryLocationKind(); 1571 DwarfExpr.addExpression(Expr); 1572 addBlock(Buffer, dwarf::DW_AT_allocated, DwarfExpr.finalize()); 1573 } 1574 1575 if (auto *RankConst = CTy->getRankConst()) { 1576 addSInt(Buffer, dwarf::DW_AT_rank, dwarf::DW_FORM_sdata, 1577 RankConst->getSExtValue()); 1578 } else if (auto *RankExpr = CTy->getRankExp()) { 1579 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1580 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc); 1581 DwarfExpr.setMemoryLocationKind(); 1582 DwarfExpr.addExpression(RankExpr); 1583 addBlock(Buffer, dwarf::DW_AT_rank, DwarfExpr.finalize()); 1584 } 1585 1586 // Emit the element type. 1587 addType(Buffer, CTy->getBaseType()); 1588 1589 // Get an anonymous type for index type. 1590 // FIXME: This type should be passed down from the front end 1591 // as different languages may have different sizes for indexes. 1592 DIE *IdxTy = getIndexTyDie(); 1593 1594 // Add subranges to array type. 1595 DINodeArray Elements = CTy->getElements(); 1596 for (DINode *E : Elements) { 1597 // FIXME: Should this really be such a loose cast? 1598 if (auto *Element = dyn_cast_or_null<DINode>(E)) { 1599 if (Element->getTag() == dwarf::DW_TAG_subrange_type) 1600 constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy); 1601 else if (Element->getTag() == dwarf::DW_TAG_generic_subrange) 1602 constructGenericSubrangeDIE(Buffer, cast<DIGenericSubrange>(Element), 1603 IdxTy); 1604 } 1605 } 1606 } 1607 1608 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) { 1609 const DIType *DTy = CTy->getBaseType(); 1610 bool IsUnsigned = DTy && DD->isUnsignedDIType(DTy); 1611 if (DTy) { 1612 if (!Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= 3) 1613 addType(Buffer, DTy); 1614 if (DD->getDwarfVersion() >= 4 && (CTy->getFlags() & DINode::FlagEnumClass)) 1615 addFlag(Buffer, dwarf::DW_AT_enum_class); 1616 } 1617 1618 auto *Context = CTy->getScope(); 1619 bool IndexEnumerators = !Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) || 1620 isa<DINamespace>(Context) || isa<DICommonBlock>(Context); 1621 DINodeArray Elements = CTy->getElements(); 1622 1623 // Add enumerators to enumeration type. 1624 for (const DINode *E : Elements) { 1625 auto *Enum = dyn_cast_or_null<DIEnumerator>(E); 1626 if (Enum) { 1627 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer); 1628 StringRef Name = Enum->getName(); 1629 addString(Enumerator, dwarf::DW_AT_name, Name); 1630 addConstantValue(Enumerator, Enum->getValue(), IsUnsigned); 1631 if (IndexEnumerators) 1632 addGlobalName(Name, Enumerator, Context); 1633 } 1634 } 1635 } 1636 1637 void DwarfUnit::constructContainingTypeDIEs() { 1638 for (auto &P : ContainingTypeMap) { 1639 DIE &SPDie = *P.first; 1640 const DINode *D = P.second; 1641 if (!D) 1642 continue; 1643 DIE *NDie = getDIE(D); 1644 if (!NDie) 1645 continue; 1646 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie); 1647 } 1648 } 1649 1650 DIE &DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) { 1651 DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer); 1652 StringRef Name = DT->getName(); 1653 if (!Name.empty()) 1654 addString(MemberDie, dwarf::DW_AT_name, Name); 1655 1656 addAnnotation(MemberDie, DT->getAnnotations()); 1657 1658 if (DIType *Resolved = DT->getBaseType()) 1659 addType(MemberDie, Resolved); 1660 1661 addSourceLine(MemberDie, DT); 1662 1663 if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) { 1664 1665 // For C++, virtual base classes are not at fixed offset. Use following 1666 // expression to extract appropriate offset from vtable. 1667 // BaseAddr = ObAddr + *((*ObAddr) - Offset) 1668 1669 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc; 1670 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup); 1671 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 1672 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 1673 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits()); 1674 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus); 1675 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 1676 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus); 1677 1678 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie); 1679 } else { 1680 uint64_t Size = DT->getSizeInBits(); 1681 uint64_t FieldSize = DD->getBaseTypeSize(DT); 1682 uint32_t AlignInBytes = DT->getAlignInBytes(); 1683 uint64_t OffsetInBytes; 1684 1685 bool IsBitfield = DT->isBitField(); 1686 if (IsBitfield) { 1687 // Handle bitfield, assume bytes are 8 bits. 1688 if (DD->useDWARF2Bitfields()) 1689 addUInt(MemberDie, dwarf::DW_AT_byte_size, std::nullopt, FieldSize / 8); 1690 addUInt(MemberDie, dwarf::DW_AT_bit_size, std::nullopt, Size); 1691 1692 assert(DT->getOffsetInBits() <= 1693 (uint64_t)std::numeric_limits<int64_t>::max()); 1694 int64_t Offset = DT->getOffsetInBits(); 1695 // We can't use DT->getAlignInBits() here: AlignInBits for member type 1696 // is non-zero if and only if alignment was forced (e.g. _Alignas()), 1697 // which can't be done with bitfields. Thus we use FieldSize here. 1698 uint32_t AlignInBits = FieldSize; 1699 uint32_t AlignMask = ~(AlignInBits - 1); 1700 // The bits from the start of the storage unit to the start of the field. 1701 uint64_t StartBitOffset = Offset - (Offset & AlignMask); 1702 // The byte offset of the field's aligned storage unit inside the struct. 1703 OffsetInBytes = (Offset - StartBitOffset) / 8; 1704 1705 if (DD->useDWARF2Bitfields()) { 1706 uint64_t HiMark = (Offset + FieldSize) & AlignMask; 1707 uint64_t FieldOffset = (HiMark - FieldSize); 1708 Offset -= FieldOffset; 1709 1710 // Maybe we need to work from the other end. 1711 if (Asm->getDataLayout().isLittleEndian()) 1712 Offset = FieldSize - (Offset + Size); 1713 1714 if (Offset < 0) 1715 addSInt(MemberDie, dwarf::DW_AT_bit_offset, dwarf::DW_FORM_sdata, 1716 Offset); 1717 else 1718 addUInt(MemberDie, dwarf::DW_AT_bit_offset, std::nullopt, 1719 (uint64_t)Offset); 1720 OffsetInBytes = FieldOffset >> 3; 1721 } else { 1722 addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, std::nullopt, Offset); 1723 } 1724 } else { 1725 // This is not a bitfield. 1726 OffsetInBytes = DT->getOffsetInBits() / 8; 1727 if (AlignInBytes) 1728 addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata, 1729 AlignInBytes); 1730 } 1731 1732 if (DD->getDwarfVersion() <= 2) { 1733 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc; 1734 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 1735 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes); 1736 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie); 1737 } else if (!IsBitfield || DD->useDWARF2Bitfields()) { 1738 // In DWARF v3, DW_FORM_data4/8 in DW_AT_data_member_location are 1739 // interpreted as location-list pointers. Interpreting constants as 1740 // pointers is not expected, so we use DW_FORM_udata to encode the 1741 // constants here. 1742 if (DD->getDwarfVersion() == 3) 1743 addUInt(MemberDie, dwarf::DW_AT_data_member_location, 1744 dwarf::DW_FORM_udata, OffsetInBytes); 1745 else 1746 addUInt(MemberDie, dwarf::DW_AT_data_member_location, std::nullopt, 1747 OffsetInBytes); 1748 } 1749 } 1750 1751 addAccess(MemberDie, DT->getFlags()); 1752 1753 if (DT->isVirtual()) 1754 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, 1755 dwarf::DW_VIRTUALITY_virtual); 1756 1757 // Objective-C properties. 1758 if (DINode *PNode = DT->getObjCProperty()) 1759 if (DIE *PDie = getDIE(PNode)) 1760 addAttribute(MemberDie, dwarf::DW_AT_APPLE_property, 1761 dwarf::DW_FORM_ref4, DIEEntry(*PDie)); 1762 1763 if (DT->isArtificial()) 1764 addFlag(MemberDie, dwarf::DW_AT_artificial); 1765 1766 return MemberDie; 1767 } 1768 1769 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) { 1770 if (!DT) 1771 return nullptr; 1772 1773 // Construct the context before querying for the existence of the DIE in case 1774 // such construction creates the DIE. 1775 DIE *ContextDIE = getOrCreateContextDIE(DT->getScope()); 1776 assert(dwarf::isType(ContextDIE->getTag()) && 1777 "Static member should belong to a type."); 1778 1779 if (DIE *StaticMemberDIE = getDIE(DT)) 1780 return StaticMemberDIE; 1781 1782 DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT); 1783 1784 const DIType *Ty = DT->getBaseType(); 1785 1786 addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName()); 1787 addType(StaticMemberDIE, Ty); 1788 addSourceLine(StaticMemberDIE, DT); 1789 addFlag(StaticMemberDIE, dwarf::DW_AT_external); 1790 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration); 1791 1792 // Consider the case when the static member was created by the compiler. 1793 if (DT->isArtificial()) 1794 addFlag(StaticMemberDIE, dwarf::DW_AT_artificial); 1795 1796 // FIXME: We could omit private if the parent is a class_type, and 1797 // public if the parent is something else. 1798 addAccess(StaticMemberDIE, DT->getFlags()); 1799 1800 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant())) 1801 addConstantValue(StaticMemberDIE, CI, Ty); 1802 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant())) 1803 addConstantFPValue(StaticMemberDIE, CFP); 1804 1805 if (uint32_t AlignInBytes = DT->getAlignInBytes()) 1806 addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata, 1807 AlignInBytes); 1808 1809 return &StaticMemberDIE; 1810 } 1811 1812 void DwarfUnit::emitCommonHeader(bool UseOffsets, dwarf::UnitType UT) { 1813 // Emit size of content not including length itself 1814 if (!DD->useSectionsAsReferences()) 1815 EndLabel = Asm->emitDwarfUnitLength( 1816 isDwoUnit() ? "debug_info_dwo" : "debug_info", "Length of Unit"); 1817 else 1818 Asm->emitDwarfUnitLength(getHeaderSize() + getUnitDie().getSize(), 1819 "Length of Unit"); 1820 1821 Asm->OutStreamer->AddComment("DWARF version number"); 1822 unsigned Version = DD->getDwarfVersion(); 1823 Asm->emitInt16(Version); 1824 1825 // DWARF v5 reorders the address size and adds a unit type. 1826 if (Version >= 5) { 1827 Asm->OutStreamer->AddComment("DWARF Unit Type"); 1828 Asm->emitInt8(UT); 1829 Asm->OutStreamer->AddComment("Address Size (in bytes)"); 1830 Asm->emitInt8(Asm->MAI->getCodePointerSize()); 1831 } 1832 1833 // We share one abbreviations table across all units so it's always at the 1834 // start of the section. Use a relocatable offset where needed to ensure 1835 // linking doesn't invalidate that offset. 1836 Asm->OutStreamer->AddComment("Offset Into Abbrev. Section"); 1837 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 1838 if (UseOffsets) 1839 Asm->emitDwarfLengthOrOffset(0); 1840 else 1841 Asm->emitDwarfSymbolReference( 1842 TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false); 1843 1844 if (Version <= 4) { 1845 Asm->OutStreamer->AddComment("Address Size (in bytes)"); 1846 Asm->emitInt8(Asm->MAI->getCodePointerSize()); 1847 } 1848 } 1849 1850 void DwarfTypeUnit::emitHeader(bool UseOffsets) { 1851 if (!DD->useSplitDwarf()) { 1852 LabelBegin = Asm->createTempSymbol("tu_begin"); 1853 Asm->OutStreamer->emitLabel(LabelBegin); 1854 } 1855 DwarfUnit::emitCommonHeader(UseOffsets, 1856 DD->useSplitDwarf() ? dwarf::DW_UT_split_type 1857 : dwarf::DW_UT_type); 1858 Asm->OutStreamer->AddComment("Type Signature"); 1859 Asm->OutStreamer->emitIntValue(TypeSignature, sizeof(TypeSignature)); 1860 Asm->OutStreamer->AddComment("Type DIE Offset"); 1861 // In a skeleton type unit there is no type DIE so emit a zero offset. 1862 Asm->emitDwarfLengthOrOffset(Ty ? Ty->getOffset() : 0); 1863 } 1864 1865 void DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute, 1866 const MCSymbol *Hi, const MCSymbol *Lo) { 1867 addAttribute(Die, Attribute, DD->getDwarfSectionOffsetForm(), 1868 new (DIEValueAllocator) DIEDelta(Hi, Lo)); 1869 } 1870 1871 void DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute, 1872 const MCSymbol *Label, const MCSymbol *Sec) { 1873 if (Asm->doesDwarfUseRelocationsAcrossSections()) 1874 addLabel(Die, Attribute, DD->getDwarfSectionOffsetForm(), Label); 1875 else 1876 addSectionDelta(Die, Attribute, Label, Sec); 1877 } 1878 1879 bool DwarfTypeUnit::isDwoUnit() const { 1880 // Since there are no skeleton type units, all type units are dwo type units 1881 // when split DWARF is being used. 1882 return DD->useSplitDwarf(); 1883 } 1884 1885 void DwarfTypeUnit::addGlobalName(StringRef Name, const DIE &Die, 1886 const DIScope *Context) { 1887 getCU().addGlobalNameForTypeUnit(Name, Context); 1888 } 1889 1890 void DwarfTypeUnit::addGlobalTypeImpl(const DIType *Ty, const DIE &Die, 1891 const DIScope *Context) { 1892 getCU().addGlobalTypeUnitType(Ty, Context); 1893 } 1894 1895 const MCSymbol *DwarfUnit::getCrossSectionRelativeBaseAddress() const { 1896 if (!Asm->doesDwarfUseRelocationsAcrossSections()) 1897 return nullptr; 1898 if (isDwoUnit()) 1899 return nullptr; 1900 return getSection()->getBeginSymbol(); 1901 } 1902 1903 void DwarfUnit::addStringOffsetsStart() { 1904 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 1905 addSectionLabel(getUnitDie(), dwarf::DW_AT_str_offsets_base, 1906 DU->getStringOffsetsStartSym(), 1907 TLOF.getDwarfStrOffSection()->getBeginSymbol()); 1908 } 1909 1910 void DwarfUnit::addRnglistsBase() { 1911 assert(DD->getDwarfVersion() >= 5 && 1912 "DW_AT_rnglists_base requires DWARF version 5 or later"); 1913 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 1914 addSectionLabel(getUnitDie(), dwarf::DW_AT_rnglists_base, 1915 DU->getRnglistsTableBaseSym(), 1916 TLOF.getDwarfRnglistsSection()->getBeginSymbol()); 1917 } 1918 1919 void DwarfTypeUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) { 1920 DD->getAddressPool().resetUsedFlag(true); 1921 } 1922 1923 bool DwarfUnit::isCompatibleWithVersion(uint16_t Version) const { 1924 return !Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= Version; 1925 } 1926