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