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