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