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