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