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