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