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