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