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