comparison lib/CodeGen/AsmPrinter/DwarfUnit.cpp @ 77:54457678186b LLVM3.6

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