1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains support for constructing a dwarf compile unit. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "DwarfUnit.h" 15 #include "AddressPool.h" 16 #include "DwarfCompileUnit.h" 17 #include "DwarfDebug.h" 18 #include "DwarfExpression.h" 19 #include "llvm/ADT/APFloat.h" 20 #include "llvm/ADT/APInt.h" 21 #include "llvm/ADT/iterator_range.h" 22 #include "llvm/ADT/None.h" 23 #include "llvm/CodeGen/MachineFunction.h" 24 #include "llvm/CodeGen/MachineOperand.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/GlobalValue.h" 28 #include "llvm/IR/Metadata.h" 29 #include "llvm/MC/MachineLocation.h" 30 #include "llvm/MC/MCDwarf.h" 31 #include "llvm/MC/MCSection.h" 32 #include "llvm/MC/MCStreamer.h" 33 #include "llvm/Support/Casting.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Target/TargetLoweringObjectFile.h" 36 #include "llvm/Target/TargetRegisterInfo.h" 37 #include "llvm/Target/TargetSubtargetInfo.h" 38 #include <cassert> 39 #include <cstdint> 40 #include <string> 41 #include <utility> 42 43 using namespace llvm; 44 45 #define DEBUG_TYPE "dwarfdebug" 46 47 static cl::opt<bool> 48 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden, 49 cl::desc("Generate DWARF4 type units."), 50 cl::init(false)); 51 52 DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP, DwarfUnit &DU, 53 DIELoc &DIE) 54 : DwarfExpression(AP.getDwarfDebug()->getDwarfVersion()), AP(AP), DU(DU), 55 DIE(DIE) {} 56 57 void DIEDwarfExpression::EmitOp(uint8_t Op, const char* Comment) { 58 DU.addUInt(DIE, dwarf::DW_FORM_data1, Op); 59 } 60 61 void DIEDwarfExpression::EmitSigned(int64_t Value) { 62 DU.addSInt(DIE, dwarf::DW_FORM_sdata, Value); 63 } 64 65 void DIEDwarfExpression::EmitUnsigned(uint64_t Value) { 66 DU.addUInt(DIE, dwarf::DW_FORM_udata, Value); 67 } 68 69 bool DIEDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI, 70 unsigned MachineReg) { 71 return MachineReg == TRI.getFrameRegister(*AP.MF); 72 } 73 74 DwarfUnit::DwarfUnit(dwarf::Tag UnitTag, const DICompileUnit *Node, 75 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU) 76 : CUNode(Node), UnitDie(*DIE::get(DIEValueAllocator, UnitTag)), Asm(A), 77 DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr) { 78 assert(UnitTag == dwarf::DW_TAG_compile_unit || 79 UnitTag == dwarf::DW_TAG_type_unit); 80 } 81 82 DwarfTypeUnit::DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A, 83 DwarfDebug *DW, DwarfFile *DWU, 84 MCDwarfDwoLineTable *SplitLineTable) 85 : DwarfUnit(dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU), CU(CU), 86 SplitLineTable(SplitLineTable) { 87 if (SplitLineTable) 88 addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0); 89 } 90 91 DwarfUnit::~DwarfUnit() { 92 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j) 93 DIEBlocks[j]->~DIEBlock(); 94 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j) 95 DIELocs[j]->~DIELoc(); 96 } 97 98 int64_t DwarfUnit::getDefaultLowerBound() const { 99 switch (getLanguage()) { 100 default: 101 break; 102 103 case dwarf::DW_LANG_C89: 104 case dwarf::DW_LANG_C99: 105 case dwarf::DW_LANG_C: 106 case dwarf::DW_LANG_C_plus_plus: 107 case dwarf::DW_LANG_ObjC: 108 case dwarf::DW_LANG_ObjC_plus_plus: 109 return 0; 110 111 case dwarf::DW_LANG_Fortran77: 112 case dwarf::DW_LANG_Fortran90: 113 case dwarf::DW_LANG_Fortran95: 114 return 1; 115 116 // The languages below have valid values only if the DWARF version >= 4. 117 case dwarf::DW_LANG_Java: 118 case dwarf::DW_LANG_Python: 119 case dwarf::DW_LANG_UPC: 120 case dwarf::DW_LANG_D: 121 if (dwarf::DWARF_VERSION >= 4) 122 return 0; 123 break; 124 125 case dwarf::DW_LANG_Ada83: 126 case dwarf::DW_LANG_Ada95: 127 case dwarf::DW_LANG_Cobol74: 128 case dwarf::DW_LANG_Cobol85: 129 case dwarf::DW_LANG_Modula2: 130 case dwarf::DW_LANG_Pascal83: 131 case dwarf::DW_LANG_PLI: 132 if (dwarf::DWARF_VERSION >= 4) 133 return 1; 134 break; 135 136 // The languages below have valid values only if the DWARF version >= 5. 137 case dwarf::DW_LANG_OpenCL: 138 case dwarf::DW_LANG_Go: 139 case dwarf::DW_LANG_Haskell: 140 case dwarf::DW_LANG_C_plus_plus_03: 141 case dwarf::DW_LANG_C_plus_plus_11: 142 case dwarf::DW_LANG_OCaml: 143 case dwarf::DW_LANG_Rust: 144 case dwarf::DW_LANG_C11: 145 case dwarf::DW_LANG_Swift: 146 case dwarf::DW_LANG_Dylan: 147 case dwarf::DW_LANG_C_plus_plus_14: 148 if (dwarf::DWARF_VERSION >= 5) 149 return 0; 150 break; 151 152 case dwarf::DW_LANG_Modula3: 153 case dwarf::DW_LANG_Julia: 154 case dwarf::DW_LANG_Fortran03: 155 case dwarf::DW_LANG_Fortran08: 156 if (dwarf::DWARF_VERSION >= 5) 157 return 1; 158 break; 159 } 160 161 return -1; 162 } 163 164 /// Check whether the DIE for this MDNode can be shared across CUs. 165 static bool isShareableAcrossCUs(const DINode *D) { 166 // When the MDNode can be part of the type system, the DIE can be shared 167 // across CUs. 168 // Combining type units and cross-CU DIE sharing is lower value (since 169 // cross-CU DIE sharing is used in LTO and removes type redundancy at that 170 // level already) but may be implementable for some value in projects 171 // building multiple independent libraries with LTO and then linking those 172 // together. 173 return (isa<DIType>(D) || 174 (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) && 175 !GenerateDwarfTypeUnits; 176 } 177 178 DIE *DwarfUnit::getDIE(const DINode *D) const { 179 if (isShareableAcrossCUs(D)) 180 return DU->getDIE(D); 181 return MDNodeToDieMap.lookup(D); 182 } 183 184 void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) { 185 if (isShareableAcrossCUs(Desc)) { 186 DU->insertDIE(Desc, D); 187 return; 188 } 189 MDNodeToDieMap.insert(std::make_pair(Desc, D)); 190 } 191 192 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) { 193 if (DD->getDwarfVersion() >= 4) 194 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag_present, 195 DIEInteger(1)); 196 else 197 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag, 198 DIEInteger(1)); 199 } 200 201 void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute, 202 Optional<dwarf::Form> Form, uint64_t Integer) { 203 if (!Form) 204 Form = DIEInteger::BestForm(false, Integer); 205 Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer)); 206 } 207 208 void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form, 209 uint64_t Integer) { 210 addUInt(Block, (dwarf::Attribute)0, Form, Integer); 211 } 212 213 void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute, 214 Optional<dwarf::Form> Form, int64_t Integer) { 215 if (!Form) 216 Form = DIEInteger::BestForm(true, Integer); 217 Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer)); 218 } 219 220 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form, 221 int64_t Integer) { 222 addSInt(Die, (dwarf::Attribute)0, Form, Integer); 223 } 224 225 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute, 226 StringRef String) { 227 Die.addValue(DIEValueAllocator, Attribute, 228 isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp, 229 DIEString(DU->getStringPool().getEntry(*Asm, String))); 230 } 231 232 DIEValueList::value_iterator DwarfUnit::addLabel(DIEValueList &Die, 233 dwarf::Attribute Attribute, 234 dwarf::Form Form, 235 const MCSymbol *Label) { 236 return Die.addValue(DIEValueAllocator, Attribute, Form, DIELabel(Label)); 237 } 238 239 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) { 240 addLabel(Die, (dwarf::Attribute)0, Form, Label); 241 } 242 243 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute, 244 uint64_t Integer) { 245 if (DD->getDwarfVersion() >= 4) 246 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer); 247 else 248 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer); 249 } 250 251 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) { 252 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName) 253 : getCU().getOrCreateSourceID(FileName, DirName); 254 } 255 256 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) { 257 if (!DD->useSplitDwarf()) { 258 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr); 259 addLabel(Die, dwarf::DW_FORM_udata, Sym); 260 } else { 261 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index); 262 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, 263 DD->getAddressPool().getIndex(Sym)); 264 } 265 } 266 267 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute, 268 const MCSymbol *Hi, const MCSymbol *Lo) { 269 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_data4, 270 new (DIEValueAllocator) DIEDelta(Hi, Lo)); 271 } 272 273 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) { 274 addDIEEntry(Die, Attribute, DIEEntry(Entry)); 275 } 276 277 void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) { 278 // Flag the type unit reference as a declaration so that if it contains 279 // members (implicit special members, static data member definitions, member 280 // declarations for definitions in this CU, etc) consumers don't get confused 281 // and think this is a full definition. 282 addFlag(Die, dwarf::DW_AT_declaration); 283 284 Die.addValue(DIEValueAllocator, dwarf::DW_AT_signature, 285 dwarf::DW_FORM_ref_sig8, DIEInteger(Signature)); 286 } 287 288 void DwarfUnit::addDIETypeSignature(DIE &Die, dwarf::Attribute Attribute, 289 StringRef Identifier) { 290 uint64_t Signature = DD->makeTypeSignature(Identifier); 291 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_ref_sig8, 292 DIEInteger(Signature)); 293 } 294 295 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, 296 DIEEntry Entry) { 297 const DIE *DieCU = Die.getUnitOrNull(); 298 const DIE *EntryCU = Entry.getEntry().getUnitOrNull(); 299 if (!DieCU) 300 // We assume that Die belongs to this CU, if it is not linked to any CU yet. 301 DieCU = &getUnitDie(); 302 if (!EntryCU) 303 EntryCU = &getUnitDie(); 304 Die.addValue(DIEValueAllocator, Attribute, 305 EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr, 306 Entry); 307 } 308 309 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) { 310 DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, (dwarf::Tag)Tag)); 311 if (N) 312 insertDIE(N, &Die); 313 return Die; 314 } 315 316 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) { 317 Loc->ComputeSize(Asm); 318 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on. 319 Die.addValue(DIEValueAllocator, Attribute, 320 Loc->BestForm(DD->getDwarfVersion()), Loc); 321 } 322 323 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, 324 DIEBlock *Block) { 325 Block->ComputeSize(Asm); 326 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on. 327 Die.addValue(DIEValueAllocator, Attribute, Block->BestForm(), Block); 328 } 329 330 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File, 331 StringRef Directory) { 332 if (Line == 0) 333 return; 334 335 unsigned FileID = getOrCreateSourceID(File, Directory); 336 assert(FileID && "Invalid file id"); 337 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID); 338 addUInt(Die, dwarf::DW_AT_decl_line, None, Line); 339 } 340 341 void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) { 342 assert(V); 343 344 addSourceLine(Die, V->getLine(), V->getScope()->getFilename(), 345 V->getScope()->getDirectory()); 346 } 347 348 void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) { 349 assert(G); 350 351 addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory()); 352 } 353 354 void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) { 355 assert(SP); 356 357 addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory()); 358 } 359 360 void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) { 361 assert(Ty); 362 363 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory()); 364 } 365 366 void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) { 367 assert(Ty); 368 369 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory()); 370 } 371 372 void DwarfUnit::addSourceLine(DIE &Die, const DINamespace *NS) { 373 addSourceLine(Die, NS->getLine(), NS->getFilename(), NS->getDirectory()); 374 } 375 376 bool DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg, 377 unsigned SizeInBits, unsigned OffsetInBits) { 378 DIEDwarfExpression Expr(*Asm, *this, TheDie); 379 Expr.AddMachineRegPiece(*Asm->MF->getSubtarget().getRegisterInfo(), Reg, 380 SizeInBits, OffsetInBits); 381 return true; 382 } 383 384 bool DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg, 385 int64_t Offset) { 386 DIEDwarfExpression Expr(*Asm, *this, TheDie); 387 return Expr.AddMachineRegIndirect(*Asm->MF->getSubtarget().getRegisterInfo(), 388 Reg, Offset); 389 } 390 391 /* Byref variables, in Blocks, are declared by the programmer as "SomeType 392 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and 393 gives the variable VarName either the struct, or a pointer to the struct, as 394 its type. This is necessary for various behind-the-scenes things the 395 compiler needs to do with by-reference variables in Blocks. 396 397 However, as far as the original *programmer* is concerned, the variable 398 should still have type 'SomeType', as originally declared. 399 400 The function getBlockByrefType dives into the __Block_byref_x_VarName 401 struct to find the original type of the variable, which is then assigned to 402 the variable's Debug Information Entry as its real type. So far, so good. 403 However now the debugger will expect the variable VarName to have the type 404 SomeType. So we need the location attribute for the variable to be an 405 expression that explains to the debugger how to navigate through the 406 pointers and struct to find the actual variable of type SomeType. 407 408 The following function does just that. We start by getting 409 the "normal" location for the variable. This will be the location 410 of either the struct __Block_byref_x_VarName or the pointer to the 411 struct __Block_byref_x_VarName. 412 413 The struct will look something like: 414 415 struct __Block_byref_x_VarName { 416 ... <various fields> 417 struct __Block_byref_x_VarName *forwarding; 418 ... <various other fields> 419 SomeType VarName; 420 ... <maybe more fields> 421 }; 422 423 If we are given the struct directly (as our starting point) we 424 need to tell the debugger to: 425 426 1). Add the offset of the forwarding field. 427 428 2). Follow that pointer to get the real __Block_byref_x_VarName 429 struct to use (the real one may have been copied onto the heap). 430 431 3). Add the offset for the field VarName, to find the actual variable. 432 433 If we started with a pointer to the struct, then we need to 434 dereference that pointer first, before the other steps. 435 Translating this into DWARF ops, we will need to append the following 436 to the current location description for the variable: 437 438 DW_OP_deref -- optional, if we start with a pointer 439 DW_OP_plus_uconst <forward_fld_offset> 440 DW_OP_deref 441 DW_OP_plus_uconst <varName_fld_offset> 442 443 That is what this function does. */ 444 445 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die, 446 dwarf::Attribute Attribute, 447 const MachineLocation &Location) { 448 const DIType *Ty = DV.getType(); 449 const DIType *TmpTy = Ty; 450 uint16_t Tag = Ty->getTag(); 451 bool isPointer = false; 452 453 StringRef varName = DV.getName(); 454 455 if (Tag == dwarf::DW_TAG_pointer_type) { 456 auto *DTy = cast<DIDerivedType>(Ty); 457 TmpTy = resolve(DTy->getBaseType()); 458 isPointer = true; 459 } 460 461 // Find the __forwarding field and the variable field in the __Block_byref 462 // struct. 463 DINodeArray Fields = cast<DICompositeType>(TmpTy)->getElements(); 464 const DIDerivedType *varField = nullptr; 465 const DIDerivedType *forwardingField = nullptr; 466 467 for (unsigned i = 0, N = Fields.size(); i < N; ++i) { 468 auto *DT = cast<DIDerivedType>(Fields[i]); 469 StringRef fieldName = DT->getName(); 470 if (fieldName == "__forwarding") 471 forwardingField = DT; 472 else if (fieldName == varName) 473 varField = DT; 474 } 475 476 // Get the offsets for the forwarding field and the variable field. 477 unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3; 478 unsigned varFieldOffset = varField->getOffsetInBits() >> 2; 479 480 // Decode the original location, and use that as the start of the byref 481 // variable's location. 482 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 483 484 bool validReg; 485 if (Location.isReg()) 486 validReg = addRegisterOpPiece(*Loc, Location.getReg()); 487 else 488 validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset()); 489 490 if (!validReg) 491 return; 492 493 // If we started with a pointer to the __Block_byref... struct, then 494 // the first thing we need to do is dereference the pointer (DW_OP_deref). 495 if (isPointer) 496 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 497 498 // Next add the offset for the '__forwarding' field: 499 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in 500 // adding the offset if it's 0. 501 if (forwardingFieldOffset > 0) { 502 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 503 addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset); 504 } 505 506 // Now dereference the __forwarding field to get to the real __Block_byref 507 // struct: DW_OP_deref. 508 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 509 510 // Now that we've got the real __Block_byref... struct, add the offset 511 // for the variable's field to get to the location of the actual variable: 512 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0. 513 if (varFieldOffset > 0) { 514 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 515 addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset); 516 } 517 518 // Now attach the location information to the DIE. 519 addBlock(Die, Attribute, Loc); 520 } 521 522 /// Return true if type encoding is unsigned. 523 static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) { 524 if (auto *CTy = dyn_cast<DICompositeType>(Ty)) { 525 // FIXME: Enums without a fixed underlying type have unknown signedness 526 // here, leading to incorrectly emitted constants. 527 if (CTy->getTag() == dwarf::DW_TAG_enumeration_type) 528 return false; 529 530 // (Pieces of) aggregate types that get hacked apart by SROA may be 531 // represented by a constant. Encode them as unsigned bytes. 532 return true; 533 } 534 535 if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) { 536 dwarf::Tag T = (dwarf::Tag)Ty->getTag(); 537 // Encode pointer constants as unsigned bytes. This is used at least for 538 // null pointer constant emission. 539 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed 540 // here, but accept them for now due to a bug in SROA producing bogus 541 // dbg.values. 542 if (T == dwarf::DW_TAG_pointer_type || 543 T == dwarf::DW_TAG_ptr_to_member_type || 544 T == dwarf::DW_TAG_reference_type || 545 T == dwarf::DW_TAG_rvalue_reference_type) 546 return true; 547 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type || 548 T == dwarf::DW_TAG_volatile_type || 549 T == dwarf::DW_TAG_restrict_type); 550 DITypeRef Deriv = DTy->getBaseType(); 551 assert(Deriv && "Expected valid base type"); 552 return isUnsignedDIType(DD, DD->resolve(Deriv)); 553 } 554 555 auto *BTy = cast<DIBasicType>(Ty); 556 unsigned Encoding = BTy->getEncoding(); 557 assert((Encoding == dwarf::DW_ATE_unsigned || 558 Encoding == dwarf::DW_ATE_unsigned_char || 559 Encoding == dwarf::DW_ATE_signed || 560 Encoding == dwarf::DW_ATE_signed_char || 561 Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF || 562 Encoding == dwarf::DW_ATE_boolean || 563 (Ty->getTag() == dwarf::DW_TAG_unspecified_type && 564 Ty->getName() == "decltype(nullptr)")) && 565 "Unsupported encoding"); 566 return Encoding == dwarf::DW_ATE_unsigned || 567 Encoding == dwarf::DW_ATE_unsigned_char || 568 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean || 569 Ty->getTag() == dwarf::DW_TAG_unspecified_type; 570 } 571 572 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) { 573 assert(MO.isFPImm() && "Invalid machine operand!"); 574 DIEBlock *Block = new (DIEValueAllocator) DIEBlock; 575 APFloat FPImm = MO.getFPImm()->getValueAPF(); 576 577 // Get the raw data form of the floating point. 578 const APInt FltVal = FPImm.bitcastToAPInt(); 579 const char *FltPtr = (const char *)FltVal.getRawData(); 580 581 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte. 582 bool LittleEndian = Asm->getDataLayout().isLittleEndian(); 583 int Incr = (LittleEndian ? 1 : -1); 584 int Start = (LittleEndian ? 0 : NumBytes - 1); 585 int Stop = (LittleEndian ? NumBytes : -1); 586 587 // Output the constant to DWARF one byte at a time. 588 for (; Start != Stop; Start += Incr) 589 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]); 590 591 addBlock(Die, dwarf::DW_AT_const_value, Block); 592 } 593 594 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) { 595 // Pass this down to addConstantValue as an unsigned bag of bits. 596 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true); 597 } 598 599 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, 600 const DIType *Ty) { 601 addConstantValue(Die, CI->getValue(), Ty); 602 } 603 604 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO, 605 const DIType *Ty) { 606 assert(MO.isImm() && "Invalid machine operand!"); 607 608 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm()); 609 } 610 611 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) { 612 // FIXME: This is a bit conservative/simple - it emits negative values always 613 // sign extended to 64 bits rather than minimizing the number of bytes. 614 addUInt(Die, dwarf::DW_AT_const_value, 615 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val); 616 } 617 618 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) { 619 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty)); 620 } 621 622 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) { 623 unsigned CIBitWidth = Val.getBitWidth(); 624 if (CIBitWidth <= 64) { 625 addConstantValue(Die, Unsigned, 626 Unsigned ? Val.getZExtValue() : Val.getSExtValue()); 627 return; 628 } 629 630 DIEBlock *Block = new (DIEValueAllocator) DIEBlock; 631 632 // Get the raw data form of the large APInt. 633 const uint64_t *Ptr64 = Val.getRawData(); 634 635 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte. 636 bool LittleEndian = Asm->getDataLayout().isLittleEndian(); 637 638 // Output the constant to DWARF one byte at a time. 639 for (int i = 0; i < NumBytes; i++) { 640 uint8_t c; 641 if (LittleEndian) 642 c = Ptr64[i / 8] >> (8 * (i & 7)); 643 else 644 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7)); 645 addUInt(*Block, dwarf::DW_FORM_data1, c); 646 } 647 648 addBlock(Die, dwarf::DW_AT_const_value, Block); 649 } 650 651 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) { 652 if (!LinkageName.empty()) 653 addString(Die, 654 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name 655 : dwarf::DW_AT_MIPS_linkage_name, 656 GlobalValue::getRealLinkageName(LinkageName)); 657 } 658 659 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) { 660 // Add template parameters. 661 for (const auto *Element : TParams) { 662 if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element)) 663 constructTemplateTypeParameterDIE(Buffer, TTP); 664 else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element)) 665 constructTemplateValueParameterDIE(Buffer, TVP); 666 } 667 } 668 669 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) { 670 if (!Context || isa<DIFile>(Context)) 671 return &getUnitDie(); 672 if (auto *T = dyn_cast<DIType>(Context)) 673 return getOrCreateTypeDIE(T); 674 if (auto *NS = dyn_cast<DINamespace>(Context)) 675 return getOrCreateNameSpace(NS); 676 if (auto *SP = dyn_cast<DISubprogram>(Context)) 677 return getOrCreateSubprogramDIE(SP); 678 if (auto *M = dyn_cast<DIModule>(Context)) 679 return getOrCreateModule(M); 680 return getDIE(Context); 681 } 682 683 DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) { 684 auto *Context = resolve(Ty->getScope()); 685 DIE *ContextDIE = getOrCreateContextDIE(Context); 686 687 if (DIE *TyDIE = getDIE(Ty)) 688 return TyDIE; 689 690 // Create new type. 691 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty); 692 693 constructTypeDIE(TyDIE, cast<DICompositeType>(Ty)); 694 695 if (!Ty->isExternalTypeRef()) 696 updateAcceleratorTables(Context, Ty, TyDIE); 697 return &TyDIE; 698 } 699 700 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) { 701 if (!TyNode) 702 return nullptr; 703 704 auto *Ty = cast<DIType>(TyNode); 705 706 // DW_TAG_restrict_type is not supported in DWARF2 707 if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2) 708 return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType())); 709 710 // Construct the context before querying for the existence of the DIE in case 711 // such construction creates the DIE. 712 auto *Context = resolve(Ty->getScope()); 713 DIE *ContextDIE = getOrCreateContextDIE(Context); 714 assert(ContextDIE); 715 716 if (DIE *TyDIE = getDIE(Ty)) 717 return TyDIE; 718 719 // Create new type. 720 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty); 721 722 updateAcceleratorTables(Context, Ty, TyDIE); 723 724 if (auto *BT = dyn_cast<DIBasicType>(Ty)) 725 constructTypeDIE(TyDIE, BT); 726 else if (auto *STy = dyn_cast<DISubroutineType>(Ty)) 727 constructTypeDIE(TyDIE, STy); 728 else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) { 729 if (GenerateDwarfTypeUnits && !Ty->isForwardDecl()) 730 if (MDString *TypeId = CTy->getRawIdentifier()) { 731 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy); 732 // Skip updating the accelerator tables since this is not the full type. 733 return &TyDIE; 734 } 735 constructTypeDIE(TyDIE, CTy); 736 } else { 737 constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty)); 738 } 739 740 return &TyDIE; 741 } 742 743 void DwarfUnit::updateAcceleratorTables(const DIScope *Context, 744 const DIType *Ty, const DIE &TyDIE) { 745 if (!Ty->getName().empty() && !Ty->isForwardDecl()) { 746 bool IsImplementation = false; 747 if (auto *CT = dyn_cast<DICompositeType>(Ty)) { 748 // A runtime language of 0 actually means C/C++ and that any 749 // non-negative value is some version of Objective-C/C++. 750 IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete(); 751 } 752 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0; 753 DD->addAccelType(Ty->getName(), TyDIE, Flags); 754 755 if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) || 756 isa<DINamespace>(Context)) 757 addGlobalType(Ty, TyDIE, Context); 758 } 759 } 760 761 void DwarfUnit::addType(DIE &Entity, const DIType *Ty, 762 dwarf::Attribute Attribute) { 763 assert(Ty && "Trying to add a type that doesn't exist?"); 764 addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty))); 765 } 766 767 std::string DwarfUnit::getParentContextString(const DIScope *Context) const { 768 if (!Context) 769 return ""; 770 771 // FIXME: Decide whether to implement this for non-C++ languages. 772 if (getLanguage() != dwarf::DW_LANG_C_plus_plus) 773 return ""; 774 775 std::string CS; 776 SmallVector<const DIScope *, 1> Parents; 777 while (!isa<DICompileUnit>(Context)) { 778 Parents.push_back(Context); 779 if (Context->getScope()) 780 Context = resolve(Context->getScope()); 781 else 782 // Structure, etc types will have a NULL context if they're at the top 783 // level. 784 break; 785 } 786 787 // Reverse iterate over our list to go from the outermost construct to the 788 // innermost. 789 for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) { 790 StringRef Name = Ctx->getName(); 791 if (Name.empty() && isa<DINamespace>(Ctx)) 792 Name = "(anonymous namespace)"; 793 if (!Name.empty()) { 794 CS += Name; 795 CS += "::"; 796 } 797 } 798 return CS; 799 } 800 801 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) { 802 // Get core information. 803 StringRef Name = BTy->getName(); 804 // Add name if not anonymous or intermediate type. 805 if (!Name.empty()) 806 addString(Buffer, dwarf::DW_AT_name, Name); 807 808 // An unspecified type only has a name attribute. 809 if (BTy->getTag() == dwarf::DW_TAG_unspecified_type) 810 return; 811 812 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, 813 BTy->getEncoding()); 814 815 uint64_t Size = BTy->getSizeInBits() >> 3; 816 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size); 817 } 818 819 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) { 820 // Get core information. 821 StringRef Name = DTy->getName(); 822 uint64_t Size = DTy->getSizeInBits() >> 3; 823 uint16_t Tag = Buffer.getTag(); 824 825 // Map to main type, void will not have a type. 826 const DIType *FromTy = resolve(DTy->getBaseType()); 827 if (FromTy) 828 addType(Buffer, FromTy); 829 830 // Add name if not anonymous or intermediate type. 831 if (!Name.empty()) 832 addString(Buffer, dwarf::DW_AT_name, Name); 833 834 // Add size if non-zero (derived types might be zero-sized.) 835 if (Size && Tag != dwarf::DW_TAG_pointer_type 836 && Tag != dwarf::DW_TAG_ptr_to_member_type 837 && Tag != dwarf::DW_TAG_reference_type 838 && Tag != dwarf::DW_TAG_rvalue_reference_type) 839 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size); 840 841 if (Tag == dwarf::DW_TAG_ptr_to_member_type) 842 addDIEEntry( 843 Buffer, dwarf::DW_AT_containing_type, 844 *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType()))); 845 // Add source line info if available and TyDesc is not a forward declaration. 846 if (!DTy->isForwardDecl()) 847 addSourceLine(Buffer, DTy); 848 } 849 850 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) { 851 for (unsigned i = 1, N = Args.size(); i < N; ++i) { 852 const DIType *Ty = resolve(Args[i]); 853 if (!Ty) { 854 assert(i == N-1 && "Unspecified parameter must be the last argument"); 855 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer); 856 } else { 857 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer); 858 addType(Arg, Ty); 859 if (Ty->isArtificial()) 860 addFlag(Arg, dwarf::DW_AT_artificial); 861 } 862 } 863 } 864 865 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) { 866 // Add return type. A void return won't have a type. 867 auto Elements = cast<DISubroutineType>(CTy)->getTypeArray(); 868 if (Elements.size()) 869 if (auto RTy = resolve(Elements[0])) 870 addType(Buffer, RTy); 871 872 bool isPrototyped = true; 873 if (Elements.size() == 2 && !Elements[1]) 874 isPrototyped = false; 875 876 constructSubprogramArguments(Buffer, Elements); 877 878 // Add prototype flag if we're dealing with a C language and the function has 879 // been prototyped. 880 uint16_t Language = getLanguage(); 881 if (isPrototyped && 882 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 || 883 Language == dwarf::DW_LANG_ObjC)) 884 addFlag(Buffer, dwarf::DW_AT_prototyped); 885 886 // Add a DW_AT_calling_convention if this has an explicit convention. 887 if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal) 888 addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, 889 CTy->getCC()); 890 891 if (CTy->isLValueReference()) 892 addFlag(Buffer, dwarf::DW_AT_reference); 893 894 if (CTy->isRValueReference()) 895 addFlag(Buffer, dwarf::DW_AT_rvalue_reference); 896 } 897 898 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) { 899 if (CTy->isExternalTypeRef()) { 900 StringRef Identifier = CTy->getIdentifier(); 901 assert(!Identifier.empty() && "external type ref without identifier"); 902 addFlag(Buffer, dwarf::DW_AT_declaration); 903 return addDIETypeSignature(Buffer, dwarf::DW_AT_signature, Identifier); 904 } 905 906 // Add name if not anonymous or intermediate type. 907 StringRef Name = CTy->getName(); 908 909 uint64_t Size = CTy->getSizeInBits() >> 3; 910 uint16_t Tag = Buffer.getTag(); 911 912 switch (Tag) { 913 case dwarf::DW_TAG_array_type: 914 constructArrayTypeDIE(Buffer, CTy); 915 break; 916 case dwarf::DW_TAG_enumeration_type: 917 constructEnumTypeDIE(Buffer, CTy); 918 break; 919 case dwarf::DW_TAG_structure_type: 920 case dwarf::DW_TAG_union_type: 921 case dwarf::DW_TAG_class_type: { 922 // Add elements to structure type. 923 DINodeArray Elements = CTy->getElements(); 924 for (const auto *Element : Elements) { 925 if (!Element) 926 continue; 927 if (auto *SP = dyn_cast<DISubprogram>(Element)) 928 getOrCreateSubprogramDIE(SP); 929 else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) { 930 if (DDTy->getTag() == dwarf::DW_TAG_friend) { 931 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer); 932 addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend); 933 } else if (DDTy->isStaticMember()) { 934 getOrCreateStaticMemberDIE(DDTy); 935 } else { 936 constructMemberDIE(Buffer, DDTy); 937 } 938 } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) { 939 DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer); 940 StringRef PropertyName = Property->getName(); 941 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName); 942 if (Property->getType()) 943 addType(ElemDie, resolve(Property->getType())); 944 addSourceLine(ElemDie, Property); 945 StringRef GetterName = Property->getGetterName(); 946 if (!GetterName.empty()) 947 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName); 948 StringRef SetterName = Property->getSetterName(); 949 if (!SetterName.empty()) 950 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName); 951 if (unsigned PropertyAttributes = Property->getAttributes()) 952 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None, 953 PropertyAttributes); 954 } 955 } 956 957 if (CTy->isAppleBlockExtension()) 958 addFlag(Buffer, dwarf::DW_AT_APPLE_block); 959 960 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type 961 // inside C++ composite types to point to the base class with the vtable. 962 if (auto *ContainingType = 963 dyn_cast_or_null<DICompositeType>(resolve(CTy->getVTableHolder()))) 964 addDIEEntry(Buffer, dwarf::DW_AT_containing_type, 965 *getOrCreateTypeDIE(ContainingType)); 966 967 if (CTy->isObjcClassComplete()) 968 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type); 969 970 // Add template parameters to a class, structure or union types. 971 // FIXME: The support isn't in the metadata for this yet. 972 if (Tag == dwarf::DW_TAG_class_type || 973 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) 974 addTemplateParams(Buffer, CTy->getTemplateParams()); 975 976 break; 977 } 978 default: 979 break; 980 } 981 982 // Add name if not anonymous or intermediate type. 983 if (!Name.empty()) 984 addString(Buffer, dwarf::DW_AT_name, Name); 985 986 if (Tag == dwarf::DW_TAG_enumeration_type || 987 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type || 988 Tag == dwarf::DW_TAG_union_type) { 989 // Add size if non-zero (derived types might be zero-sized.) 990 // TODO: Do we care about size for enum forward declarations? 991 if (Size) 992 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size); 993 else if (!CTy->isForwardDecl()) 994 // Add zero size if it is not a forward declaration. 995 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0); 996 997 // If we're a forward decl, say so. 998 if (CTy->isForwardDecl()) 999 addFlag(Buffer, dwarf::DW_AT_declaration); 1000 1001 // Add source line info if available. 1002 if (!CTy->isForwardDecl()) 1003 addSourceLine(Buffer, CTy); 1004 1005 // No harm in adding the runtime language to the declaration. 1006 unsigned RLang = CTy->getRuntimeLang(); 1007 if (RLang) 1008 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1, 1009 RLang); 1010 } 1011 } 1012 1013 void DwarfUnit::constructTemplateTypeParameterDIE( 1014 DIE &Buffer, const DITemplateTypeParameter *TP) { 1015 DIE &ParamDIE = 1016 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer); 1017 // Add the type if it exists, it could be void and therefore no type. 1018 if (TP->getType()) 1019 addType(ParamDIE, resolve(TP->getType())); 1020 if (!TP->getName().empty()) 1021 addString(ParamDIE, dwarf::DW_AT_name, TP->getName()); 1022 } 1023 1024 void DwarfUnit::constructTemplateValueParameterDIE( 1025 DIE &Buffer, const DITemplateValueParameter *VP) { 1026 DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer); 1027 1028 // Add the type if there is one, template template and template parameter 1029 // packs will not have a type. 1030 if (VP->getTag() == dwarf::DW_TAG_template_value_parameter) 1031 addType(ParamDIE, resolve(VP->getType())); 1032 if (!VP->getName().empty()) 1033 addString(ParamDIE, dwarf::DW_AT_name, VP->getName()); 1034 if (Metadata *Val = VP->getValue()) { 1035 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val)) 1036 addConstantValue(ParamDIE, CI, resolve(VP->getType())); 1037 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) { 1038 // We cannot describe the location of dllimport'd entities: the 1039 // computation of their address requires loads from the IAT. 1040 if (!GV->hasDLLImportStorageClass()) { 1041 // For declaration non-type template parameters (such as global values 1042 // and functions) 1043 DIELoc *Loc = new (DIEValueAllocator) DIELoc; 1044 addOpAddress(*Loc, Asm->getSymbol(GV)); 1045 // Emit DW_OP_stack_value to use the address as the immediate value of 1046 // the parameter, rather than a pointer to it. 1047 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value); 1048 addBlock(ParamDIE, dwarf::DW_AT_location, Loc); 1049 } 1050 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) { 1051 assert(isa<MDString>(Val)); 1052 addString(ParamDIE, dwarf::DW_AT_GNU_template_name, 1053 cast<MDString>(Val)->getString()); 1054 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) { 1055 addTemplateParams(ParamDIE, cast<MDTuple>(Val)); 1056 } 1057 } 1058 } 1059 1060 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) { 1061 // Construct the context before querying for the existence of the DIE in case 1062 // such construction creates the DIE. 1063 DIE *ContextDIE = getOrCreateContextDIE(NS->getScope()); 1064 1065 if (DIE *NDie = getDIE(NS)) 1066 return NDie; 1067 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS); 1068 1069 StringRef Name = NS->getName(); 1070 if (!Name.empty()) 1071 addString(NDie, dwarf::DW_AT_name, NS->getName()); 1072 else 1073 Name = "(anonymous namespace)"; 1074 DD->addAccelNamespace(Name, NDie); 1075 addGlobalName(Name, NDie, NS->getScope()); 1076 addSourceLine(NDie, NS); 1077 return &NDie; 1078 } 1079 1080 DIE *DwarfUnit::getOrCreateModule(const DIModule *M) { 1081 // Construct the context before querying for the existence of the DIE in case 1082 // such construction creates the DIE. 1083 DIE *ContextDIE = getOrCreateContextDIE(M->getScope()); 1084 1085 if (DIE *MDie = getDIE(M)) 1086 return MDie; 1087 DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M); 1088 1089 if (!M->getName().empty()) { 1090 addString(MDie, dwarf::DW_AT_name, M->getName()); 1091 addGlobalName(M->getName(), MDie, M->getScope()); 1092 } 1093 if (!M->getConfigurationMacros().empty()) 1094 addString(MDie, dwarf::DW_AT_LLVM_config_macros, 1095 M->getConfigurationMacros()); 1096 if (!M->getIncludePath().empty()) 1097 addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath()); 1098 if (!M->getISysRoot().empty()) 1099 addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot()); 1100 1101 return &MDie; 1102 } 1103 1104 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) { 1105 // Construct the context before querying for the existence of the DIE in case 1106 // such construction creates the DIE (as is the case for member function 1107 // declarations). 1108 DIE *ContextDIE = 1109 Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope())); 1110 1111 if (DIE *SPDie = getDIE(SP)) 1112 return SPDie; 1113 1114 if (auto *SPDecl = SP->getDeclaration()) { 1115 if (!Minimal) { 1116 // Add subprogram definitions to the CU die directly. 1117 ContextDIE = &getUnitDie(); 1118 // Build the decl now to ensure it precedes the definition. 1119 getOrCreateSubprogramDIE(SPDecl); 1120 } 1121 } 1122 1123 // DW_TAG_inlined_subroutine may refer to this DIE. 1124 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP); 1125 1126 // Stop here and fill this in later, depending on whether or not this 1127 // subprogram turns out to have inlined instances or not. 1128 if (SP->isDefinition()) 1129 return &SPDie; 1130 1131 applySubprogramAttributes(SP, SPDie); 1132 return &SPDie; 1133 } 1134 1135 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP, 1136 DIE &SPDie) { 1137 DIE *DeclDie = nullptr; 1138 StringRef DeclLinkageName; 1139 if (auto *SPDecl = SP->getDeclaration()) { 1140 DeclDie = getDIE(SPDecl); 1141 assert(DeclDie && "This DIE should've already been constructed when the " 1142 "definition DIE was created in " 1143 "getOrCreateSubprogramDIE"); 1144 DeclLinkageName = SPDecl->getLinkageName(); 1145 unsigned DeclID = 1146 getOrCreateSourceID(SPDecl->getFilename(), SPDecl->getDirectory()); 1147 unsigned DefID = getOrCreateSourceID(SP->getFilename(), SP->getDirectory()); 1148 if (DeclID != DefID) 1149 addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID); 1150 1151 if (SP->getLine() != SPDecl->getLine()) 1152 addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine()); 1153 } 1154 1155 // Add function template parameters. 1156 addTemplateParams(SPDie, SP->getTemplateParams()); 1157 1158 // Add the linkage name if we have one and it isn't in the Decl. 1159 StringRef LinkageName = SP->getLinkageName(); 1160 assert(((LinkageName.empty() || DeclLinkageName.empty()) || 1161 LinkageName == DeclLinkageName) && 1162 "decl has a linkage name and it is different"); 1163 if (DeclLinkageName.empty() && 1164 // Always emit it for abstract subprograms. 1165 (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP))) 1166 addLinkageName(SPDie, LinkageName); 1167 1168 if (!DeclDie) 1169 return false; 1170 1171 // Refer to the function declaration where all the other attributes will be 1172 // found. 1173 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie); 1174 return true; 1175 } 1176 1177 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie, 1178 bool Minimal) { 1179 if (!Minimal) 1180 if (applySubprogramDefinitionAttributes(SP, SPDie)) 1181 return; 1182 1183 // Constructors and operators for anonymous aggregates do not have names. 1184 if (!SP->getName().empty()) 1185 addString(SPDie, dwarf::DW_AT_name, SP->getName()); 1186 1187 // Skip the rest of the attributes under -gmlt to save space. 1188 if (Minimal) 1189 return; 1190 1191 addSourceLine(SPDie, SP); 1192 1193 // Add the prototype if we have a prototype and we have a C like 1194 // language. 1195 uint16_t Language = getLanguage(); 1196 if (SP->isPrototyped() && 1197 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 || 1198 Language == dwarf::DW_LANG_ObjC)) 1199 addFlag(SPDie, dwarf::DW_AT_prototyped); 1200 1201 unsigned CC = 0; 1202 DITypeRefArray Args; 1203 if (const DISubroutineType *SPTy = SP->getType()) { 1204 Args = SPTy->getTypeArray(); 1205 CC = SPTy->getCC(); 1206 } 1207 1208 // Add a DW_AT_calling_convention if this has an explicit convention. 1209 if (CC && CC != dwarf::DW_CC_normal) 1210 addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC); 1211 1212 // Add a return type. If this is a type like a C/C++ void type we don't add a 1213 // return type. 1214 if (Args.size()) 1215 if (auto Ty = resolve(Args[0])) 1216 addType(SPDie, Ty); 1217 1218 unsigned VK = SP->getVirtuality(); 1219 if (VK) { 1220 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK); 1221 if (SP->getVirtualIndex() != -1u) { 1222 DIELoc *Block = getDIELoc(); 1223 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 1224 addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex()); 1225 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block); 1226 } 1227 ContainingTypeMap.insert( 1228 std::make_pair(&SPDie, resolve(SP->getContainingType()))); 1229 } 1230 1231 if (!SP->isDefinition()) { 1232 addFlag(SPDie, dwarf::DW_AT_declaration); 1233 1234 // Add arguments. Do not add arguments for subprogram definition. They will 1235 // be handled while processing variables. 1236 constructSubprogramArguments(SPDie, Args); 1237 } 1238 1239 if (SP->isArtificial()) 1240 addFlag(SPDie, dwarf::DW_AT_artificial); 1241 1242 if (!SP->isLocalToUnit()) 1243 addFlag(SPDie, dwarf::DW_AT_external); 1244 1245 if (DD->useAppleExtensionAttributes()) { 1246 if (SP->isOptimized()) 1247 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized); 1248 1249 if (unsigned isa = Asm->getISAEncoding()) 1250 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa); 1251 } 1252 1253 if (SP->isLValueReference()) 1254 addFlag(SPDie, dwarf::DW_AT_reference); 1255 1256 if (SP->isRValueReference()) 1257 addFlag(SPDie, dwarf::DW_AT_rvalue_reference); 1258 1259 if (SP->isNoReturn()) 1260 addFlag(SPDie, dwarf::DW_AT_noreturn); 1261 1262 if (SP->isProtected()) 1263 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1264 dwarf::DW_ACCESS_protected); 1265 else if (SP->isPrivate()) 1266 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1267 dwarf::DW_ACCESS_private); 1268 else if (SP->isPublic()) 1269 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1270 dwarf::DW_ACCESS_public); 1271 1272 if (SP->isExplicit()) 1273 addFlag(SPDie, dwarf::DW_AT_explicit); 1274 } 1275 1276 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR, 1277 DIE *IndexTy) { 1278 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer); 1279 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy); 1280 1281 // The LowerBound value defines the lower bounds which is typically zero for 1282 // C/C++. The Count value is the number of elements. Values are 64 bit. If 1283 // Count == -1 then the array is unbounded and we do not emit 1284 // DW_AT_lower_bound and DW_AT_count attributes. 1285 int64_t LowerBound = SR->getLowerBound(); 1286 int64_t DefaultLowerBound = getDefaultLowerBound(); 1287 int64_t Count = SR->getCount(); 1288 1289 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound) 1290 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound); 1291 1292 if (Count != -1) 1293 // FIXME: An unbounded array should reference the expression that defines 1294 // the array. 1295 addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count); 1296 } 1297 1298 DIE *DwarfUnit::getIndexTyDie() { 1299 if (IndexTyDie) 1300 return IndexTyDie; 1301 // Construct an integer type to use for indexes. 1302 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie); 1303 addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype"); 1304 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t)); 1305 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, 1306 dwarf::DW_ATE_unsigned); 1307 return IndexTyDie; 1308 } 1309 1310 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) { 1311 if (CTy->isVector()) 1312 addFlag(Buffer, dwarf::DW_AT_GNU_vector); 1313 1314 // Emit the element type. 1315 addType(Buffer, resolve(CTy->getBaseType())); 1316 1317 // Get an anonymous type for index type. 1318 // FIXME: This type should be passed down from the front end 1319 // as different languages may have different sizes for indexes. 1320 DIE *IdxTy = getIndexTyDie(); 1321 1322 // Add subranges to array type. 1323 DINodeArray Elements = CTy->getElements(); 1324 for (unsigned i = 0, N = Elements.size(); i < N; ++i) { 1325 // FIXME: Should this really be such a loose cast? 1326 if (auto *Element = dyn_cast_or_null<DINode>(Elements[i])) 1327 if (Element->getTag() == dwarf::DW_TAG_subrange_type) 1328 constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy); 1329 } 1330 } 1331 1332 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) { 1333 DINodeArray Elements = CTy->getElements(); 1334 1335 // Add enumerators to enumeration type. 1336 for (unsigned i = 0, N = Elements.size(); i < N; ++i) { 1337 auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]); 1338 if (Enum) { 1339 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer); 1340 StringRef Name = Enum->getName(); 1341 addString(Enumerator, dwarf::DW_AT_name, Name); 1342 int64_t Value = Enum->getValue(); 1343 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, 1344 Value); 1345 } 1346 } 1347 const DIType *DTy = resolve(CTy->getBaseType()); 1348 if (DTy) { 1349 addType(Buffer, DTy); 1350 addFlag(Buffer, dwarf::DW_AT_enum_class); 1351 } 1352 } 1353 1354 void DwarfUnit::constructContainingTypeDIEs() { 1355 for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end(); 1356 CI != CE; ++CI) { 1357 DIE &SPDie = *CI->first; 1358 const DINode *D = CI->second; 1359 if (!D) 1360 continue; 1361 DIE *NDie = getDIE(D); 1362 if (!NDie) 1363 continue; 1364 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie); 1365 } 1366 } 1367 1368 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) { 1369 DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer); 1370 StringRef Name = DT->getName(); 1371 if (!Name.empty()) 1372 addString(MemberDie, dwarf::DW_AT_name, Name); 1373 1374 addType(MemberDie, resolve(DT->getBaseType())); 1375 1376 addSourceLine(MemberDie, DT); 1377 1378 if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) { 1379 1380 // For C++, virtual base classes are not at fixed offset. Use following 1381 // expression to extract appropriate offset from vtable. 1382 // BaseAddr = ObAddr + *((*ObAddr) - Offset) 1383 1384 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc; 1385 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup); 1386 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 1387 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 1388 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits()); 1389 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus); 1390 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 1391 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus); 1392 1393 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie); 1394 } else { 1395 uint64_t Size = DT->getSizeInBits(); 1396 uint64_t FieldSize = DD->getBaseTypeSize(DT); 1397 uint64_t OffsetInBytes; 1398 1399 bool IsBitfield = FieldSize && Size != FieldSize; 1400 if (IsBitfield) { 1401 // Handle bitfield, assume bytes are 8 bits. 1402 if (DD->useDWARF2Bitfields()) 1403 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8); 1404 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size); 1405 1406 uint64_t Offset = DT->getOffsetInBits(); 1407 uint64_t Align = DT->getAlignInBits() ? DT->getAlignInBits() : FieldSize; 1408 uint64_t AlignMask = ~(Align - 1); 1409 // The bits from the start of the storage unit to the start of the field. 1410 uint64_t StartBitOffset = Offset - (Offset & AlignMask); 1411 // The byte offset of the field's aligned storage unit inside the struct. 1412 OffsetInBytes = (Offset - StartBitOffset) / 8; 1413 1414 if (DD->useDWARF2Bitfields()) { 1415 uint64_t HiMark = (Offset + FieldSize) & AlignMask; 1416 uint64_t FieldOffset = (HiMark - FieldSize); 1417 Offset -= FieldOffset; 1418 1419 // Maybe we need to work from the other end. 1420 if (Asm->getDataLayout().isLittleEndian()) 1421 Offset = FieldSize - (Offset + Size); 1422 1423 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset); 1424 OffsetInBytes = FieldOffset >> 3; 1425 } else { 1426 addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset); 1427 } 1428 } else { 1429 // This is not a bitfield. 1430 OffsetInBytes = DT->getOffsetInBits() / 8; 1431 } 1432 1433 if (DD->getDwarfVersion() <= 2) { 1434 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc; 1435 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 1436 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes); 1437 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie); 1438 } else if (!IsBitfield || DD->useDWARF2Bitfields()) 1439 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None, 1440 OffsetInBytes); 1441 } 1442 1443 if (DT->isProtected()) 1444 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1445 dwarf::DW_ACCESS_protected); 1446 else if (DT->isPrivate()) 1447 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1448 dwarf::DW_ACCESS_private); 1449 // Otherwise C++ member and base classes are considered public. 1450 else if (DT->isPublic()) 1451 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1452 dwarf::DW_ACCESS_public); 1453 if (DT->isVirtual()) 1454 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, 1455 dwarf::DW_VIRTUALITY_virtual); 1456 1457 // Objective-C properties. 1458 if (DINode *PNode = DT->getObjCProperty()) 1459 if (DIE *PDie = getDIE(PNode)) 1460 MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property, 1461 dwarf::DW_FORM_ref4, DIEEntry(*PDie)); 1462 1463 if (DT->isArtificial()) 1464 addFlag(MemberDie, dwarf::DW_AT_artificial); 1465 } 1466 1467 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) { 1468 if (!DT) 1469 return nullptr; 1470 1471 // Construct the context before querying for the existence of the DIE in case 1472 // such construction creates the DIE. 1473 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope())); 1474 assert(dwarf::isType(ContextDIE->getTag()) && 1475 "Static member should belong to a type."); 1476 1477 if (DIE *StaticMemberDIE = getDIE(DT)) 1478 return StaticMemberDIE; 1479 1480 DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT); 1481 1482 const DIType *Ty = resolve(DT->getBaseType()); 1483 1484 addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName()); 1485 addType(StaticMemberDIE, Ty); 1486 addSourceLine(StaticMemberDIE, DT); 1487 addFlag(StaticMemberDIE, dwarf::DW_AT_external); 1488 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration); 1489 1490 // FIXME: We could omit private if the parent is a class_type, and 1491 // public if the parent is something else. 1492 if (DT->isProtected()) 1493 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1494 dwarf::DW_ACCESS_protected); 1495 else if (DT->isPrivate()) 1496 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1497 dwarf::DW_ACCESS_private); 1498 else if (DT->isPublic()) 1499 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1500 dwarf::DW_ACCESS_public); 1501 1502 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant())) 1503 addConstantValue(StaticMemberDIE, CI, Ty); 1504 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant())) 1505 addConstantFPValue(StaticMemberDIE, CFP); 1506 1507 return &StaticMemberDIE; 1508 } 1509 1510 void DwarfUnit::emitHeader(bool UseOffsets) { 1511 // Emit size of content not including length itself 1512 Asm->OutStreamer->AddComment("Length of Unit"); 1513 Asm->EmitInt32(getHeaderSize() + UnitDie.getSize()); 1514 1515 Asm->OutStreamer->AddComment("DWARF version number"); 1516 Asm->EmitInt16(DD->getDwarfVersion()); 1517 Asm->OutStreamer->AddComment("Offset Into Abbrev. Section"); 1518 1519 // We share one abbreviations table across all units so it's always at the 1520 // start of the section. Use a relocatable offset where needed to ensure 1521 // linking doesn't invalidate that offset. 1522 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 1523 if (UseOffsets) 1524 Asm->EmitInt32(0); 1525 else 1526 Asm->emitDwarfSymbolReference( 1527 TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false); 1528 1529 Asm->OutStreamer->AddComment("Address Size (in bytes)"); 1530 Asm->EmitInt8(Asm->getDataLayout().getPointerSize()); 1531 } 1532 1533 void DwarfUnit::initSection(MCSection *Section) { 1534 assert(!this->Section); 1535 this->Section = Section; 1536 } 1537 1538 void DwarfTypeUnit::emitHeader(bool UseOffsets) { 1539 DwarfUnit::emitHeader(UseOffsets); 1540 Asm->OutStreamer->AddComment("Type Signature"); 1541 Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature)); 1542 Asm->OutStreamer->AddComment("Type DIE Offset"); 1543 // In a skeleton type unit there is no type DIE so emit a zero offset. 1544 Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0, 1545 sizeof(Ty->getOffset())); 1546 } 1547 1548 bool DwarfTypeUnit::isDwoUnit() const { 1549 // Since there are no skeleton type units, all type units are dwo type units 1550 // when split DWARF is being used. 1551 return DD->useSplitDwarf(); 1552 } 1553