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