b19b576cdf3d56b15c5194b9cac941354116f385
[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) == dwarf::DW_OP_plus) {
611       assert(!DV.getVariable().isIndirect() &&
612              "double indirection not handled");
613       // If first address element is OpPlus then emit
614       // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
615       addRegisterOffset(*Loc, Location.getReg(), DV.getAddrElement(1));
616       i = 2;
617     } else if (N >= 2 && DV.getAddrElement(0) == dwarf::DW_OP_deref) {
618       assert(!DV.getVariable().isIndirect() &&
619              "double indirection not handled");
620       addRegisterOpPiece(*Loc, Location.getReg(),
621                          DV.getExpression().getPieceSize(),
622                          DV.getExpression().getPieceOffset());
623       i = 3;
624     } else
625       addRegisterOpPiece(*Loc, Location.getReg());
626   } else
627     addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
628
629   for (; i < N; ++i) {
630     uint64_t Element = DV.getAddrElement(i);
631     if (Element == dwarf::DW_OP_plus) {
632       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
633       addUInt(*Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
634
635     } else if (Element == dwarf::DW_OP_deref) {
636       if (!Location.isReg())
637         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
638
639     } else if (Element == dwarf::DW_OP_piece) {
640       const unsigned SizeOfByte = 8;
641       unsigned PieceOffsetInBits = DV.getAddrElement(++i)*SizeOfByte;
642       unsigned PieceSizeInBits = DV.getAddrElement(++i)*SizeOfByte;
643       // Emit DW_OP_bit_piece Size Offset.
644       assert(PieceSizeInBits > 0 && "piece has zero size");
645       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
646       addUInt(*Loc, dwarf::DW_FORM_udata, PieceSizeInBits);
647       addUInt(*Loc, dwarf::DW_FORM_udata, PieceOffsetInBits);
648
649     } else
650       llvm_unreachable("unknown DIBuilder Opcode");
651   }
652
653   // Now attach the location information to the DIE.
654   addBlock(Die, Attribute, Loc);
655 }
656
657 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
658    VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
659    gives the variable VarName either the struct, or a pointer to the struct, as
660    its type.  This is necessary for various behind-the-scenes things the
661    compiler needs to do with by-reference variables in Blocks.
662
663    However, as far as the original *programmer* is concerned, the variable
664    should still have type 'SomeType', as originally declared.
665
666    The function getBlockByrefType dives into the __Block_byref_x_VarName
667    struct to find the original type of the variable, which is then assigned to
668    the variable's Debug Information Entry as its real type.  So far, so good.
669    However now the debugger will expect the variable VarName to have the type
670    SomeType.  So we need the location attribute for the variable to be an
671    expression that explains to the debugger how to navigate through the
672    pointers and struct to find the actual variable of type SomeType.
673
674    The following function does just that.  We start by getting
675    the "normal" location for the variable. This will be the location
676    of either the struct __Block_byref_x_VarName or the pointer to the
677    struct __Block_byref_x_VarName.
678
679    The struct will look something like:
680
681    struct __Block_byref_x_VarName {
682      ... <various fields>
683      struct __Block_byref_x_VarName *forwarding;
684      ... <various other fields>
685      SomeType VarName;
686      ... <maybe more fields>
687    };
688
689    If we are given the struct directly (as our starting point) we
690    need to tell the debugger to:
691
692    1).  Add the offset of the forwarding field.
693
694    2).  Follow that pointer to get the real __Block_byref_x_VarName
695    struct to use (the real one may have been copied onto the heap).
696
697    3).  Add the offset for the field VarName, to find the actual variable.
698
699    If we started with a pointer to the struct, then we need to
700    dereference that pointer first, before the other steps.
701    Translating this into DWARF ops, we will need to append the following
702    to the current location description for the variable:
703
704    DW_OP_deref                    -- optional, if we start with a pointer
705    DW_OP_plus_uconst <forward_fld_offset>
706    DW_OP_deref
707    DW_OP_plus_uconst <varName_fld_offset>
708
709    That is what this function does.  */
710
711 /// addBlockByrefAddress - Start with the address based on the location
712 /// provided, and generate the DWARF information necessary to find the
713 /// actual Block variable (navigating the Block struct) based on the
714 /// starting location.  Add the DWARF information to the die.  For
715 /// more information, read large comment just above here.
716 ///
717 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
718                                      dwarf::Attribute Attribute,
719                                      const MachineLocation &Location) {
720   DIType Ty = DV.getType();
721   DIType TmpTy = Ty;
722   uint16_t Tag = Ty.getTag();
723   bool isPointer = false;
724
725   StringRef varName = DV.getName();
726
727   if (Tag == dwarf::DW_TAG_pointer_type) {
728     DIDerivedType DTy(Ty);
729     TmpTy = resolve(DTy.getTypeDerivedFrom());
730     isPointer = true;
731   }
732
733   DICompositeType blockStruct(TmpTy);
734
735   // Find the __forwarding field and the variable field in the __Block_byref
736   // struct.
737   DIArray Fields = blockStruct.getElements();
738   DIDerivedType varField;
739   DIDerivedType forwardingField;
740
741   for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
742     DIDerivedType DT(Fields.getElement(i));
743     StringRef fieldName = DT.getName();
744     if (fieldName == "__forwarding")
745       forwardingField = DT;
746     else if (fieldName == varName)
747       varField = DT;
748   }
749
750   // Get the offsets for the forwarding field and the variable field.
751   unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
752   unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
753
754   // Decode the original location, and use that as the start of the byref
755   // variable's location.
756   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
757
758   if (Location.isReg())
759     addRegisterOpPiece(*Loc, Location.getReg());
760   else
761     addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
762
763   // If we started with a pointer to the __Block_byref... struct, then
764   // the first thing we need to do is dereference the pointer (DW_OP_deref).
765   if (isPointer)
766     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
767
768   // Next add the offset for the '__forwarding' field:
769   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
770   // adding the offset if it's 0.
771   if (forwardingFieldOffset > 0) {
772     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
773     addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
774   }
775
776   // Now dereference the __forwarding field to get to the real __Block_byref
777   // struct:  DW_OP_deref.
778   addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
779
780   // Now that we've got the real __Block_byref... struct, add the offset
781   // for the variable's field to get to the location of the actual variable:
782   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
783   if (varFieldOffset > 0) {
784     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
785     addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
786   }
787
788   // Now attach the location information to the DIE.
789   addBlock(Die, Attribute, Loc);
790 }
791
792 /// Return true if type encoding is unsigned.
793 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
794   DIDerivedType DTy(Ty);
795   if (DTy.isDerivedType()) {
796     dwarf::Tag T = (dwarf::Tag)Ty.getTag();
797     // Encode pointer constants as unsigned bytes. This is used at least for
798     // null pointer constant emission.
799     // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
800     // here, but accept them for now due to a bug in SROA producing bogus
801     // dbg.values.
802     if (T == dwarf::DW_TAG_pointer_type ||
803         T == dwarf::DW_TAG_ptr_to_member_type ||
804         T == dwarf::DW_TAG_reference_type ||
805         T == dwarf::DW_TAG_rvalue_reference_type)
806       return true;
807     assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
808            T == dwarf::DW_TAG_volatile_type ||
809            T == dwarf::DW_TAG_restrict_type ||
810            T == dwarf::DW_TAG_enumeration_type);
811     if (DITypeRef Deriv = DTy.getTypeDerivedFrom())
812       return isUnsignedDIType(DD, DD->resolve(Deriv));
813     // FIXME: Enums without a fixed underlying type have unknown signedness
814     // here, leading to incorrectly emitted constants.
815     assert(DTy.getTag() == dwarf::DW_TAG_enumeration_type);
816     return false;
817   }
818
819   DIBasicType BTy(Ty);
820   assert(BTy.isBasicType());
821   unsigned Encoding = BTy.getEncoding();
822   assert((Encoding == dwarf::DW_ATE_unsigned ||
823           Encoding == dwarf::DW_ATE_unsigned_char ||
824           Encoding == dwarf::DW_ATE_signed ||
825           Encoding == dwarf::DW_ATE_signed_char ||
826           Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean) &&
827          "Unsupported encoding");
828   return (Encoding == dwarf::DW_ATE_unsigned ||
829           Encoding == dwarf::DW_ATE_unsigned_char ||
830           Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean);
831 }
832
833 /// If this type is derived from a base type then return base type size.
834 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
835   unsigned Tag = Ty.getTag();
836
837   if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
838       Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
839       Tag != dwarf::DW_TAG_restrict_type)
840     return Ty.getSizeInBits();
841
842   DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
843
844   // If this type is not derived from any type or the type is a declaration then
845   // take conservative approach.
846   if (!BaseType.isValid() || BaseType.isForwardDecl())
847     return Ty.getSizeInBits();
848
849   // If this is a derived type, go ahead and get the base type, unless it's a
850   // reference then it's just the size of the field. Pointer types have no need
851   // of this since they're a different type of qualification on the type.
852   if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
853       BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
854     return Ty.getSizeInBits();
855
856   if (BaseType.isDerivedType())
857     return getBaseTypeSize(DD, DIDerivedType(BaseType));
858
859   return BaseType.getSizeInBits();
860 }
861
862 /// addConstantFPValue - Add constant value entry in variable DIE.
863 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
864   assert(MO.isFPImm() && "Invalid machine operand!");
865   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
866   APFloat FPImm = MO.getFPImm()->getValueAPF();
867
868   // Get the raw data form of the floating point.
869   const APInt FltVal = FPImm.bitcastToAPInt();
870   const char *FltPtr = (const char *)FltVal.getRawData();
871
872   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
873   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
874   int Incr = (LittleEndian ? 1 : -1);
875   int Start = (LittleEndian ? 0 : NumBytes - 1);
876   int Stop = (LittleEndian ? NumBytes : -1);
877
878   // Output the constant to DWARF one byte at a time.
879   for (; Start != Stop; Start += Incr)
880     addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
881
882   addBlock(Die, dwarf::DW_AT_const_value, Block);
883 }
884
885 /// addConstantFPValue - Add constant value entry in variable DIE.
886 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
887   // Pass this down to addConstantValue as an unsigned bag of bits.
888   addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
889 }
890
891 /// addConstantValue - Add constant value entry in variable DIE.
892 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, DIType Ty) {
893   addConstantValue(Die, CI->getValue(), Ty);
894 }
895
896 /// addConstantValue - Add constant value entry in variable DIE.
897 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
898                                  DIType Ty) {
899   assert(MO.isImm() && "Invalid machine operand!");
900
901   addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
902 }
903
904 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
905   // FIXME: This is a bit conservative/simple - it emits negative values always
906   // sign extended to 64 bits rather than minimizing the number of bytes.
907   addUInt(Die, dwarf::DW_AT_const_value,
908           Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
909 }
910
911 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, DIType Ty) {
912   addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
913 }
914
915 // addConstantValue - Add constant value entry in variable DIE.
916 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
917   unsigned CIBitWidth = Val.getBitWidth();
918   if (CIBitWidth <= 64) {
919     addConstantValue(Die, Unsigned,
920                      Unsigned ? Val.getZExtValue() : Val.getSExtValue());
921     return;
922   }
923
924   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
925
926   // Get the raw data form of the large APInt.
927   const uint64_t *Ptr64 = Val.getRawData();
928
929   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
930   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
931
932   // Output the constant to DWARF one byte at a time.
933   for (int i = 0; i < NumBytes; i++) {
934     uint8_t c;
935     if (LittleEndian)
936       c = Ptr64[i / 8] >> (8 * (i & 7));
937     else
938       c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
939     addUInt(*Block, dwarf::DW_FORM_data1, c);
940   }
941
942   addBlock(Die, dwarf::DW_AT_const_value, Block);
943 }
944
945 /// addTemplateParams - Add template parameters into buffer.
946 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
947   // Add template parameters.
948   for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
949     DIDescriptor Element = TParams.getElement(i);
950     if (Element.isTemplateTypeParameter())
951       constructTemplateTypeParameterDIE(Buffer,
952                                         DITemplateTypeParameter(Element));
953     else if (Element.isTemplateValueParameter())
954       constructTemplateValueParameterDIE(Buffer,
955                                          DITemplateValueParameter(Element));
956   }
957 }
958
959 /// getOrCreateContextDIE - Get context owner's DIE.
960 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
961   if (!Context || Context.isFile())
962     return &getUnitDie();
963   if (Context.isType())
964     return getOrCreateTypeDIE(DIType(Context));
965   if (Context.isNameSpace())
966     return getOrCreateNameSpace(DINameSpace(Context));
967   if (Context.isSubprogram())
968     return getOrCreateSubprogramDIE(DISubprogram(Context));
969   return getDIE(Context);
970 }
971
972 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
973   DIScope Context = resolve(Ty.getContext());
974   DIE *ContextDIE = getOrCreateContextDIE(Context);
975
976   if (DIE *TyDIE = getDIE(Ty))
977     return TyDIE;
978
979   // Create new type.
980   DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
981
982   constructTypeDIE(TyDIE, Ty);
983
984   updateAcceleratorTables(Context, Ty, TyDIE);
985   return &TyDIE;
986 }
987
988 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
989 /// given DIType.
990 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
991   if (!TyNode)
992     return nullptr;
993
994   DIType Ty(TyNode);
995   assert(Ty.isType());
996   assert(Ty == resolve(Ty.getRef()) &&
997          "type was not uniqued, possible ODR violation.");
998
999   // DW_TAG_restrict_type is not supported in DWARF2
1000   if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
1001     return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
1002
1003   // Construct the context before querying for the existence of the DIE in case
1004   // such construction creates the DIE.
1005   DIScope Context = resolve(Ty.getContext());
1006   DIE *ContextDIE = getOrCreateContextDIE(Context);
1007   assert(ContextDIE);
1008
1009   if (DIE *TyDIE = getDIE(Ty))
1010     return TyDIE;
1011
1012   // Create new type.
1013   DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
1014
1015   updateAcceleratorTables(Context, Ty, TyDIE);
1016
1017   if (Ty.isBasicType())
1018     constructTypeDIE(TyDIE, DIBasicType(Ty));
1019   else if (Ty.isCompositeType()) {
1020     DICompositeType CTy(Ty);
1021     if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
1022       if (MDString *TypeId = CTy.getIdentifier()) {
1023         DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
1024         // Skip updating the accelerator tables since this is not the full type.
1025         return &TyDIE;
1026       }
1027     constructTypeDIE(TyDIE, CTy);
1028   } else {
1029     assert(Ty.isDerivedType() && "Unknown kind of DIType");
1030     constructTypeDIE(TyDIE, DIDerivedType(Ty));
1031   }
1032
1033   return &TyDIE;
1034 }
1035
1036 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1037                                         const DIE &TyDIE) {
1038   if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1039     bool IsImplementation = 0;
1040     if (Ty.isCompositeType()) {
1041       DICompositeType CT(Ty);
1042       // A runtime language of 0 actually means C/C++ and that any
1043       // non-negative value is some version of Objective-C/C++.
1044       IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1045     }
1046     unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1047     DD->addAccelType(Ty.getName(), TyDIE, Flags);
1048
1049     if ((!Context || Context.isCompileUnit() || Context.isFile() ||
1050          Context.isNameSpace()) &&
1051         getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
1052       GlobalTypes[getParentContextString(Context) + Ty.getName().str()] =
1053           &TyDIE;
1054   }
1055 }
1056
1057 /// addType - Add a new type attribute to the specified entity.
1058 void DwarfUnit::addType(DIE &Entity, DIType Ty, dwarf::Attribute Attribute) {
1059   assert(Ty && "Trying to add a type that doesn't exist?");
1060
1061   // Check for pre-existence.
1062   DIEEntry *Entry = getDIEEntry(Ty);
1063   // If it exists then use the existing value.
1064   if (Entry) {
1065     addDIEEntry(Entity, Attribute, Entry);
1066     return;
1067   }
1068
1069   // Construct type.
1070   DIE *Buffer = getOrCreateTypeDIE(Ty);
1071
1072   // Set up proxy.
1073   Entry = createDIEEntry(*Buffer);
1074   insertDIEEntry(Ty, Entry);
1075   addDIEEntry(Entity, Attribute, Entry);
1076 }
1077
1078 /// addGlobalName - Add a new global name to the compile unit.
1079 void DwarfUnit::addGlobalName(StringRef Name, DIE &Die, DIScope Context) {
1080   if (getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1081     return;
1082   std::string FullName = getParentContextString(Context) + Name.str();
1083   GlobalNames[FullName] = &Die;
1084 }
1085
1086 /// getParentContextString - Walks the metadata parent chain in a language
1087 /// specific manner (using the compile unit language) and returns
1088 /// it as a string. This is done at the metadata level because DIEs may
1089 /// not currently have been added to the parent context and walking the
1090 /// DIEs looking for names is more expensive than walking the metadata.
1091 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1092   if (!Context)
1093     return "";
1094
1095   // FIXME: Decide whether to implement this for non-C++ languages.
1096   if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1097     return "";
1098
1099   std::string CS;
1100   SmallVector<DIScope, 1> Parents;
1101   while (!Context.isCompileUnit()) {
1102     Parents.push_back(Context);
1103     if (Context.getContext())
1104       Context = resolve(Context.getContext());
1105     else
1106       // Structure, etc types will have a NULL context if they're at the top
1107       // level.
1108       break;
1109   }
1110
1111   // Reverse iterate over our list to go from the outermost construct to the
1112   // innermost.
1113   for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1114                                                   E = Parents.rend();
1115        I != E; ++I) {
1116     DIScope Ctx = *I;
1117     StringRef Name = Ctx.getName();
1118     if (Name.empty() && Ctx.isNameSpace())
1119       Name = "(anonymous namespace)";
1120     if (!Name.empty()) {
1121       CS += Name;
1122       CS += "::";
1123     }
1124   }
1125   return CS;
1126 }
1127
1128 /// constructTypeDIE - Construct basic type die from DIBasicType.
1129 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1130   // Get core information.
1131   StringRef Name = BTy.getName();
1132   // Add name if not anonymous or intermediate type.
1133   if (!Name.empty())
1134     addString(Buffer, dwarf::DW_AT_name, Name);
1135
1136   // An unspecified type only has a name attribute.
1137   if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1138     return;
1139
1140   addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1141           BTy.getEncoding());
1142
1143   uint64_t Size = BTy.getSizeInBits() >> 3;
1144   addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1145 }
1146
1147 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1148 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1149   // Get core information.
1150   StringRef Name = DTy.getName();
1151   uint64_t Size = DTy.getSizeInBits() >> 3;
1152   uint16_t Tag = Buffer.getTag();
1153
1154   // Map to main type, void will not have a type.
1155   DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1156   if (FromTy)
1157     addType(Buffer, FromTy);
1158
1159   // Add name if not anonymous or intermediate type.
1160   if (!Name.empty())
1161     addString(Buffer, dwarf::DW_AT_name, Name);
1162
1163   // Add size if non-zero (derived types might be zero-sized.)
1164   if (Size && Tag != dwarf::DW_TAG_pointer_type)
1165     addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1166
1167   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1168     addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1169                 *getOrCreateTypeDIE(resolve(DTy.getClassType())));
1170   // Add source line info if available and TyDesc is not a forward declaration.
1171   if (!DTy.isForwardDecl())
1172     addSourceLine(Buffer, DTy);
1173 }
1174
1175 /// constructSubprogramArguments - Construct function argument DIEs.
1176 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeArray Args) {
1177   for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1178     DIType Ty = resolve(Args.getElement(i));
1179     if (!Ty) {
1180       assert(i == N-1 && "Unspecified parameter must be the last argument");
1181       createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1182     } else {
1183       DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1184       addType(Arg, DIType(Ty));
1185       if (DIType(Ty).isArtificial())
1186         addFlag(Arg, dwarf::DW_AT_artificial);
1187     }
1188   }
1189 }
1190
1191 /// constructTypeDIE - Construct type DIE from DICompositeType.
1192 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1193   // Add name if not anonymous or intermediate type.
1194   StringRef Name = CTy.getName();
1195
1196   uint64_t Size = CTy.getSizeInBits() >> 3;
1197   uint16_t Tag = Buffer.getTag();
1198
1199   switch (Tag) {
1200   case dwarf::DW_TAG_array_type:
1201     constructArrayTypeDIE(Buffer, CTy);
1202     break;
1203   case dwarf::DW_TAG_enumeration_type:
1204     constructEnumTypeDIE(Buffer, CTy);
1205     break;
1206   case dwarf::DW_TAG_subroutine_type: {
1207     // Add return type. A void return won't have a type.
1208     DITypeArray Elements = DISubroutineType(CTy).getTypeArray();
1209     DIType RTy(resolve(Elements.getElement(0)));
1210     if (RTy)
1211       addType(Buffer, RTy);
1212
1213     bool isPrototyped = true;
1214     if (Elements.getNumElements() == 2 &&
1215         !Elements.getElement(1))
1216       isPrototyped = false;
1217
1218     constructSubprogramArguments(Buffer, Elements);
1219
1220     // Add prototype flag if we're dealing with a C language and the
1221     // function has been prototyped.
1222     uint16_t Language = getLanguage();
1223     if (isPrototyped &&
1224         (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1225          Language == dwarf::DW_LANG_ObjC))
1226       addFlag(Buffer, dwarf::DW_AT_prototyped);
1227
1228     if (CTy.isLValueReference())
1229       addFlag(Buffer, dwarf::DW_AT_reference);
1230
1231     if (CTy.isRValueReference())
1232       addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
1233   } break;
1234   case dwarf::DW_TAG_structure_type:
1235   case dwarf::DW_TAG_union_type:
1236   case dwarf::DW_TAG_class_type: {
1237     // Add elements to structure type.
1238     DIArray Elements = CTy.getElements();
1239     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1240       DIDescriptor Element = Elements.getElement(i);
1241       if (Element.isSubprogram())
1242         getOrCreateSubprogramDIE(DISubprogram(Element));
1243       else if (Element.isDerivedType()) {
1244         DIDerivedType DDTy(Element);
1245         if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1246           DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1247           addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1248                   dwarf::DW_AT_friend);
1249         } else if (DDTy.isStaticMember()) {
1250           getOrCreateStaticMemberDIE(DDTy);
1251         } else {
1252           constructMemberDIE(Buffer, DDTy);
1253         }
1254       } else if (Element.isObjCProperty()) {
1255         DIObjCProperty Property(Element);
1256         DIE &ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1257         StringRef PropertyName = Property.getObjCPropertyName();
1258         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1259         if (Property.getType())
1260           addType(ElemDie, Property.getType());
1261         addSourceLine(ElemDie, Property);
1262         StringRef GetterName = Property.getObjCPropertyGetterName();
1263         if (!GetterName.empty())
1264           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1265         StringRef SetterName = Property.getObjCPropertySetterName();
1266         if (!SetterName.empty())
1267           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1268         unsigned PropertyAttributes = 0;
1269         if (Property.isReadOnlyObjCProperty())
1270           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1271         if (Property.isReadWriteObjCProperty())
1272           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1273         if (Property.isAssignObjCProperty())
1274           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1275         if (Property.isRetainObjCProperty())
1276           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1277         if (Property.isCopyObjCProperty())
1278           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1279         if (Property.isNonAtomicObjCProperty())
1280           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1281         if (PropertyAttributes)
1282           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1283                   PropertyAttributes);
1284
1285         DIEEntry *Entry = getDIEEntry(Element);
1286         if (!Entry) {
1287           Entry = createDIEEntry(ElemDie);
1288           insertDIEEntry(Element, Entry);
1289         }
1290       } else
1291         continue;
1292     }
1293
1294     if (CTy.isAppleBlockExtension())
1295       addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1296
1297     DICompositeType ContainingType(resolve(CTy.getContainingType()));
1298     if (ContainingType)
1299       addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1300                   *getOrCreateTypeDIE(ContainingType));
1301
1302     if (CTy.isObjcClassComplete())
1303       addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1304
1305     // Add template parameters to a class, structure or union types.
1306     // FIXME: The support isn't in the metadata for this yet.
1307     if (Tag == dwarf::DW_TAG_class_type ||
1308         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1309       addTemplateParams(Buffer, CTy.getTemplateParams());
1310
1311     break;
1312   }
1313   default:
1314     break;
1315   }
1316
1317   // Add name if not anonymous or intermediate type.
1318   if (!Name.empty())
1319     addString(Buffer, dwarf::DW_AT_name, Name);
1320
1321   if (Tag == dwarf::DW_TAG_enumeration_type ||
1322       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1323       Tag == dwarf::DW_TAG_union_type) {
1324     // Add size if non-zero (derived types might be zero-sized.)
1325     // TODO: Do we care about size for enum forward declarations?
1326     if (Size)
1327       addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1328     else if (!CTy.isForwardDecl())
1329       // Add zero size if it is not a forward declaration.
1330       addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1331
1332     // If we're a forward decl, say so.
1333     if (CTy.isForwardDecl())
1334       addFlag(Buffer, dwarf::DW_AT_declaration);
1335
1336     // Add source line info if available.
1337     if (!CTy.isForwardDecl())
1338       addSourceLine(Buffer, CTy);
1339
1340     // No harm in adding the runtime language to the declaration.
1341     unsigned RLang = CTy.getRunTimeLang();
1342     if (RLang)
1343       addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1344               RLang);
1345   }
1346 }
1347
1348 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1349 /// DITemplateTypeParameter.
1350 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1351                                                   DITemplateTypeParameter TP) {
1352   DIE &ParamDIE =
1353       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1354   // Add the type if it exists, it could be void and therefore no type.
1355   if (TP.getType())
1356     addType(ParamDIE, resolve(TP.getType()));
1357   if (!TP.getName().empty())
1358     addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1359 }
1360
1361 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1362 /// DITemplateValueParameter.
1363 void
1364 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1365                                               DITemplateValueParameter VP) {
1366   DIE &ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1367
1368   // Add the type if there is one, template template and template parameter
1369   // packs will not have a type.
1370   if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1371     addType(ParamDIE, resolve(VP.getType()));
1372   if (!VP.getName().empty())
1373     addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1374   if (Value *Val = VP.getValue()) {
1375     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1376       addConstantValue(ParamDIE, CI, resolve(VP.getType()));
1377     else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1378       // For declaration non-type template parameters (such as global values and
1379       // functions)
1380       DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1381       addOpAddress(*Loc, Asm->getSymbol(GV));
1382       // Emit DW_OP_stack_value to use the address as the immediate value of the
1383       // parameter, rather than a pointer to it.
1384       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1385       addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1386     } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1387       assert(isa<MDString>(Val));
1388       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1389                 cast<MDString>(Val)->getString());
1390     } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1391       assert(isa<MDNode>(Val));
1392       DIArray A(cast<MDNode>(Val));
1393       addTemplateParams(ParamDIE, A);
1394     }
1395   }
1396 }
1397
1398 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1399 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1400   // Construct the context before querying for the existence of the DIE in case
1401   // such construction creates the DIE.
1402   DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1403
1404   if (DIE *NDie = getDIE(NS))
1405     return NDie;
1406   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1407
1408   StringRef Name = NS.getName();
1409   if (!Name.empty())
1410     addString(NDie, dwarf::DW_AT_name, NS.getName());
1411   else
1412     Name = "(anonymous namespace)";
1413   DD->addAccelNamespace(Name, NDie);
1414   addGlobalName(Name, NDie, NS.getContext());
1415   addSourceLine(NDie, NS);
1416   return &NDie;
1417 }
1418
1419 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1420 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1421   // Construct the context before querying for the existence of the DIE in case
1422   // such construction creates the DIE (as is the case for member function
1423   // declarations).
1424   DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1425
1426   if (DIE *SPDie = getDIE(SP))
1427     return SPDie;
1428
1429   if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1430     // Add subprogram definitions to the CU die directly.
1431     ContextDIE = &getUnitDie();
1432     // Build the decl now to ensure it precedes the definition.
1433     getOrCreateSubprogramDIE(SPDecl);
1434   }
1435
1436   // DW_TAG_inlined_subroutine may refer to this DIE.
1437   DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1438
1439   // Stop here and fill this in later, depending on whether or not this
1440   // subprogram turns out to have inlined instances or not.
1441   if (SP.isDefinition())
1442     return &SPDie;
1443
1444   applySubprogramAttributes(SP, SPDie);
1445   return &SPDie;
1446 }
1447
1448 void DwarfUnit::applySubprogramAttributesToDefinition(DISubprogram SP, DIE &SPDie) {
1449   DISubprogram SPDecl = SP.getFunctionDeclaration();
1450   DIScope Context = resolve(SPDecl ? SPDecl.getContext() : SP.getContext());
1451   applySubprogramAttributes(SP, SPDie);
1452   addGlobalName(SP.getName(), SPDie, Context);
1453 }
1454
1455 void DwarfUnit::applySubprogramAttributes(DISubprogram SP, DIE &SPDie) {
1456   DIE *DeclDie = nullptr;
1457   StringRef DeclLinkageName;
1458   if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1459     DeclDie = getDIE(SPDecl);
1460     assert(DeclDie && "This DIE should've already been constructed when the "
1461                       "definition DIE was created in "
1462                       "getOrCreateSubprogramDIE");
1463     DeclLinkageName = SPDecl.getLinkageName();
1464   }
1465
1466   // Add function template parameters.
1467   addTemplateParams(SPDie, SP.getTemplateParams());
1468
1469   // Add the linkage name if we have one and it isn't in the Decl.
1470   StringRef LinkageName = SP.getLinkageName();
1471   assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1472           LinkageName == DeclLinkageName) &&
1473          "decl has a linkage name and it is different");
1474   if (!LinkageName.empty() && DeclLinkageName.empty())
1475     addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1476               GlobalValue::getRealLinkageName(LinkageName));
1477
1478   if (DeclDie) {
1479     // Refer to the function declaration where all the other attributes will be
1480     // found.
1481     addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1482     return;
1483   }
1484
1485   // Constructors and operators for anonymous aggregates do not have names.
1486   if (!SP.getName().empty())
1487     addString(SPDie, dwarf::DW_AT_name, SP.getName());
1488
1489   // Skip the rest of the attributes under -gmlt to save space.
1490   if(getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1491     return;
1492
1493   addSourceLine(SPDie, SP);
1494
1495   // Add the prototype if we have a prototype and we have a C like
1496   // language.
1497   uint16_t Language = getLanguage();
1498   if (SP.isPrototyped() &&
1499       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1500        Language == dwarf::DW_LANG_ObjC))
1501     addFlag(SPDie, dwarf::DW_AT_prototyped);
1502
1503   DISubroutineType SPTy = SP.getType();
1504   assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1505          "the type of a subprogram should be a subroutine");
1506
1507   DITypeArray Args = SPTy.getTypeArray();
1508   // Add a return type. If this is a type like a C/C++ void type we don't add a
1509   // return type.
1510   if (resolve(Args.getElement(0)))
1511     addType(SPDie, DIType(resolve(Args.getElement(0))));
1512
1513   unsigned VK = SP.getVirtuality();
1514   if (VK) {
1515     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1516     DIELoc *Block = getDIELoc();
1517     addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1518     addUInt(*Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1519     addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1520     ContainingTypeMap.insert(
1521         std::make_pair(&SPDie, resolve(SP.getContainingType())));
1522   }
1523
1524   if (!SP.isDefinition()) {
1525     addFlag(SPDie, dwarf::DW_AT_declaration);
1526
1527     // Add arguments. Do not add arguments for subprogram definition. They will
1528     // be handled while processing variables.
1529     constructSubprogramArguments(SPDie, Args);
1530   }
1531
1532   if (SP.isArtificial())
1533     addFlag(SPDie, dwarf::DW_AT_artificial);
1534
1535   if (!SP.isLocalToUnit())
1536     addFlag(SPDie, dwarf::DW_AT_external);
1537
1538   if (SP.isOptimized())
1539     addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1540
1541   if (unsigned isa = Asm->getISAEncoding()) {
1542     addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1543   }
1544
1545   if (SP.isLValueReference())
1546     addFlag(SPDie, dwarf::DW_AT_reference);
1547
1548   if (SP.isRValueReference())
1549     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1550
1551   if (SP.isProtected())
1552     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1553             dwarf::DW_ACCESS_protected);
1554   else if (SP.isPrivate())
1555     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1556             dwarf::DW_ACCESS_private);
1557   else if (SP.isPublic())
1558     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1559             dwarf::DW_ACCESS_public);
1560
1561   if (SP.isExplicit())
1562     addFlag(SPDie, dwarf::DW_AT_explicit);
1563 }
1564
1565 void DwarfUnit::applyVariableAttributes(const DbgVariable &Var,
1566                                         DIE &VariableDie) {
1567   StringRef Name = Var.getName();
1568   if (!Name.empty())
1569     addString(VariableDie, dwarf::DW_AT_name, Name);
1570   addSourceLine(VariableDie, Var.getVariable());
1571   addType(VariableDie, Var.getType());
1572   if (Var.isArtificial())
1573     addFlag(VariableDie, dwarf::DW_AT_artificial);
1574 }
1575
1576 // Return const expression if value is a GEP to access merged global
1577 // constant. e.g.
1578 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1579 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1580   const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1581   if (!CE || CE->getNumOperands() != 3 ||
1582       CE->getOpcode() != Instruction::GetElementPtr)
1583     return nullptr;
1584
1585   // First operand points to a global struct.
1586   Value *Ptr = CE->getOperand(0);
1587   if (!isa<GlobalValue>(Ptr) ||
1588       !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1589     return nullptr;
1590
1591   // Second operand is zero.
1592   const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1593   if (!CI || !CI->isZero())
1594     return nullptr;
1595
1596   // Third operand is offset.
1597   if (!isa<ConstantInt>(CE->getOperand(2)))
1598     return nullptr;
1599
1600   return CE;
1601 }
1602
1603 /// getOrCreateGlobalVariableDIE - get or create global variable DIE.
1604 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(DIGlobalVariable GV) {
1605   // Check for pre-existence.
1606   if (DIE *Die = getDIE(GV))
1607     return Die;
1608
1609   assert(GV.isGlobalVariable());
1610
1611   DIScope GVContext = GV.getContext();
1612   DIType GTy = DD->resolve(GV.getType());
1613
1614   // If this is a static data member definition, some attributes belong
1615   // to the declaration DIE.
1616   DIE *VariableDIE = nullptr;
1617   bool IsStaticMember = false;
1618   DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1619   if (SDMDecl.Verify()) {
1620     assert(SDMDecl.isStaticMember() && "Expected static member decl");
1621     // We need the declaration DIE that is in the static member's class.
1622     VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1623     IsStaticMember = true;
1624   }
1625
1626   // If this is not a static data member definition, create the variable
1627   // DIE and add the initial set of attributes to it.
1628   if (!VariableDIE) {
1629     // Construct the context before querying for the existence of the DIE in
1630     // case such construction creates the DIE.
1631     DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1632
1633     // Add to map.
1634     VariableDIE = &createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1635
1636     // Add name and type.
1637     addString(*VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1638     addType(*VariableDIE, GTy);
1639
1640     // Add scoping info.
1641     if (!GV.isLocalToUnit())
1642       addFlag(*VariableDIE, dwarf::DW_AT_external);
1643
1644     // Add line number info.
1645     addSourceLine(*VariableDIE, GV);
1646   }
1647
1648   // Add location.
1649   bool addToAccelTable = false;
1650   DIE *VariableSpecDIE = nullptr;
1651   bool isGlobalVariable = GV.getGlobal() != nullptr;
1652   if (isGlobalVariable) {
1653     addToAccelTable = true;
1654     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1655     const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1656     if (GV.getGlobal()->isThreadLocal()) {
1657       // FIXME: Make this work with -gsplit-dwarf.
1658       unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1659       assert((PointerSize == 4 || PointerSize == 8) &&
1660              "Add support for other sizes if necessary");
1661       // Based on GCC's support for TLS:
1662       if (!DD->useSplitDwarf()) {
1663         // 1) Start with a constNu of the appropriate pointer size
1664         addUInt(*Loc, dwarf::DW_FORM_data1,
1665                 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1666         // 2) containing the (relocated) offset of the TLS variable
1667         //    within the module's TLS block.
1668         addExpr(*Loc, dwarf::DW_FORM_udata,
1669                 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
1670       } else {
1671         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1672         addUInt(*Loc, dwarf::DW_FORM_udata,
1673                 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
1674       }
1675       // 3) followed by a custom OP to make the debugger do a TLS lookup.
1676       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1677     } else {
1678       DD->addArangeLabel(SymbolCU(this, Sym));
1679       addOpAddress(*Loc, Sym);
1680     }
1681     // A static member's declaration is already flagged as such.
1682     if (!SDMDecl.Verify() && !GV.isDefinition())
1683       addFlag(*VariableDIE, dwarf::DW_AT_declaration);
1684     // Do not create specification DIE if context is either compile unit
1685     // or a subprogram.
1686     if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1687         !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1688       // Create specification DIE.
1689       VariableSpecDIE = &createAndAddDIE(dwarf::DW_TAG_variable, UnitDie);
1690       addDIEEntry(*VariableSpecDIE, dwarf::DW_AT_specification, *VariableDIE);
1691       addBlock(*VariableSpecDIE, dwarf::DW_AT_location, Loc);
1692       // A static member's declaration is already flagged as such.
1693       if (!SDMDecl.Verify())
1694         addFlag(*VariableDIE, dwarf::DW_AT_declaration);
1695     } else {
1696       addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
1697     }
1698     // Add the linkage name.
1699     StringRef LinkageName = GV.getLinkageName();
1700     if (!LinkageName.empty())
1701       // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1702       // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1703       // TAG_variable.
1704       addString(IsStaticMember && VariableSpecDIE ? *VariableSpecDIE
1705                                                   : *VariableDIE,
1706                 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
1707                                            : dwarf::DW_AT_MIPS_linkage_name,
1708                 GlobalValue::getRealLinkageName(LinkageName));
1709   } else if (const ConstantInt *CI =
1710                  dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1711     // AT_const_value was added when the static member was created. To avoid
1712     // emitting AT_const_value multiple times, we only add AT_const_value when
1713     // it is not a static member.
1714     if (!IsStaticMember)
1715       addConstantValue(*VariableDIE, CI, GTy);
1716   } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1717     addToAccelTable = true;
1718     // GV is a merged global.
1719     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1720     Value *Ptr = CE->getOperand(0);
1721     MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1722     DD->addArangeLabel(SymbolCU(this, Sym));
1723     addOpAddress(*Loc, Sym);
1724     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1725     SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1726     addUInt(*Loc, dwarf::DW_FORM_udata,
1727             Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1728     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1729     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
1730   }
1731
1732   DIE *ResultDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1733
1734   if (addToAccelTable) {
1735     DD->addAccelName(GV.getName(), *ResultDIE);
1736
1737     // If the linkage name is different than the name, go ahead and output
1738     // that as well into the name table.
1739     if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1740       DD->addAccelName(GV.getLinkageName(), *ResultDIE);
1741   }
1742
1743   addGlobalName(GV.getName(), *ResultDIE, GV.getContext());
1744   return ResultDIE;
1745 }
1746
1747 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1748 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1749   DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1750   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1751
1752   // The LowerBound value defines the lower bounds which is typically zero for
1753   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1754   // Count == -1 then the array is unbounded and we do not emit
1755   // DW_AT_lower_bound and DW_AT_count attributes.
1756   int64_t LowerBound = SR.getLo();
1757   int64_t DefaultLowerBound = getDefaultLowerBound();
1758   int64_t Count = SR.getCount();
1759
1760   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1761     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1762
1763   if (Count != -1)
1764     // FIXME: An unbounded array should reference the expression that defines
1765     // the array.
1766     addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1767 }
1768
1769 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1770 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1771   if (CTy.isVector())
1772     addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1773
1774   // Emit the element type.
1775   addType(Buffer, resolve(CTy.getTypeDerivedFrom()));
1776
1777   // Get an anonymous type for index type.
1778   // FIXME: This type should be passed down from the front end
1779   // as different languages may have different sizes for indexes.
1780   DIE *IdxTy = getIndexTyDie();
1781   if (!IdxTy) {
1782     // Construct an integer type to use for indexes.
1783     IdxTy = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1784     addString(*IdxTy, dwarf::DW_AT_name, "sizetype");
1785     addUInt(*IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1786     addUInt(*IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1787             dwarf::DW_ATE_unsigned);
1788     setIndexTyDie(IdxTy);
1789   }
1790
1791   // Add subranges to array type.
1792   DIArray Elements = CTy.getElements();
1793   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1794     DIDescriptor Element = Elements.getElement(i);
1795     if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1796       constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1797   }
1798 }
1799
1800 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1801 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1802   DIArray Elements = CTy.getElements();
1803
1804   // Add enumerators to enumeration type.
1805   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1806     DIEnumerator Enum(Elements.getElement(i));
1807     if (Enum.isEnumerator()) {
1808       DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1809       StringRef Name = Enum.getName();
1810       addString(Enumerator, dwarf::DW_AT_name, Name);
1811       int64_t Value = Enum.getEnumValue();
1812       addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1813               Value);
1814     }
1815   }
1816   DIType DTy = resolve(CTy.getTypeDerivedFrom());
1817   if (DTy) {
1818     addType(Buffer, DTy);
1819     addFlag(Buffer, dwarf::DW_AT_enum_class);
1820   }
1821 }
1822
1823 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1824 /// vtables.
1825 void DwarfUnit::constructContainingTypeDIEs() {
1826   for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1827                                                  CE = ContainingTypeMap.end();
1828        CI != CE; ++CI) {
1829     DIE &SPDie = *CI->first;
1830     DIDescriptor D(CI->second);
1831     if (!D)
1832       continue;
1833     DIE *NDie = getDIE(D);
1834     if (!NDie)
1835       continue;
1836     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1837   }
1838 }
1839
1840 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1841 std::unique_ptr<DIE> DwarfUnit::constructVariableDIE(DbgVariable &DV,
1842                                                      bool Abstract) {
1843   auto D = constructVariableDIEImpl(DV, Abstract);
1844   DV.setDIE(*D);
1845   return D;
1846 }
1847
1848 std::unique_ptr<DIE> DwarfUnit::constructVariableDIEImpl(const DbgVariable &DV,
1849                                                          bool Abstract) {
1850   // Define variable debug information entry.
1851   auto VariableDie = make_unique<DIE>(DV.getTag());
1852
1853   if (Abstract) {
1854     applyVariableAttributes(DV, *VariableDie);
1855     return VariableDie;
1856   }
1857
1858   // Add variable address.
1859
1860   unsigned Offset = DV.getDotDebugLocOffset();
1861   if (Offset != ~0U) {
1862     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
1863     return VariableDie;
1864   }
1865
1866   // Check if variable is described by a DBG_VALUE instruction.
1867   if (const MachineInstr *DVInsn = DV.getMInsn()) {
1868     assert(DVInsn->getNumOperands() == 4);
1869     if (DVInsn->getOperand(0).isReg()) {
1870       const MachineOperand RegOp = DVInsn->getOperand(0);
1871       // If the second operand is an immediate, this is an indirect value.
1872       if (DVInsn->getOperand(1).isImm()) {
1873         MachineLocation Location(RegOp.getReg(),
1874                                  DVInsn->getOperand(1).getImm());
1875         addVariableAddress(DV, *VariableDie, Location);
1876       } else if (RegOp.getReg())
1877         addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
1878     } else if (DVInsn->getOperand(0).isImm())
1879       addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
1880     else if (DVInsn->getOperand(0).isFPImm())
1881       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
1882     else if (DVInsn->getOperand(0).isCImm())
1883       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
1884                        DV.getType());
1885
1886     return VariableDie;
1887   }
1888
1889   // .. else use frame index.
1890   int FI = DV.getFrameIndex();
1891   if (FI != ~0) {
1892     unsigned FrameReg = 0;
1893     const TargetFrameLowering *TFI =
1894         Asm->TM.getSubtargetImpl()->getFrameLowering();
1895     int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1896     MachineLocation Location(FrameReg, Offset);
1897     addVariableAddress(DV, *VariableDie, Location);
1898   }
1899
1900   return VariableDie;
1901 }
1902
1903 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1904 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1905   DIE &MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1906   StringRef Name = DT.getName();
1907   if (!Name.empty())
1908     addString(MemberDie, dwarf::DW_AT_name, Name);
1909
1910   addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1911
1912   addSourceLine(MemberDie, DT);
1913
1914   if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1915
1916     // For C++, virtual base classes are not at fixed offset. Use following
1917     // expression to extract appropriate offset from vtable.
1918     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1919
1920     DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1921     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1922     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1923     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1924     addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1925     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1926     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1927     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1928
1929     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1930   } else {
1931     uint64_t Size = DT.getSizeInBits();
1932     uint64_t FieldSize = getBaseTypeSize(DD, DT);
1933     uint64_t OffsetInBytes;
1934
1935     if (Size != FieldSize) {
1936       // Handle bitfield, assume bytes are 8 bits.
1937       addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1938       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1939
1940       uint64_t Offset = DT.getOffsetInBits();
1941       uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1942       uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1943       uint64_t FieldOffset = (HiMark - FieldSize);
1944       Offset -= FieldOffset;
1945
1946       // Maybe we need to work from the other end.
1947       if (Asm->getDataLayout().isLittleEndian())
1948         Offset = FieldSize - (Offset + Size);
1949       addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1950
1951       // Here DW_AT_data_member_location points to the anonymous
1952       // field that includes this bit field.
1953       OffsetInBytes = FieldOffset >> 3;
1954     } else
1955       // This is not a bitfield.
1956       OffsetInBytes = DT.getOffsetInBits() >> 3;
1957
1958     if (DD->getDwarfVersion() <= 2) {
1959       DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1960       addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1961       addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1962       addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1963     } else
1964       addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1965               OffsetInBytes);
1966   }
1967
1968   if (DT.isProtected())
1969     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1970             dwarf::DW_ACCESS_protected);
1971   else if (DT.isPrivate())
1972     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1973             dwarf::DW_ACCESS_private);
1974   // Otherwise C++ member and base classes are considered public.
1975   else if (DT.isPublic())
1976     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1977             dwarf::DW_ACCESS_public);
1978   if (DT.isVirtual())
1979     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1980             dwarf::DW_VIRTUALITY_virtual);
1981
1982   // Objective-C properties.
1983   if (MDNode *PNode = DT.getObjCProperty())
1984     if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1985       MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1986                          PropertyDie);
1987
1988   if (DT.isArtificial())
1989     addFlag(MemberDie, dwarf::DW_AT_artificial);
1990 }
1991
1992 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1993 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1994   if (!DT.Verify())
1995     return nullptr;
1996
1997   // Construct the context before querying for the existence of the DIE in case
1998   // such construction creates the DIE.
1999   DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
2000   assert(dwarf::isType(ContextDIE->getTag()) &&
2001          "Static member should belong to a type.");
2002
2003   if (DIE *StaticMemberDIE = getDIE(DT))
2004     return StaticMemberDIE;
2005
2006   DIE &StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
2007
2008   DIType Ty = resolve(DT.getTypeDerivedFrom());
2009
2010   addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
2011   addType(StaticMemberDIE, Ty);
2012   addSourceLine(StaticMemberDIE, DT);
2013   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
2014   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
2015
2016   // FIXME: We could omit private if the parent is a class_type, and
2017   // public if the parent is something else.
2018   if (DT.isProtected())
2019     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2020             dwarf::DW_ACCESS_protected);
2021   else if (DT.isPrivate())
2022     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2023             dwarf::DW_ACCESS_private);
2024   else if (DT.isPublic())
2025     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2026             dwarf::DW_ACCESS_public);
2027
2028   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
2029     addConstantValue(StaticMemberDIE, CI, Ty);
2030   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
2031     addConstantFPValue(StaticMemberDIE, CFP);
2032
2033   return &StaticMemberDIE;
2034 }
2035
2036 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
2037   Asm->OutStreamer.AddComment("DWARF version number");
2038   Asm->EmitInt16(DD->getDwarfVersion());
2039   Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2040   // We share one abbreviations table across all units so it's always at the
2041   // start of the section. Use a relocatable offset where needed to ensure
2042   // linking doesn't invalidate that offset.
2043   if (ASectionSym)
2044     Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2045   else
2046     // Use a constant value when no symbol is provided.
2047     Asm->EmitInt32(0);
2048   Asm->OutStreamer.AddComment("Address Size (in bytes)");
2049   Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2050 }
2051
2052 void DwarfCompileUnit::addRange(RangeSpan Range) {
2053   bool SameAsPrevCU = this == DD->getPrevCU();
2054   DD->setPrevCU(this);
2055   // If we have no current ranges just add the range and return, otherwise,
2056   // check the current section and CU against the previous section and CU we
2057   // emitted into and the subprogram was contained within. If these are the
2058   // same then extend our current range, otherwise add this as a new range.
2059   if (CURanges.empty() || !SameAsPrevCU ||
2060       (&CURanges.back().getEnd()->getSection() !=
2061        &Range.getEnd()->getSection())) {
2062     CURanges.push_back(Range);
2063     return;
2064   }
2065
2066   CURanges.back().setEnd(Range.getEnd());
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 }