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