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