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