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