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 #define DEBUG_TYPE "dwarfdebug" 15 16 #include "DwarfUnit.h" 17 #include "DwarfAccelTable.h" 18 #include "DwarfDebug.h" 19 #include "llvm/ADT/APFloat.h" 20 #include "llvm/DIBuilder.h" 21 #include "llvm/IR/Constants.h" 22 #include "llvm/IR/DataLayout.h" 23 #include "llvm/IR/GlobalVariable.h" 24 #include "llvm/IR/Instructions.h" 25 #include "llvm/MC/MCSection.h" 26 #include "llvm/MC/MCStreamer.h" 27 #include "llvm/Target/Mangler.h" 28 #include "llvm/Target/TargetFrameLowering.h" 29 #include "llvm/Target/TargetMachine.h" 30 #include "llvm/Target/TargetLoweringObjectFile.h" 31 #include "llvm/Target/TargetRegisterInfo.h" 32 #include "llvm/Support/CommandLine.h" 33 34 using namespace llvm; 35 36 static cl::opt<bool> 37 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden, 38 cl::desc("Generate DWARF4 type units."), 39 cl::init(false)); 40 41 /// Unit - Unit constructor. 42 DwarfUnit::DwarfUnit(unsigned UID, DIE *D, DICompileUnit Node, AsmPrinter *A, 43 DwarfDebug *DW, DwarfFile *DWU) 44 : UniqueID(UID), Node(Node), UnitDie(D), DebugInfoOffset(0), Asm(A), DD(DW), 45 DU(DWU), IndexTyDie(0), Section(0) { 46 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1); 47 } 48 49 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DIE *D, DICompileUnit Node, 50 AsmPrinter *A, DwarfDebug *DW, 51 DwarfFile *DWU) 52 : DwarfUnit(UID, D, Node, A, DW, DWU) { 53 insertDIE(Node, D); 54 } 55 56 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DIE *D, uint16_t Language, 57 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU) 58 : DwarfUnit(UID, D, DICompileUnit(), A, DW, DWU), Language(Language) {} 59 60 /// ~Unit - Destructor for compile unit. 61 DwarfUnit::~DwarfUnit() { 62 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j) 63 DIEBlocks[j]->~DIEBlock(); 64 } 65 66 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug 67 /// information entry. 68 DIEEntry *DwarfUnit::createDIEEntry(DIE *Entry) { 69 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry); 70 return Value; 71 } 72 73 /// getDefaultLowerBound - Return the default lower bound for an array. If the 74 /// DWARF version doesn't handle the language, return -1. 75 int64_t DwarfUnit::getDefaultLowerBound() const { 76 switch (getLanguage()) { 77 default: 78 break; 79 80 case dwarf::DW_LANG_C89: 81 case dwarf::DW_LANG_C99: 82 case dwarf::DW_LANG_C: 83 case dwarf::DW_LANG_C_plus_plus: 84 case dwarf::DW_LANG_ObjC: 85 case dwarf::DW_LANG_ObjC_plus_plus: 86 return 0; 87 88 case dwarf::DW_LANG_Fortran77: 89 case dwarf::DW_LANG_Fortran90: 90 case dwarf::DW_LANG_Fortran95: 91 return 1; 92 93 // The languages below have valid values only if the DWARF version >= 4. 94 case dwarf::DW_LANG_Java: 95 case dwarf::DW_LANG_Python: 96 case dwarf::DW_LANG_UPC: 97 case dwarf::DW_LANG_D: 98 if (dwarf::DWARF_VERSION >= 4) 99 return 0; 100 break; 101 102 case dwarf::DW_LANG_Ada83: 103 case dwarf::DW_LANG_Ada95: 104 case dwarf::DW_LANG_Cobol74: 105 case dwarf::DW_LANG_Cobol85: 106 case dwarf::DW_LANG_Modula2: 107 case dwarf::DW_LANG_Pascal83: 108 case dwarf::DW_LANG_PLI: 109 if (dwarf::DWARF_VERSION >= 4) 110 return 1; 111 break; 112 } 113 114 return -1; 115 } 116 117 /// Check whether the DIE for this MDNode can be shared across CUs. 118 static bool isShareableAcrossCUs(DIDescriptor D) { 119 // When the MDNode can be part of the type system, the DIE can be shared 120 // across CUs. 121 // Combining type units and cross-CU DIE sharing is lower value (since 122 // cross-CU DIE sharing is used in LTO and removes type redundancy at that 123 // level already) but may be implementable for some value in projects 124 // building multiple independent libraries with LTO and then linking those 125 // together. 126 return (D.isType() || 127 (D.isSubprogram() && !DISubprogram(D).isDefinition())) && 128 !GenerateDwarfTypeUnits; 129 } 130 131 /// getDIE - Returns the debug information entry map slot for the 132 /// specified debug variable. We delegate the request to DwarfDebug 133 /// when the DIE for this MDNode can be shared across CUs. The mappings 134 /// will be kept in DwarfDebug for shareable DIEs. 135 DIE *DwarfUnit::getDIE(DIDescriptor D) const { 136 if (isShareableAcrossCUs(D)) 137 return DD->getDIE(D); 138 return MDNodeToDieMap.lookup(D); 139 } 140 141 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug 142 /// when the DIE for this MDNode can be shared across CUs. The mappings 143 /// will be kept in DwarfDebug for shareable DIEs. 144 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) { 145 if (isShareableAcrossCUs(Desc)) { 146 DD->insertDIE(Desc, D); 147 return; 148 } 149 MDNodeToDieMap.insert(std::make_pair(Desc, D)); 150 } 151 152 /// addFlag - Add a flag that is true. 153 void DwarfUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) { 154 if (DD->getDwarfVersion() >= 4) 155 Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne); 156 else 157 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne); 158 } 159 160 /// addUInt - Add an unsigned integer attribute data and value. 161 /// 162 void DwarfUnit::addUInt(DIE *Die, dwarf::Attribute Attribute, 163 Optional<dwarf::Form> Form, uint64_t Integer) { 164 if (!Form) 165 Form = DIEInteger::BestForm(false, Integer); 166 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator) 167 DIEInteger(Integer); 168 Die->addValue(Attribute, *Form, Value); 169 } 170 171 void DwarfUnit::addUInt(DIEBlock *Block, dwarf::Form Form, uint64_t Integer) { 172 addUInt(Block, (dwarf::Attribute)0, Form, Integer); 173 } 174 175 /// addSInt - Add an signed integer attribute data and value. 176 /// 177 void DwarfUnit::addSInt(DIE *Die, dwarf::Attribute Attribute, 178 Optional<dwarf::Form> Form, int64_t Integer) { 179 if (!Form) 180 Form = DIEInteger::BestForm(true, Integer); 181 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer); 182 Die->addValue(Attribute, *Form, Value); 183 } 184 185 void DwarfUnit::addSInt(DIEBlock *Die, Optional<dwarf::Form> Form, 186 int64_t Integer) { 187 addSInt(Die, (dwarf::Attribute)0, Form, Integer); 188 } 189 190 /// addString - Add a string attribute data and value. We always emit a 191 /// reference to the string pool instead of immediate strings so that DIEs have 192 /// more predictable sizes. In the case of split dwarf we emit an index 193 /// into another table which gets us the static offset into the string 194 /// table. 195 void DwarfUnit::addString(DIE *Die, dwarf::Attribute Attribute, 196 StringRef String) { 197 DIEValue *Value; 198 dwarf::Form Form; 199 if (!DD->useSplitDwarf()) { 200 MCSymbol *Symb = DU->getStringPoolEntry(String); 201 if (Asm->needsRelocationsForDwarfStringPool()) 202 Value = new (DIEValueAllocator) DIELabel(Symb); 203 else { 204 MCSymbol *StringPool = DU->getStringPoolSym(); 205 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool); 206 } 207 Form = dwarf::DW_FORM_strp; 208 } else { 209 unsigned idx = DU->getStringPoolIndex(String); 210 Value = new (DIEValueAllocator) DIEInteger(idx); 211 Form = dwarf::DW_FORM_GNU_str_index; 212 } 213 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String); 214 Die->addValue(Attribute, Form, Str); 215 } 216 217 /// addLocalString - Add a string attribute data and value. This is guaranteed 218 /// to be in the local string pool instead of indirected. 219 void DwarfUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute, 220 StringRef String) { 221 MCSymbol *Symb = DU->getStringPoolEntry(String); 222 DIEValue *Value; 223 if (Asm->needsRelocationsForDwarfStringPool()) 224 Value = new (DIEValueAllocator) DIELabel(Symb); 225 else { 226 MCSymbol *StringPool = DU->getStringPoolSym(); 227 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool); 228 } 229 Die->addValue(Attribute, dwarf::DW_FORM_strp, Value); 230 } 231 232 /// addExpr - Add a Dwarf expression attribute data and value. 233 /// 234 void DwarfUnit::addExpr(DIEBlock *Die, dwarf::Form Form, const MCExpr *Expr) { 235 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr); 236 Die->addValue((dwarf::Attribute)0, Form, Value); 237 } 238 239 /// addLabel - Add a Dwarf label attribute data and value. 240 /// 241 void DwarfUnit::addLabel(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form, 242 const MCSymbol *Label) { 243 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label); 244 Die->addValue(Attribute, Form, Value); 245 } 246 247 void DwarfUnit::addLabel(DIEBlock *Die, dwarf::Form Form, 248 const MCSymbol *Label) { 249 addLabel(Die, (dwarf::Attribute)0, Form, Label); 250 } 251 252 /// addSectionLabel - Add a Dwarf section label attribute data and value. 253 /// 254 void DwarfUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute, 255 const MCSymbol *Label) { 256 if (DD->getDwarfVersion() >= 4) 257 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label); 258 else 259 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label); 260 } 261 262 /// addSectionOffset - Add an offset into a section attribute data and value. 263 /// 264 void DwarfUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute, 265 uint64_t Integer) { 266 if (DD->getDwarfVersion() >= 4) 267 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer); 268 else 269 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer); 270 } 271 272 /// addLabelAddress - Add a dwarf label attribute data and value using 273 /// DW_FORM_addr or DW_FORM_GNU_addr_index. 274 /// 275 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute, 276 MCSymbol *Label) { 277 if (Label) 278 DD->addArangeLabel(SymbolCU(this, Label)); 279 280 if (!DD->useSplitDwarf()) { 281 if (Label != NULL) { 282 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label); 283 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value); 284 } else { 285 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0); 286 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value); 287 } 288 } else { 289 unsigned idx = DU->getAddrPoolIndex(Label); 290 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx); 291 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value); 292 } 293 } 294 295 /// addOpAddress - Add a dwarf op address data and value using the 296 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index. 297 /// 298 void DwarfUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) { 299 if (!DD->useSplitDwarf()) { 300 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr); 301 addLabel(Die, dwarf::DW_FORM_udata, Sym); 302 } else { 303 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index); 304 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym)); 305 } 306 } 307 308 /// addSectionDelta - Add a section label delta attribute data and value. 309 /// 310 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute, 311 const MCSymbol *Hi, const MCSymbol *Lo) { 312 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo); 313 if (DD->getDwarfVersion() >= 4) 314 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value); 315 else 316 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value); 317 } 318 319 /// addDIEEntry - Add a DIE attribute data and value. 320 /// 321 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) { 322 addDIEEntry(Die, Attribute, createDIEEntry(Entry)); 323 } 324 325 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) { 326 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8, 327 new (DIEValueAllocator) DIETypeSignature(Type)); 328 } 329 330 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, 331 DIEEntry *Entry) { 332 const DIE *DieCU = Die->getUnitOrNull(); 333 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull(); 334 if (!DieCU) 335 // We assume that Die belongs to this CU, if it is not linked to any CU yet. 336 DieCU = getUnitDie(); 337 if (!EntryCU) 338 EntryCU = getUnitDie(); 339 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4 340 : dwarf::DW_FORM_ref_addr, 341 Entry); 342 } 343 344 /// Create a DIE with the given Tag, add the DIE to its parent, and 345 /// call insertDIE if MD is not null. 346 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) { 347 DIE *Die = new DIE(Tag); 348 Parent.addChild(Die); 349 if (N) 350 insertDIE(N, Die); 351 return Die; 352 } 353 354 /// addBlock - Add block data. 355 /// 356 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute, 357 DIEBlock *Block) { 358 Block->ComputeSize(Asm); 359 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on. 360 Die->addValue(Attribute, Block->BestForm(), Block); 361 } 362 363 /// addSourceLine - Add location information to specified debug information 364 /// entry. 365 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) { 366 // Verify variable. 367 if (!V.isVariable()) 368 return; 369 370 unsigned Line = V.getLineNumber(); 371 if (Line == 0) 372 return; 373 unsigned FileID = 374 DD->getOrCreateSourceID(V.getContext().getFilename(), 375 V.getContext().getDirectory(), getUniqueID()); 376 assert(FileID && "Invalid file id"); 377 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID); 378 addUInt(Die, dwarf::DW_AT_decl_line, None, Line); 379 } 380 381 /// addSourceLine - Add location information to specified debug information 382 /// entry. 383 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) { 384 // Verify global variable. 385 if (!G.isGlobalVariable()) 386 return; 387 388 unsigned Line = G.getLineNumber(); 389 if (Line == 0) 390 return; 391 unsigned FileID = 392 DD->getOrCreateSourceID(G.getFilename(), G.getDirectory(), getUniqueID()); 393 assert(FileID && "Invalid file id"); 394 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID); 395 addUInt(Die, dwarf::DW_AT_decl_line, None, Line); 396 } 397 398 /// addSourceLine - Add location information to specified debug information 399 /// entry. 400 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) { 401 // Verify subprogram. 402 if (!SP.isSubprogram()) 403 return; 404 405 // If the line number is 0, don't add it. 406 unsigned Line = SP.getLineNumber(); 407 if (Line == 0) 408 return; 409 410 unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(), SP.getDirectory(), 411 getUniqueID()); 412 assert(FileID && "Invalid file id"); 413 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID); 414 addUInt(Die, dwarf::DW_AT_decl_line, None, Line); 415 } 416 417 /// addSourceLine - Add location information to specified debug information 418 /// entry. 419 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) { 420 // Verify type. 421 if (!Ty.isType()) 422 return; 423 424 unsigned Line = Ty.getLineNumber(); 425 if (Line == 0) 426 return; 427 unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(), Ty.getDirectory(), 428 getUniqueID()); 429 assert(FileID && "Invalid file id"); 430 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID); 431 addUInt(Die, dwarf::DW_AT_decl_line, None, Line); 432 } 433 434 /// addSourceLine - Add location information to specified debug information 435 /// entry. 436 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) { 437 // Verify type. 438 if (!Ty.isObjCProperty()) 439 return; 440 441 unsigned Line = Ty.getLineNumber(); 442 if (Line == 0) 443 return; 444 DIFile File = Ty.getFile(); 445 unsigned FileID = DD->getOrCreateSourceID(File.getFilename(), 446 File.getDirectory(), getUniqueID()); 447 assert(FileID && "Invalid file id"); 448 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID); 449 addUInt(Die, dwarf::DW_AT_decl_line, None, Line); 450 } 451 452 /// addSourceLine - Add location information to specified debug information 453 /// entry. 454 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) { 455 // Verify namespace. 456 if (!NS.Verify()) 457 return; 458 459 unsigned Line = NS.getLineNumber(); 460 if (Line == 0) 461 return; 462 StringRef FN = NS.getFilename(); 463 464 unsigned FileID = 465 DD->getOrCreateSourceID(FN, NS.getDirectory(), getUniqueID()); 466 assert(FileID && "Invalid file id"); 467 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID); 468 addUInt(Die, dwarf::DW_AT_decl_line, None, Line); 469 } 470 471 /// addVariableAddress - Add DW_AT_location attribute for a 472 /// DbgVariable based on provided MachineLocation. 473 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die, 474 MachineLocation Location) { 475 if (DV.variableHasComplexAddress()) 476 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location); 477 else if (DV.isBlockByrefVariable()) 478 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location); 479 else 480 addAddress(Die, dwarf::DW_AT_location, Location, 481 DV.getVariable().isIndirect()); 482 } 483 484 /// addRegisterOp - Add register operand. 485 void DwarfUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) { 486 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo(); 487 unsigned DWReg = RI->getDwarfRegNum(Reg, false); 488 if (DWReg < 32) 489 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg); 490 else { 491 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx); 492 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg); 493 } 494 } 495 496 /// addRegisterOffset - Add register offset. 497 void DwarfUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg, 498 int64_t Offset) { 499 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo(); 500 unsigned DWReg = RI->getDwarfRegNum(Reg, false); 501 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo(); 502 if (Reg == TRI->getFrameRegister(*Asm->MF)) 503 // If variable offset is based in frame register then use fbreg. 504 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg); 505 else if (DWReg < 32) 506 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg); 507 else { 508 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx); 509 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg); 510 } 511 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset); 512 } 513 514 /// addAddress - Add an address attribute to a die based on the location 515 /// provided. 516 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute, 517 const MachineLocation &Location, bool Indirect) { 518 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 519 520 if (Location.isReg() && !Indirect) 521 addRegisterOp(Block, Location.getReg()); 522 else { 523 addRegisterOffset(Block, Location.getReg(), Location.getOffset()); 524 if (Indirect && !Location.isReg()) { 525 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 526 } 527 } 528 529 // Now attach the location information to the DIE. 530 addBlock(Die, Attribute, Block); 531 } 532 533 /// addComplexAddress - Start with the address based on the location provided, 534 /// and generate the DWARF information necessary to find the actual variable 535 /// given the extra address information encoded in the DbgVariable, starting 536 /// from the starting location. Add the DWARF information to the die. 537 /// 538 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die, 539 dwarf::Attribute Attribute, 540 const MachineLocation &Location) { 541 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 542 unsigned N = DV.getNumAddrElements(); 543 unsigned i = 0; 544 if (Location.isReg()) { 545 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) { 546 // If first address element is OpPlus then emit 547 // DW_OP_breg + Offset instead of DW_OP_reg + Offset. 548 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1)); 549 i = 2; 550 } else 551 addRegisterOp(Block, Location.getReg()); 552 } else 553 addRegisterOffset(Block, Location.getReg(), Location.getOffset()); 554 555 for (; i < N; ++i) { 556 uint64_t Element = DV.getAddrElement(i); 557 if (Element == DIBuilder::OpPlus) { 558 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 559 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i)); 560 } else if (Element == DIBuilder::OpDeref) { 561 if (!Location.isReg()) 562 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 563 } else 564 llvm_unreachable("unknown DIBuilder Opcode"); 565 } 566 567 // Now attach the location information to the DIE. 568 addBlock(Die, Attribute, Block); 569 } 570 571 /* Byref variables, in Blocks, are declared by the programmer as "SomeType 572 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and 573 gives the variable VarName either the struct, or a pointer to the struct, as 574 its type. This is necessary for various behind-the-scenes things the 575 compiler needs to do with by-reference variables in Blocks. 576 577 However, as far as the original *programmer* is concerned, the variable 578 should still have type 'SomeType', as originally declared. 579 580 The function getBlockByrefType dives into the __Block_byref_x_VarName 581 struct to find the original type of the variable, which is then assigned to 582 the variable's Debug Information Entry as its real type. So far, so good. 583 However now the debugger will expect the variable VarName to have the type 584 SomeType. So we need the location attribute for the variable to be an 585 expression that explains to the debugger how to navigate through the 586 pointers and struct to find the actual variable of type SomeType. 587 588 The following function does just that. We start by getting 589 the "normal" location for the variable. This will be the location 590 of either the struct __Block_byref_x_VarName or the pointer to the 591 struct __Block_byref_x_VarName. 592 593 The struct will look something like: 594 595 struct __Block_byref_x_VarName { 596 ... <various fields> 597 struct __Block_byref_x_VarName *forwarding; 598 ... <various other fields> 599 SomeType VarName; 600 ... <maybe more fields> 601 }; 602 603 If we are given the struct directly (as our starting point) we 604 need to tell the debugger to: 605 606 1). Add the offset of the forwarding field. 607 608 2). Follow that pointer to get the real __Block_byref_x_VarName 609 struct to use (the real one may have been copied onto the heap). 610 611 3). Add the offset for the field VarName, to find the actual variable. 612 613 If we started with a pointer to the struct, then we need to 614 dereference that pointer first, before the other steps. 615 Translating this into DWARF ops, we will need to append the following 616 to the current location description for the variable: 617 618 DW_OP_deref -- optional, if we start with a pointer 619 DW_OP_plus_uconst <forward_fld_offset> 620 DW_OP_deref 621 DW_OP_plus_uconst <varName_fld_offset> 622 623 That is what this function does. */ 624 625 /// addBlockByrefAddress - Start with the address based on the location 626 /// provided, and generate the DWARF information necessary to find the 627 /// actual Block variable (navigating the Block struct) based on the 628 /// starting location. Add the DWARF information to the die. For 629 /// more information, read large comment just above here. 630 /// 631 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die, 632 dwarf::Attribute Attribute, 633 const MachineLocation &Location) { 634 DIType Ty = DV.getType(); 635 DIType TmpTy = Ty; 636 uint16_t Tag = Ty.getTag(); 637 bool isPointer = false; 638 639 StringRef varName = DV.getName(); 640 641 if (Tag == dwarf::DW_TAG_pointer_type) { 642 DIDerivedType DTy(Ty); 643 TmpTy = resolve(DTy.getTypeDerivedFrom()); 644 isPointer = true; 645 } 646 647 DICompositeType blockStruct(TmpTy); 648 649 // Find the __forwarding field and the variable field in the __Block_byref 650 // struct. 651 DIArray Fields = blockStruct.getTypeArray(); 652 DIDerivedType varField; 653 DIDerivedType forwardingField; 654 655 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) { 656 DIDerivedType DT(Fields.getElement(i)); 657 StringRef fieldName = DT.getName(); 658 if (fieldName == "__forwarding") 659 forwardingField = DT; 660 else if (fieldName == varName) 661 varField = DT; 662 } 663 664 // Get the offsets for the forwarding field and the variable field. 665 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3; 666 unsigned varFieldOffset = varField.getOffsetInBits() >> 2; 667 668 // Decode the original location, and use that as the start of the byref 669 // variable's location. 670 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 671 672 if (Location.isReg()) 673 addRegisterOp(Block, Location.getReg()); 674 else 675 addRegisterOffset(Block, Location.getReg(), Location.getOffset()); 676 677 // If we started with a pointer to the __Block_byref... struct, then 678 // the first thing we need to do is dereference the pointer (DW_OP_deref). 679 if (isPointer) 680 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 681 682 // Next add the offset for the '__forwarding' field: 683 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in 684 // adding the offset if it's 0. 685 if (forwardingFieldOffset > 0) { 686 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 687 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset); 688 } 689 690 // Now dereference the __forwarding field to get to the real __Block_byref 691 // struct: DW_OP_deref. 692 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 693 694 // Now that we've got the real __Block_byref... struct, add the offset 695 // for the variable's field to get to the location of the actual variable: 696 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0. 697 if (varFieldOffset > 0) { 698 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 699 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset); 700 } 701 702 // Now attach the location information to the DIE. 703 addBlock(Die, Attribute, Block); 704 } 705 706 /// isTypeSigned - Return true if the type is signed. 707 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) { 708 if (Ty.isDerivedType()) 709 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()), 710 SizeInBits); 711 if (Ty.isBasicType()) 712 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed || 713 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) { 714 *SizeInBits = Ty.getSizeInBits(); 715 return true; 716 } 717 return false; 718 } 719 720 /// Return true if type encoding is unsigned. 721 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) { 722 DIDerivedType DTy(Ty); 723 if (DTy.isDerivedType()) 724 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom())); 725 726 DIBasicType BTy(Ty); 727 if (BTy.isBasicType()) { 728 unsigned Encoding = BTy.getEncoding(); 729 if (Encoding == dwarf::DW_ATE_unsigned || 730 Encoding == dwarf::DW_ATE_unsigned_char || 731 Encoding == dwarf::DW_ATE_boolean) 732 return true; 733 } 734 return false; 735 } 736 737 /// If this type is derived from a base type then return base type size. 738 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) { 739 unsigned Tag = Ty.getTag(); 740 741 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef && 742 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type && 743 Tag != dwarf::DW_TAG_restrict_type) 744 return Ty.getSizeInBits(); 745 746 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom()); 747 748 // If this type is not derived from any type then take conservative approach. 749 if (!BaseType.isValid()) 750 return Ty.getSizeInBits(); 751 752 // If this is a derived type, go ahead and get the base type, unless it's a 753 // reference then it's just the size of the field. Pointer types have no need 754 // of this since they're a different type of qualification on the type. 755 if (BaseType.getTag() == dwarf::DW_TAG_reference_type || 756 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type) 757 return Ty.getSizeInBits(); 758 759 if (BaseType.isDerivedType()) 760 return getBaseTypeSize(DD, DIDerivedType(BaseType)); 761 762 return BaseType.getSizeInBits(); 763 } 764 765 /// addConstantValue - Add constant value entry in variable DIE. 766 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO, 767 DIType Ty) { 768 // FIXME: This is a bit conservative/simple - it emits negative values at 769 // their maximum bit width which is a bit unfortunate (& doesn't prefer 770 // udata/sdata over dataN as suggested by the DWARF spec) 771 assert(MO.isImm() && "Invalid machine operand!"); 772 int SizeInBits = -1; 773 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits); 774 dwarf::Form Form; 775 776 // If we're a signed constant definitely use sdata. 777 if (SignedConstant) { 778 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm()); 779 return; 780 } 781 782 // Else use data for now unless it's larger than we can deal with. 783 switch (SizeInBits) { 784 case 8: 785 Form = dwarf::DW_FORM_data1; 786 break; 787 case 16: 788 Form = dwarf::DW_FORM_data2; 789 break; 790 case 32: 791 Form = dwarf::DW_FORM_data4; 792 break; 793 case 64: 794 Form = dwarf::DW_FORM_data8; 795 break; 796 default: 797 Form = dwarf::DW_FORM_udata; 798 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm()); 799 return; 800 } 801 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm()); 802 } 803 804 /// addConstantFPValue - Add constant value entry in variable DIE. 805 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) { 806 assert(MO.isFPImm() && "Invalid machine operand!"); 807 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 808 APFloat FPImm = MO.getFPImm()->getValueAPF(); 809 810 // Get the raw data form of the floating point. 811 const APInt FltVal = FPImm.bitcastToAPInt(); 812 const char *FltPtr = (const char *)FltVal.getRawData(); 813 814 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte. 815 bool LittleEndian = Asm->getDataLayout().isLittleEndian(); 816 int Incr = (LittleEndian ? 1 : -1); 817 int Start = (LittleEndian ? 0 : NumBytes - 1); 818 int Stop = (LittleEndian ? NumBytes : -1); 819 820 // Output the constant to DWARF one byte at a time. 821 for (; Start != Stop; Start += Incr) 822 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]); 823 824 addBlock(Die, dwarf::DW_AT_const_value, Block); 825 } 826 827 /// addConstantFPValue - Add constant value entry in variable DIE. 828 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) { 829 // Pass this down to addConstantValue as an unsigned bag of bits. 830 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true); 831 } 832 833 /// addConstantValue - Add constant value entry in variable DIE. 834 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI, 835 bool Unsigned) { 836 addConstantValue(Die, CI->getValue(), Unsigned); 837 } 838 839 // addConstantValue - Add constant value entry in variable DIE. 840 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) { 841 unsigned CIBitWidth = Val.getBitWidth(); 842 if (CIBitWidth <= 64) { 843 // If we're a signed constant definitely use sdata. 844 if (!Unsigned) { 845 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, 846 Val.getSExtValue()); 847 return; 848 } 849 850 // Else use data for now unless it's larger than we can deal with. 851 dwarf::Form Form; 852 switch (CIBitWidth) { 853 case 8: 854 Form = dwarf::DW_FORM_data1; 855 break; 856 case 16: 857 Form = dwarf::DW_FORM_data2; 858 break; 859 case 32: 860 Form = dwarf::DW_FORM_data4; 861 break; 862 case 64: 863 Form = dwarf::DW_FORM_data8; 864 break; 865 default: 866 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata, 867 Val.getZExtValue()); 868 return; 869 } 870 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue()); 871 return; 872 } 873 874 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 875 876 // Get the raw data form of the large APInt. 877 const uint64_t *Ptr64 = Val.getRawData(); 878 879 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte. 880 bool LittleEndian = Asm->getDataLayout().isLittleEndian(); 881 882 // Output the constant to DWARF one byte at a time. 883 for (int i = 0; i < NumBytes; i++) { 884 uint8_t c; 885 if (LittleEndian) 886 c = Ptr64[i / 8] >> (8 * (i & 7)); 887 else 888 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7)); 889 addUInt(Block, dwarf::DW_FORM_data1, c); 890 } 891 892 addBlock(Die, dwarf::DW_AT_const_value, Block); 893 } 894 895 /// addTemplateParams - Add template parameters into buffer. 896 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) { 897 // Add template parameters. 898 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) { 899 DIDescriptor Element = TParams.getElement(i); 900 if (Element.isTemplateTypeParameter()) 901 constructTemplateTypeParameterDIE(Buffer, 902 DITemplateTypeParameter(Element)); 903 else if (Element.isTemplateValueParameter()) 904 constructTemplateValueParameterDIE(Buffer, 905 DITemplateValueParameter(Element)); 906 } 907 } 908 909 /// getOrCreateContextDIE - Get context owner's DIE. 910 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) { 911 if (!Context || Context.isFile()) 912 return getUnitDie(); 913 if (Context.isType()) 914 return getOrCreateTypeDIE(DIType(Context)); 915 if (Context.isNameSpace()) 916 return getOrCreateNameSpace(DINameSpace(Context)); 917 if (Context.isSubprogram()) 918 return getOrCreateSubprogramDIE(DISubprogram(Context)); 919 return getDIE(Context); 920 } 921 922 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) { 923 DIScope Context = resolve(Ty.getContext()); 924 DIE *ContextDIE = getOrCreateContextDIE(Context); 925 926 DIE *TyDIE = getDIE(Ty); 927 if (TyDIE) 928 return TyDIE; 929 930 // Create new type. 931 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty); 932 933 constructTypeDIE(*TyDIE, Ty); 934 935 updateAcceleratorTables(Context, Ty, TyDIE); 936 return TyDIE; 937 } 938 939 /// Return true if the type is appropriately scoped to be contained inside 940 /// its own type unit. 941 static bool isDwarfTypeUnitScoped(DIType Ty, const DwarfDebug *DD) { 942 DIScope Parent = DD->resolve(Ty.getContext()); 943 while (Parent) { 944 // Don't generate a hash for anything scoped inside a function. 945 if (Parent.isSubprogram()) 946 return false; 947 Parent = DD->resolve(Parent.getContext()); 948 } 949 return true; 950 } 951 952 /// Return true if the type should be split out into a type unit. 953 static bool shouldCreateDwarfTypeUnit(DICompositeType CTy, 954 const DwarfDebug *DD) { 955 if (!GenerateDwarfTypeUnits) 956 return false; 957 958 uint16_t Tag = CTy.getTag(); 959 960 switch (Tag) { 961 case dwarf::DW_TAG_structure_type: 962 case dwarf::DW_TAG_union_type: 963 case dwarf::DW_TAG_enumeration_type: 964 case dwarf::DW_TAG_class_type: 965 // If this is a class, structure, union, or enumeration type 966 // that is a definition (not a declaration), and not scoped 967 // inside a function then separate this out as a type unit. 968 return !CTy.isForwardDecl() && isDwarfTypeUnitScoped(CTy, DD); 969 default: 970 return false; 971 } 972 } 973 974 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the 975 /// given DIType. 976 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) { 977 if (!TyNode) 978 return NULL; 979 980 DIType Ty(TyNode); 981 assert(Ty.isType()); 982 983 // Construct the context before querying for the existence of the DIE in case 984 // such construction creates the DIE. 985 DIScope Context = resolve(Ty.getContext()); 986 DIE *ContextDIE = getOrCreateContextDIE(Context); 987 assert(ContextDIE); 988 989 DIE *TyDIE = getDIE(Ty); 990 if (TyDIE) 991 return TyDIE; 992 993 // Create new type. 994 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty); 995 996 if (Ty.isBasicType()) 997 constructTypeDIE(*TyDIE, DIBasicType(Ty)); 998 else if (Ty.isCompositeType()) { 999 DICompositeType CTy(Ty); 1000 if (shouldCreateDwarfTypeUnit(CTy, DD)) { 1001 DD->addDwarfTypeUnitType(getLanguage(), TyDIE, CTy); 1002 // Skip updating the accellerator tables since this is not the full type 1003 return TyDIE; 1004 } 1005 constructTypeDIE(*TyDIE, CTy); 1006 } else { 1007 assert(Ty.isDerivedType() && "Unknown kind of DIType"); 1008 constructTypeDIE(*TyDIE, DIDerivedType(Ty)); 1009 } 1010 1011 updateAcceleratorTables(Context, Ty, TyDIE); 1012 1013 return TyDIE; 1014 } 1015 1016 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty, 1017 const DIE *TyDIE) { 1018 if (!Ty.getName().empty() && !Ty.isForwardDecl()) { 1019 bool IsImplementation = 0; 1020 if (Ty.isCompositeType()) { 1021 DICompositeType CT(Ty); 1022 // A runtime language of 0 actually means C/C++ and that any 1023 // non-negative value is some version of Objective-C/C++. 1024 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete(); 1025 } 1026 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0; 1027 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags)); 1028 1029 if (!Context || Context.isCompileUnit() || Context.isFile() || 1030 Context.isNameSpace()) 1031 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE; 1032 } 1033 } 1034 1035 /// addType - Add a new type attribute to the specified entity. 1036 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) { 1037 assert(Ty && "Trying to add a type that doesn't exist?"); 1038 1039 // Check for pre-existence. 1040 DIEEntry *Entry = getDIEEntry(Ty); 1041 // If it exists then use the existing value. 1042 if (Entry) { 1043 addDIEEntry(Entity, Attribute, Entry); 1044 return; 1045 } 1046 1047 // Construct type. 1048 DIE *Buffer = getOrCreateTypeDIE(Ty); 1049 1050 // Set up proxy. 1051 Entry = createDIEEntry(Buffer); 1052 insertDIEEntry(Ty, Entry); 1053 addDIEEntry(Entity, Attribute, Entry); 1054 } 1055 1056 // Accelerator table mutators - add each name along with its companion 1057 // DIE to the proper table while ensuring that the name that we're going 1058 // to reference is in the string table. We do this since the names we 1059 // add may not only be identical to the names in the DIE. 1060 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) { 1061 DU->getStringPoolEntry(Name); 1062 std::vector<const DIE *> &DIEs = AccelNames[Name]; 1063 DIEs.push_back(Die); 1064 } 1065 1066 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) { 1067 DU->getStringPoolEntry(Name); 1068 std::vector<const DIE *> &DIEs = AccelObjC[Name]; 1069 DIEs.push_back(Die); 1070 } 1071 1072 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) { 1073 DU->getStringPoolEntry(Name); 1074 std::vector<const DIE *> &DIEs = AccelNamespace[Name]; 1075 DIEs.push_back(Die); 1076 } 1077 1078 void DwarfUnit::addAccelType(StringRef Name, 1079 std::pair<const DIE *, unsigned> Die) { 1080 DU->getStringPoolEntry(Name); 1081 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name]; 1082 DIEs.push_back(Die); 1083 } 1084 1085 /// addGlobalName - Add a new global name to the compile unit. 1086 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) { 1087 std::string FullName = getParentContextString(Context) + Name.str(); 1088 GlobalNames[FullName] = Die; 1089 } 1090 1091 /// getParentContextString - Walks the metadata parent chain in a language 1092 /// specific manner (using the compile unit language) and returns 1093 /// it as a string. This is done at the metadata level because DIEs may 1094 /// not currently have been added to the parent context and walking the 1095 /// DIEs looking for names is more expensive than walking the metadata. 1096 std::string DwarfUnit::getParentContextString(DIScope Context) const { 1097 if (!Context) 1098 return ""; 1099 1100 // FIXME: Decide whether to implement this for non-C++ languages. 1101 if (getLanguage() != dwarf::DW_LANG_C_plus_plus) 1102 return ""; 1103 1104 std::string CS; 1105 SmallVector<DIScope, 1> Parents; 1106 while (!Context.isCompileUnit()) { 1107 Parents.push_back(Context); 1108 if (Context.getContext()) 1109 Context = resolve(Context.getContext()); 1110 else 1111 // Structure, etc types will have a NULL context if they're at the top 1112 // level. 1113 break; 1114 } 1115 1116 // Reverse iterate over our list to go from the outermost construct to the 1117 // innermost. 1118 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(), 1119 E = Parents.rend(); 1120 I != E; ++I) { 1121 DIScope Ctx = *I; 1122 StringRef Name = Ctx.getName(); 1123 if (!Name.empty()) { 1124 CS += Name; 1125 CS += "::"; 1126 } 1127 } 1128 return CS; 1129 } 1130 1131 /// constructTypeDIE - Construct basic type die from DIBasicType. 1132 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) { 1133 // Get core information. 1134 StringRef Name = BTy.getName(); 1135 // Add name if not anonymous or intermediate type. 1136 if (!Name.empty()) 1137 addString(&Buffer, dwarf::DW_AT_name, Name); 1138 1139 // An unspecified type only has a name attribute. 1140 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type) 1141 return; 1142 1143 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, 1144 BTy.getEncoding()); 1145 1146 uint64_t Size = BTy.getSizeInBits() >> 3; 1147 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size); 1148 } 1149 1150 /// constructTypeDIE - Construct derived type die from DIDerivedType. 1151 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) { 1152 // Get core information. 1153 StringRef Name = DTy.getName(); 1154 uint64_t Size = DTy.getSizeInBits() >> 3; 1155 uint16_t Tag = Buffer.getTag(); 1156 1157 // Map to main type, void will not have a type. 1158 DIType FromTy = resolve(DTy.getTypeDerivedFrom()); 1159 if (FromTy) 1160 addType(&Buffer, FromTy); 1161 1162 // Add name if not anonymous or intermediate type. 1163 if (!Name.empty()) 1164 addString(&Buffer, dwarf::DW_AT_name, Name); 1165 1166 // Add size if non-zero (derived types might be zero-sized.) 1167 if (Size && Tag != dwarf::DW_TAG_pointer_type) 1168 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size); 1169 1170 if (Tag == dwarf::DW_TAG_ptr_to_member_type) 1171 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, 1172 getOrCreateTypeDIE(resolve(DTy.getClassType()))); 1173 // Add source line info if available and TyDesc is not a forward declaration. 1174 if (!DTy.isForwardDecl()) 1175 addSourceLine(&Buffer, DTy); 1176 } 1177 1178 /// constructTypeDIE - Construct type DIE from DICompositeType. 1179 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) { 1180 // Add name if not anonymous or intermediate type. 1181 StringRef Name = CTy.getName(); 1182 1183 uint64_t Size = CTy.getSizeInBits() >> 3; 1184 uint16_t Tag = Buffer.getTag(); 1185 1186 switch (Tag) { 1187 case dwarf::DW_TAG_array_type: 1188 constructArrayTypeDIE(Buffer, CTy); 1189 break; 1190 case dwarf::DW_TAG_enumeration_type: 1191 constructEnumTypeDIE(Buffer, CTy); 1192 break; 1193 case dwarf::DW_TAG_subroutine_type: { 1194 // Add return type. A void return won't have a type. 1195 DIArray Elements = CTy.getTypeArray(); 1196 DIType RTy(Elements.getElement(0)); 1197 if (RTy) 1198 addType(&Buffer, RTy); 1199 1200 bool isPrototyped = true; 1201 // Add arguments. 1202 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) { 1203 DIDescriptor Ty = Elements.getElement(i); 1204 if (Ty.isUnspecifiedParameter()) { 1205 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer); 1206 isPrototyped = false; 1207 } else { 1208 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer); 1209 addType(Arg, DIType(Ty)); 1210 if (DIType(Ty).isArtificial()) 1211 addFlag(Arg, dwarf::DW_AT_artificial); 1212 } 1213 } 1214 // Add prototype flag if we're dealing with a C language and the 1215 // function has been prototyped. 1216 uint16_t Language = getLanguage(); 1217 if (isPrototyped && 1218 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 || 1219 Language == dwarf::DW_LANG_ObjC)) 1220 addFlag(&Buffer, dwarf::DW_AT_prototyped); 1221 1222 if (CTy.isLValueReference()) 1223 addFlag(&Buffer, dwarf::DW_AT_reference); 1224 1225 if (CTy.isRValueReference()) 1226 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference); 1227 } break; 1228 case dwarf::DW_TAG_structure_type: 1229 case dwarf::DW_TAG_union_type: 1230 case dwarf::DW_TAG_class_type: { 1231 // Add elements to structure type. 1232 DIArray Elements = CTy.getTypeArray(); 1233 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) { 1234 DIDescriptor Element = Elements.getElement(i); 1235 DIE *ElemDie = NULL; 1236 if (Element.isSubprogram()) { 1237 DISubprogram SP(Element); 1238 ElemDie = getOrCreateSubprogramDIE(SP); 1239 if (SP.isProtected()) 1240 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1241 dwarf::DW_ACCESS_protected); 1242 else if (SP.isPrivate()) 1243 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1244 dwarf::DW_ACCESS_private); 1245 else 1246 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1247 dwarf::DW_ACCESS_public); 1248 if (SP.isExplicit()) 1249 addFlag(ElemDie, dwarf::DW_AT_explicit); 1250 } else if (Element.isDerivedType()) { 1251 DIDerivedType DDTy(Element); 1252 if (DDTy.getTag() == dwarf::DW_TAG_friend) { 1253 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer); 1254 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()), 1255 dwarf::DW_AT_friend); 1256 } else if (DDTy.isStaticMember()) { 1257 getOrCreateStaticMemberDIE(DDTy); 1258 } else { 1259 constructMemberDIE(Buffer, DDTy); 1260 } 1261 } else if (Element.isObjCProperty()) { 1262 DIObjCProperty Property(Element); 1263 ElemDie = createAndAddDIE(Property.getTag(), Buffer); 1264 StringRef PropertyName = Property.getObjCPropertyName(); 1265 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName); 1266 addType(ElemDie, Property.getType()); 1267 addSourceLine(ElemDie, Property); 1268 StringRef GetterName = Property.getObjCPropertyGetterName(); 1269 if (!GetterName.empty()) 1270 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName); 1271 StringRef SetterName = Property.getObjCPropertySetterName(); 1272 if (!SetterName.empty()) 1273 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName); 1274 unsigned PropertyAttributes = 0; 1275 if (Property.isReadOnlyObjCProperty()) 1276 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly; 1277 if (Property.isReadWriteObjCProperty()) 1278 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite; 1279 if (Property.isAssignObjCProperty()) 1280 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign; 1281 if (Property.isRetainObjCProperty()) 1282 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain; 1283 if (Property.isCopyObjCProperty()) 1284 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy; 1285 if (Property.isNonAtomicObjCProperty()) 1286 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic; 1287 if (PropertyAttributes) 1288 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None, 1289 PropertyAttributes); 1290 1291 DIEEntry *Entry = getDIEEntry(Element); 1292 if (!Entry) { 1293 Entry = createDIEEntry(ElemDie); 1294 insertDIEEntry(Element, Entry); 1295 } 1296 } else 1297 continue; 1298 } 1299 1300 if (CTy.isAppleBlockExtension()) 1301 addFlag(&Buffer, dwarf::DW_AT_APPLE_block); 1302 1303 DICompositeType ContainingType(resolve(CTy.getContainingType())); 1304 if (ContainingType) 1305 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, 1306 getOrCreateTypeDIE(ContainingType)); 1307 1308 if (CTy.isObjcClassComplete()) 1309 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type); 1310 1311 // Add template parameters to a class, structure or union types. 1312 // FIXME: The support isn't in the metadata for this yet. 1313 if (Tag == dwarf::DW_TAG_class_type || 1314 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) 1315 addTemplateParams(Buffer, CTy.getTemplateParams()); 1316 1317 break; 1318 } 1319 default: 1320 break; 1321 } 1322 1323 // Add name if not anonymous or intermediate type. 1324 if (!Name.empty()) 1325 addString(&Buffer, dwarf::DW_AT_name, Name); 1326 1327 if (Tag == dwarf::DW_TAG_enumeration_type || 1328 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type || 1329 Tag == dwarf::DW_TAG_union_type) { 1330 // Add size if non-zero (derived types might be zero-sized.) 1331 // TODO: Do we care about size for enum forward declarations? 1332 if (Size) 1333 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size); 1334 else if (!CTy.isForwardDecl()) 1335 // Add zero size if it is not a forward declaration. 1336 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0); 1337 1338 // If we're a forward decl, say so. 1339 if (CTy.isForwardDecl()) 1340 addFlag(&Buffer, dwarf::DW_AT_declaration); 1341 1342 // Add source line info if available. 1343 if (!CTy.isForwardDecl()) 1344 addSourceLine(&Buffer, CTy); 1345 1346 // No harm in adding the runtime language to the declaration. 1347 unsigned RLang = CTy.getRunTimeLang(); 1348 if (RLang) 1349 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1, 1350 RLang); 1351 } 1352 } 1353 1354 /// constructTemplateTypeParameterDIE - Construct new DIE for the given 1355 /// DITemplateTypeParameter. 1356 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer, 1357 DITemplateTypeParameter TP) { 1358 DIE *ParamDIE = 1359 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer); 1360 // Add the type if it exists, it could be void and therefore no type. 1361 if (TP.getType()) 1362 addType(ParamDIE, resolve(TP.getType())); 1363 if (!TP.getName().empty()) 1364 addString(ParamDIE, dwarf::DW_AT_name, TP.getName()); 1365 } 1366 1367 /// constructTemplateValueParameterDIE - Construct new DIE for the given 1368 /// DITemplateValueParameter. 1369 void 1370 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer, 1371 DITemplateValueParameter VP) { 1372 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer); 1373 1374 // Add the type if there is one, template template and template parameter 1375 // packs will not have a type. 1376 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter) 1377 addType(ParamDIE, resolve(VP.getType())); 1378 if (!VP.getName().empty()) 1379 addString(ParamDIE, dwarf::DW_AT_name, VP.getName()); 1380 if (Value *Val = VP.getValue()) { 1381 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) 1382 addConstantValue(ParamDIE, CI, 1383 isUnsignedDIType(DD, resolve(VP.getType()))); 1384 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) { 1385 // For declaration non-type template parameters (such as global values and 1386 // functions) 1387 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 1388 addOpAddress(Block, Asm->getSymbol(GV)); 1389 // Emit DW_OP_stack_value to use the address as the immediate value of the 1390 // parameter, rather than a pointer to it. 1391 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value); 1392 addBlock(ParamDIE, dwarf::DW_AT_location, Block); 1393 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) { 1394 assert(isa<MDString>(Val)); 1395 addString(ParamDIE, dwarf::DW_AT_GNU_template_name, 1396 cast<MDString>(Val)->getString()); 1397 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) { 1398 assert(isa<MDNode>(Val)); 1399 DIArray A(cast<MDNode>(Val)); 1400 addTemplateParams(*ParamDIE, A); 1401 } 1402 } 1403 } 1404 1405 /// getOrCreateNameSpace - Create a DIE for DINameSpace. 1406 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) { 1407 // Construct the context before querying for the existence of the DIE in case 1408 // such construction creates the DIE. 1409 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext()); 1410 1411 DIE *NDie = getDIE(NS); 1412 if (NDie) 1413 return NDie; 1414 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS); 1415 1416 if (!NS.getName().empty()) { 1417 addString(NDie, dwarf::DW_AT_name, NS.getName()); 1418 addAccelNamespace(NS.getName(), NDie); 1419 addGlobalName(NS.getName(), NDie, NS.getContext()); 1420 } else 1421 addAccelNamespace("(anonymous namespace)", NDie); 1422 addSourceLine(NDie, NS); 1423 return NDie; 1424 } 1425 1426 /// getOrCreateSubprogramDIE - Create new DIE using SP. 1427 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) { 1428 // Construct the context before querying for the existence of the DIE in case 1429 // such construction creates the DIE (as is the case for member function 1430 // declarations). 1431 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext())); 1432 1433 DIE *SPDie = getDIE(SP); 1434 if (SPDie) 1435 return SPDie; 1436 1437 DISubprogram SPDecl = SP.getFunctionDeclaration(); 1438 if (SPDecl.isSubprogram()) 1439 // Add subprogram definitions to the CU die directly. 1440 ContextDIE = UnitDie.get(); 1441 1442 // DW_TAG_inlined_subroutine may refer to this DIE. 1443 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP); 1444 1445 DIE *DeclDie = NULL; 1446 if (SPDecl.isSubprogram()) 1447 DeclDie = getOrCreateSubprogramDIE(SPDecl); 1448 1449 // Add function template parameters. 1450 addTemplateParams(*SPDie, SP.getTemplateParams()); 1451 1452 // If this DIE is going to refer declaration info using AT_specification 1453 // then there is no need to add other attributes. 1454 if (DeclDie) { 1455 // Refer function declaration directly. 1456 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie); 1457 1458 return SPDie; 1459 } 1460 1461 // Add the linkage name if we have one. 1462 StringRef LinkageName = SP.getLinkageName(); 1463 if (!LinkageName.empty()) 1464 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, 1465 GlobalValue::getRealLinkageName(LinkageName)); 1466 1467 // Constructors and operators for anonymous aggregates do not have names. 1468 if (!SP.getName().empty()) 1469 addString(SPDie, dwarf::DW_AT_name, SP.getName()); 1470 1471 addSourceLine(SPDie, SP); 1472 1473 // Add the prototype if we have a prototype and we have a C like 1474 // language. 1475 uint16_t Language = getLanguage(); 1476 if (SP.isPrototyped() && 1477 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 || 1478 Language == dwarf::DW_LANG_ObjC)) 1479 addFlag(SPDie, dwarf::DW_AT_prototyped); 1480 1481 DICompositeType SPTy = SP.getType(); 1482 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type && 1483 "the type of a subprogram should be a subroutine"); 1484 1485 DIArray Args = SPTy.getTypeArray(); 1486 // Add a return type. If this is a type like a C/C++ void type we don't add a 1487 // return type. 1488 if (Args.getElement(0)) 1489 addType(SPDie, DIType(Args.getElement(0))); 1490 1491 unsigned VK = SP.getVirtuality(); 1492 if (VK) { 1493 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK); 1494 DIEBlock *Block = getDIEBlock(); 1495 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 1496 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex()); 1497 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block); 1498 ContainingTypeMap.insert( 1499 std::make_pair(SPDie, resolve(SP.getContainingType()))); 1500 } 1501 1502 if (!SP.isDefinition()) { 1503 addFlag(SPDie, dwarf::DW_AT_declaration); 1504 1505 // Add arguments. Do not add arguments for subprogram definition. They will 1506 // be handled while processing variables. 1507 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) { 1508 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie); 1509 DIType ATy(Args.getElement(i)); 1510 addType(Arg, ATy); 1511 if (ATy.isArtificial()) 1512 addFlag(Arg, dwarf::DW_AT_artificial); 1513 } 1514 } 1515 1516 if (SP.isArtificial()) 1517 addFlag(SPDie, dwarf::DW_AT_artificial); 1518 1519 if (!SP.isLocalToUnit()) 1520 addFlag(SPDie, dwarf::DW_AT_external); 1521 1522 if (SP.isOptimized()) 1523 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized); 1524 1525 if (unsigned isa = Asm->getISAEncoding()) { 1526 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa); 1527 } 1528 1529 if (SP.isLValueReference()) 1530 addFlag(SPDie, dwarf::DW_AT_reference); 1531 1532 if (SP.isRValueReference()) 1533 addFlag(SPDie, dwarf::DW_AT_rvalue_reference); 1534 1535 return SPDie; 1536 } 1537 1538 // Return const expression if value is a GEP to access merged global 1539 // constant. e.g. 1540 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0) 1541 static const ConstantExpr *getMergedGlobalExpr(const Value *V) { 1542 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V); 1543 if (!CE || CE->getNumOperands() != 3 || 1544 CE->getOpcode() != Instruction::GetElementPtr) 1545 return NULL; 1546 1547 // First operand points to a global struct. 1548 Value *Ptr = CE->getOperand(0); 1549 if (!isa<GlobalValue>(Ptr) || 1550 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType())) 1551 return NULL; 1552 1553 // Second operand is zero. 1554 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1)); 1555 if (!CI || !CI->isZero()) 1556 return NULL; 1557 1558 // Third operand is offset. 1559 if (!isa<ConstantInt>(CE->getOperand(2))) 1560 return NULL; 1561 1562 return CE; 1563 } 1564 1565 /// createGlobalVariableDIE - create global variable DIE. 1566 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) { 1567 // Check for pre-existence. 1568 if (getDIE(GV)) 1569 return; 1570 1571 if (!GV.isGlobalVariable()) 1572 return; 1573 1574 DIScope GVContext = GV.getContext(); 1575 DIType GTy = GV.getType(); 1576 1577 // If this is a static data member definition, some attributes belong 1578 // to the declaration DIE. 1579 DIE *VariableDIE = NULL; 1580 bool IsStaticMember = false; 1581 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration(); 1582 if (SDMDecl.Verify()) { 1583 assert(SDMDecl.isStaticMember() && "Expected static member decl"); 1584 // We need the declaration DIE that is in the static member's class. 1585 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl); 1586 IsStaticMember = true; 1587 } 1588 1589 // If this is not a static data member definition, create the variable 1590 // DIE and add the initial set of attributes to it. 1591 if (!VariableDIE) { 1592 // Construct the context before querying for the existence of the DIE in 1593 // case such construction creates the DIE. 1594 DIE *ContextDIE = getOrCreateContextDIE(GVContext); 1595 1596 // Add to map. 1597 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV); 1598 1599 // Add name and type. 1600 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName()); 1601 addType(VariableDIE, GTy); 1602 1603 // Add scoping info. 1604 if (!GV.isLocalToUnit()) 1605 addFlag(VariableDIE, dwarf::DW_AT_external); 1606 1607 // Add line number info. 1608 addSourceLine(VariableDIE, GV); 1609 } 1610 1611 // Add location. 1612 bool addToAccelTable = false; 1613 DIE *VariableSpecDIE = NULL; 1614 bool isGlobalVariable = GV.getGlobal() != NULL; 1615 if (isGlobalVariable) { 1616 addToAccelTable = true; 1617 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 1618 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal()); 1619 if (GV.getGlobal()->isThreadLocal()) { 1620 // FIXME: Make this work with -gsplit-dwarf. 1621 unsigned PointerSize = Asm->getDataLayout().getPointerSize(); 1622 assert((PointerSize == 4 || PointerSize == 8) && 1623 "Add support for other sizes if necessary"); 1624 const MCExpr *Expr = 1625 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym); 1626 // Based on GCC's support for TLS: 1627 if (!DD->useSplitDwarf()) { 1628 // 1) Start with a constNu of the appropriate pointer size 1629 addUInt(Block, dwarf::DW_FORM_data1, 1630 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u); 1631 // 2) containing the (relocated) offset of the TLS variable 1632 // within the module's TLS block. 1633 addExpr(Block, dwarf::DW_FORM_udata, Expr); 1634 } else { 1635 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index); 1636 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr)); 1637 } 1638 // 3) followed by a custom OP to make the debugger do a TLS lookup. 1639 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address); 1640 } else { 1641 DD->addArangeLabel(SymbolCU(this, Sym)); 1642 addOpAddress(Block, Sym); 1643 } 1644 // Do not create specification DIE if context is either compile unit 1645 // or a subprogram. 1646 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() && 1647 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) { 1648 // Create specification DIE. 1649 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie); 1650 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE); 1651 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block); 1652 // A static member's declaration is already flagged as such. 1653 if (!SDMDecl.Verify()) 1654 addFlag(VariableDIE, dwarf::DW_AT_declaration); 1655 } else { 1656 addBlock(VariableDIE, dwarf::DW_AT_location, Block); 1657 } 1658 // Add the linkage name. 1659 StringRef LinkageName = GV.getLinkageName(); 1660 if (!LinkageName.empty()) 1661 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include: 1662 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and 1663 // TAG_variable. 1664 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE 1665 : VariableDIE, 1666 dwarf::DW_AT_MIPS_linkage_name, 1667 GlobalValue::getRealLinkageName(LinkageName)); 1668 } else if (const ConstantInt *CI = 1669 dyn_cast_or_null<ConstantInt>(GV.getConstant())) { 1670 // AT_const_value was added when the static member was created. To avoid 1671 // emitting AT_const_value multiple times, we only add AT_const_value when 1672 // it is not a static member. 1673 if (!IsStaticMember) 1674 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy)); 1675 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) { 1676 addToAccelTable = true; 1677 // GV is a merged global. 1678 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 1679 Value *Ptr = CE->getOperand(0); 1680 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr)); 1681 DD->addArangeLabel(SymbolCU(this, Sym)); 1682 addOpAddress(Block, Sym); 1683 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 1684 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end()); 1685 addUInt(Block, dwarf::DW_FORM_udata, 1686 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx)); 1687 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus); 1688 addBlock(VariableDIE, dwarf::DW_AT_location, Block); 1689 } 1690 1691 if (addToAccelTable) { 1692 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE; 1693 addAccelName(GV.getName(), AddrDIE); 1694 1695 // If the linkage name is different than the name, go ahead and output 1696 // that as well into the name table. 1697 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName()) 1698 addAccelName(GV.getLinkageName(), AddrDIE); 1699 } 1700 1701 if (!GV.isLocalToUnit()) 1702 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE, 1703 GV.getContext()); 1704 } 1705 1706 /// constructSubrangeDIE - Construct subrange DIE from DISubrange. 1707 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) { 1708 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer); 1709 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy); 1710 1711 // The LowerBound value defines the lower bounds which is typically zero for 1712 // C/C++. The Count value is the number of elements. Values are 64 bit. If 1713 // Count == -1 then the array is unbounded and we do not emit 1714 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and 1715 // Count == 0, then the array has zero elements in which case we do not emit 1716 // an upper bound. 1717 int64_t LowerBound = SR.getLo(); 1718 int64_t DefaultLowerBound = getDefaultLowerBound(); 1719 int64_t Count = SR.getCount(); 1720 1721 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound) 1722 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound); 1723 1724 if (Count != -1 && Count != 0) 1725 // FIXME: An unbounded array should reference the expression that defines 1726 // the array. 1727 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None, 1728 LowerBound + Count - 1); 1729 } 1730 1731 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType. 1732 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) { 1733 if (CTy.isVector()) 1734 addFlag(&Buffer, dwarf::DW_AT_GNU_vector); 1735 1736 // Emit the element type. 1737 addType(&Buffer, resolve(CTy.getTypeDerivedFrom())); 1738 1739 // Get an anonymous type for index type. 1740 // FIXME: This type should be passed down from the front end 1741 // as different languages may have different sizes for indexes. 1742 DIE *IdxTy = getIndexTyDie(); 1743 if (!IdxTy) { 1744 // Construct an anonymous type for index type. 1745 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie); 1746 addString(IdxTy, dwarf::DW_AT_name, "int"); 1747 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t)); 1748 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, 1749 dwarf::DW_ATE_signed); 1750 setIndexTyDie(IdxTy); 1751 } 1752 1753 // Add subranges to array type. 1754 DIArray Elements = CTy.getTypeArray(); 1755 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) { 1756 DIDescriptor Element = Elements.getElement(i); 1757 if (Element.getTag() == dwarf::DW_TAG_subrange_type) 1758 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy); 1759 } 1760 } 1761 1762 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType. 1763 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) { 1764 DIArray Elements = CTy.getTypeArray(); 1765 1766 // Add enumerators to enumeration type. 1767 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) { 1768 DIEnumerator Enum(Elements.getElement(i)); 1769 if (Enum.isEnumerator()) { 1770 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer); 1771 StringRef Name = Enum.getName(); 1772 addString(Enumerator, dwarf::DW_AT_name, Name); 1773 int64_t Value = Enum.getEnumValue(); 1774 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, 1775 Value); 1776 } 1777 } 1778 DIType DTy = resolve(CTy.getTypeDerivedFrom()); 1779 if (DTy) { 1780 addType(&Buffer, DTy); 1781 addFlag(&Buffer, dwarf::DW_AT_enum_class); 1782 } 1783 } 1784 1785 /// constructContainingTypeDIEs - Construct DIEs for types that contain 1786 /// vtables. 1787 void DwarfUnit::constructContainingTypeDIEs() { 1788 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(), 1789 CE = ContainingTypeMap.end(); 1790 CI != CE; ++CI) { 1791 DIE *SPDie = CI->first; 1792 DIDescriptor D(CI->second); 1793 if (!D) 1794 continue; 1795 DIE *NDie = getDIE(D); 1796 if (!NDie) 1797 continue; 1798 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie); 1799 } 1800 } 1801 1802 /// constructVariableDIE - Construct a DIE for the given DbgVariable. 1803 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) { 1804 StringRef Name = DV.getName(); 1805 1806 // Define variable debug information entry. 1807 DIE *VariableDie = new DIE(DV.getTag()); 1808 DbgVariable *AbsVar = DV.getAbstractVariable(); 1809 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL; 1810 if (AbsDIE) 1811 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE); 1812 else { 1813 if (!Name.empty()) 1814 addString(VariableDie, dwarf::DW_AT_name, Name); 1815 addSourceLine(VariableDie, DV.getVariable()); 1816 addType(VariableDie, DV.getType()); 1817 } 1818 1819 if (DV.isArtificial()) 1820 addFlag(VariableDie, dwarf::DW_AT_artificial); 1821 1822 if (isScopeAbstract) { 1823 DV.setDIE(VariableDie); 1824 return VariableDie; 1825 } 1826 1827 // Add variable address. 1828 1829 unsigned Offset = DV.getDotDebugLocOffset(); 1830 if (Offset != ~0U) { 1831 addSectionLabel(VariableDie, dwarf::DW_AT_location, 1832 Asm->GetTempSymbol("debug_loc", Offset)); 1833 DV.setDIE(VariableDie); 1834 return VariableDie; 1835 } 1836 1837 // Check if variable is described by a DBG_VALUE instruction. 1838 if (const MachineInstr *DVInsn = DV.getMInsn()) { 1839 assert(DVInsn->getNumOperands() == 3); 1840 if (DVInsn->getOperand(0).isReg()) { 1841 const MachineOperand RegOp = DVInsn->getOperand(0); 1842 // If the second operand is an immediate, this is an indirect value. 1843 if (DVInsn->getOperand(1).isImm()) { 1844 MachineLocation Location(RegOp.getReg(), 1845 DVInsn->getOperand(1).getImm()); 1846 addVariableAddress(DV, VariableDie, Location); 1847 } else if (RegOp.getReg()) 1848 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg())); 1849 } else if (DVInsn->getOperand(0).isImm()) 1850 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType()); 1851 else if (DVInsn->getOperand(0).isFPImm()) 1852 addConstantFPValue(VariableDie, DVInsn->getOperand(0)); 1853 else if (DVInsn->getOperand(0).isCImm()) 1854 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(), 1855 isUnsignedDIType(DD, DV.getType())); 1856 1857 DV.setDIE(VariableDie); 1858 return VariableDie; 1859 } else { 1860 // .. else use frame index. 1861 int FI = DV.getFrameIndex(); 1862 if (FI != ~0) { 1863 unsigned FrameReg = 0; 1864 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering(); 1865 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg); 1866 MachineLocation Location(FrameReg, Offset); 1867 addVariableAddress(DV, VariableDie, Location); 1868 } 1869 } 1870 1871 DV.setDIE(VariableDie); 1872 return VariableDie; 1873 } 1874 1875 /// constructMemberDIE - Construct member DIE from DIDerivedType. 1876 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) { 1877 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer); 1878 StringRef Name = DT.getName(); 1879 if (!Name.empty()) 1880 addString(MemberDie, dwarf::DW_AT_name, Name); 1881 1882 addType(MemberDie, resolve(DT.getTypeDerivedFrom())); 1883 1884 addSourceLine(MemberDie, DT); 1885 1886 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock(); 1887 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 1888 1889 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) { 1890 1891 // For C++, virtual base classes are not at fixed offset. Use following 1892 // expression to extract appropriate offset from vtable. 1893 // BaseAddr = ObAddr + *((*ObAddr) - Offset) 1894 1895 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock(); 1896 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup); 1897 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 1898 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 1899 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits()); 1900 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus); 1901 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 1902 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus); 1903 1904 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie); 1905 } else { 1906 uint64_t Size = DT.getSizeInBits(); 1907 uint64_t FieldSize = getBaseTypeSize(DD, DT); 1908 uint64_t OffsetInBytes; 1909 1910 if (Size != FieldSize) { 1911 // Handle bitfield. 1912 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, 1913 getBaseTypeSize(DD, DT) >> 3); 1914 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits()); 1915 1916 uint64_t Offset = DT.getOffsetInBits(); 1917 uint64_t AlignMask = ~(DT.getAlignInBits() - 1); 1918 uint64_t HiMark = (Offset + FieldSize) & AlignMask; 1919 uint64_t FieldOffset = (HiMark - FieldSize); 1920 Offset -= FieldOffset; 1921 1922 // Maybe we need to work from the other end. 1923 if (Asm->getDataLayout().isLittleEndian()) 1924 Offset = FieldSize - (Offset + Size); 1925 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset); 1926 1927 // Here WD_AT_data_member_location points to the anonymous 1928 // field that includes this bit field. 1929 OffsetInBytes = FieldOffset >> 3; 1930 } else 1931 // This is not a bitfield. 1932 OffsetInBytes = DT.getOffsetInBits() >> 3; 1933 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None, OffsetInBytes); 1934 } 1935 1936 if (DT.isProtected()) 1937 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1938 dwarf::DW_ACCESS_protected); 1939 else if (DT.isPrivate()) 1940 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1941 dwarf::DW_ACCESS_private); 1942 // Otherwise C++ member and base classes are considered public. 1943 else 1944 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1945 dwarf::DW_ACCESS_public); 1946 if (DT.isVirtual()) 1947 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, 1948 dwarf::DW_VIRTUALITY_virtual); 1949 1950 // Objective-C properties. 1951 if (MDNode *PNode = DT.getObjCProperty()) 1952 if (DIEEntry *PropertyDie = getDIEEntry(PNode)) 1953 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4, 1954 PropertyDie); 1955 1956 if (DT.isArtificial()) 1957 addFlag(MemberDie, dwarf::DW_AT_artificial); 1958 } 1959 1960 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member. 1961 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) { 1962 if (!DT.Verify()) 1963 return NULL; 1964 1965 // Construct the context before querying for the existence of the DIE in case 1966 // such construction creates the DIE. 1967 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext())); 1968 assert(dwarf::isType(ContextDIE->getTag()) && 1969 "Static member should belong to a type."); 1970 1971 DIE *StaticMemberDIE = getDIE(DT); 1972 if (StaticMemberDIE) 1973 return StaticMemberDIE; 1974 1975 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT); 1976 1977 DIType Ty = resolve(DT.getTypeDerivedFrom()); 1978 1979 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName()); 1980 addType(StaticMemberDIE, Ty); 1981 addSourceLine(StaticMemberDIE, DT); 1982 addFlag(StaticMemberDIE, dwarf::DW_AT_external); 1983 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration); 1984 1985 // FIXME: We could omit private if the parent is a class_type, and 1986 // public if the parent is something else. 1987 if (DT.isProtected()) 1988 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1989 dwarf::DW_ACCESS_protected); 1990 else if (DT.isPrivate()) 1991 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1992 dwarf::DW_ACCESS_private); 1993 else 1994 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1995 dwarf::DW_ACCESS_public); 1996 1997 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant())) 1998 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty)); 1999 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant())) 2000 addConstantFPValue(StaticMemberDIE, CFP); 2001 2002 return StaticMemberDIE; 2003 } 2004 2005 void DwarfUnit::emitHeader(const MCSection *ASection, 2006 const MCSymbol *ASectionSym) const { 2007 Asm->OutStreamer.AddComment("DWARF version number"); 2008 Asm->EmitInt16(DD->getDwarfVersion()); 2009 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section"); 2010 // We share one abbreviations table across all units so it's always at the 2011 // start of the section. Use a relocatable offset where needed to ensure 2012 // linking doesn't invalidate that offset. 2013 Asm->EmitSectionOffset(ASectionSym, ASectionSym); 2014 Asm->OutStreamer.AddComment("Address Size (in bytes)"); 2015 Asm->EmitInt8(Asm->getDataLayout().getPointerSize()); 2016 } 2017 2018 DwarfCompileUnit::~DwarfCompileUnit() {} 2019 DwarfTypeUnit::~DwarfTypeUnit() {} 2020 2021 void DwarfTypeUnit::emitHeader(const MCSection *ASection, 2022 const MCSymbol *ASectionSym) const { 2023 DwarfUnit::emitHeader(ASection, ASectionSym); 2024 Asm->OutStreamer.AddComment("Type Signature"); 2025 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature)); 2026 Asm->OutStreamer.AddComment("Type DIE Offset"); 2027 Asm->OutStreamer.EmitIntValue(Ty->getOffset(), sizeof(Ty->getOffset())); 2028 } 2029 2030 void DwarfTypeUnit::initSection(const MCSection *Section) { 2031 assert(!this->Section); 2032 this->Section = Section; 2033 // Since each type unit is contained in its own COMDAT section, the begin 2034 // label and the section label are the same. Using the begin label emission in 2035 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but 2036 // the only other alternative of lazily constructing start-of-section labels 2037 // and storing a mapping in DwarfDebug (or AsmPrinter). 2038 this->SectionSym = this->LabelBegin = 2039 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID()); 2040 this->LabelEnd = 2041 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID()); 2042 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID()); 2043 } 2044