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