1 //===-- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Unit ------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf compile unit.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "dwarfdebug"
15
16 #include "DwarfCompileUnit.h"
17 #include "DwarfDebug.h"
18 #include "llvm/Constants.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Analysis/DIBuilder.h"
22 #include "llvm/Target/Mangler.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetFrameLowering.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetRegisterInfo.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/Support/ErrorHandling.h"
29
30 using namespace llvm;
31
32 /// CompileUnit - Compile unit constructor.
CompileUnit(unsigned I,DIE * D,AsmPrinter * A,DwarfDebug * DW)33 CompileUnit::CompileUnit(unsigned I, DIE *D, AsmPrinter *A, DwarfDebug *DW)
34 : ID(I), CUDie(D), Asm(A), DD(DW), IndexTyDie(0) {
35 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
36 }
37
38 /// ~CompileUnit - Destructor for compile unit.
~CompileUnit()39 CompileUnit::~CompileUnit() {
40 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
41 DIEBlocks[j]->~DIEBlock();
42 }
43
44 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
45 /// information entry.
createDIEEntry(DIE * Entry)46 DIEEntry *CompileUnit::createDIEEntry(DIE *Entry) {
47 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
48 return Value;
49 }
50
51 /// addUInt - Add an unsigned integer attribute data and value.
52 ///
addUInt(DIE * Die,unsigned Attribute,unsigned Form,uint64_t Integer)53 void CompileUnit::addUInt(DIE *Die, unsigned Attribute,
54 unsigned Form, uint64_t Integer) {
55 if (!Form) Form = DIEInteger::BestForm(false, Integer);
56 DIEValue *Value = Integer == 1 ?
57 DIEIntegerOne : new (DIEValueAllocator) DIEInteger(Integer);
58 Die->addValue(Attribute, Form, Value);
59 }
60
61 /// addSInt - Add an signed integer attribute data and value.
62 ///
addSInt(DIE * Die,unsigned Attribute,unsigned Form,int64_t Integer)63 void CompileUnit::addSInt(DIE *Die, unsigned Attribute,
64 unsigned Form, int64_t Integer) {
65 if (!Form) Form = DIEInteger::BestForm(true, Integer);
66 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
67 Die->addValue(Attribute, Form, Value);
68 }
69
70 /// addString - Add a string attribute data and value. DIEString only
71 /// keeps string reference.
addString(DIE * Die,unsigned Attribute,unsigned Form,StringRef String)72 void CompileUnit::addString(DIE *Die, unsigned Attribute, unsigned Form,
73 StringRef String) {
74 DIEValue *Value = new (DIEValueAllocator) DIEString(String);
75 Die->addValue(Attribute, Form, Value);
76 }
77
78 /// addLabel - Add a Dwarf label attribute data and value.
79 ///
addLabel(DIE * Die,unsigned Attribute,unsigned Form,const MCSymbol * Label)80 void CompileUnit::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
81 const MCSymbol *Label) {
82 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
83 Die->addValue(Attribute, Form, Value);
84 }
85
86 /// addDelta - Add a label delta attribute data and value.
87 ///
addDelta(DIE * Die,unsigned Attribute,unsigned Form,const MCSymbol * Hi,const MCSymbol * Lo)88 void CompileUnit::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
89 const MCSymbol *Hi, const MCSymbol *Lo) {
90 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
91 Die->addValue(Attribute, Form, Value);
92 }
93
94 /// addDIEEntry - Add a DIE attribute data and value.
95 ///
addDIEEntry(DIE * Die,unsigned Attribute,unsigned Form,DIE * Entry)96 void CompileUnit::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
97 DIE *Entry) {
98 Die->addValue(Attribute, Form, createDIEEntry(Entry));
99 }
100
101
102 /// addBlock - Add block data.
103 ///
addBlock(DIE * Die,unsigned Attribute,unsigned Form,DIEBlock * Block)104 void CompileUnit::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
105 DIEBlock *Block) {
106 Block->ComputeSize(Asm);
107 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
108 Die->addValue(Attribute, Block->BestForm(), Block);
109 }
110
111 /// addSourceLine - Add location information to specified debug information
112 /// entry.
addSourceLine(DIE * Die,DIVariable V)113 void CompileUnit::addSourceLine(DIE *Die, DIVariable V) {
114 // Verify variable.
115 if (!V.Verify())
116 return;
117
118 unsigned Line = V.getLineNumber();
119 if (Line == 0)
120 return;
121 unsigned FileID = DD->GetOrCreateSourceID(V.getContext().getFilename(),
122 V.getContext().getDirectory());
123 assert(FileID && "Invalid file id");
124 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
125 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
126 }
127
128 /// addSourceLine - Add location information to specified debug information
129 /// entry.
addSourceLine(DIE * Die,DIGlobalVariable G)130 void CompileUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
131 // Verify global variable.
132 if (!G.Verify())
133 return;
134
135 unsigned Line = G.getLineNumber();
136 if (Line == 0)
137 return;
138 unsigned FileID = DD->GetOrCreateSourceID(G.getFilename(),
139 G.getDirectory());
140 assert(FileID && "Invalid file id");
141 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
142 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
143 }
144
145 /// addSourceLine - Add location information to specified debug information
146 /// entry.
addSourceLine(DIE * Die,DISubprogram SP)147 void CompileUnit::addSourceLine(DIE *Die, DISubprogram SP) {
148 // Verify subprogram.
149 if (!SP.Verify())
150 return;
151 // If the line number is 0, don't add it.
152 if (SP.getLineNumber() == 0)
153 return;
154
155 unsigned Line = SP.getLineNumber();
156 if (!SP.getContext().Verify())
157 return;
158 unsigned FileID = DD->GetOrCreateSourceID(SP.getFilename(), SP.getDirectory());
159 assert(FileID && "Invalid file id");
160 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
161 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
162 }
163
164 /// addSourceLine - Add location information to specified debug information
165 /// entry.
addSourceLine(DIE * Die,DIType Ty)166 void CompileUnit::addSourceLine(DIE *Die, DIType Ty) {
167 // Verify type.
168 if (!Ty.Verify())
169 return;
170
171 unsigned Line = Ty.getLineNumber();
172 if (Line == 0 || !Ty.getContext().Verify())
173 return;
174 unsigned FileID = DD->GetOrCreateSourceID(Ty.getFilename(), Ty.getDirectory());
175 assert(FileID && "Invalid file id");
176 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
177 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
178 }
179
180 /// addSourceLine - Add location information to specified debug information
181 /// entry.
addSourceLine(DIE * Die,DINameSpace NS)182 void CompileUnit::addSourceLine(DIE *Die, DINameSpace NS) {
183 // Verify namespace.
184 if (!NS.Verify())
185 return;
186
187 unsigned Line = NS.getLineNumber();
188 if (Line == 0)
189 return;
190 StringRef FN = NS.getFilename();
191
192 unsigned FileID = DD->GetOrCreateSourceID(FN, NS.getDirectory());
193 assert(FileID && "Invalid file id");
194 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
195 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
196 }
197
198 /// addVariableAddress - Add DW_AT_location attribute for a
199 /// DbgVariable based on provided MachineLocation.
addVariableAddress(DbgVariable * & DV,DIE * Die,MachineLocation Location)200 void CompileUnit::addVariableAddress(DbgVariable *&DV, DIE *Die,
201 MachineLocation Location) {
202 if (DV->variableHasComplexAddress())
203 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
204 else if (DV->isBlockByrefVariable())
205 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
206 else
207 addAddress(Die, dwarf::DW_AT_location, Location);
208 }
209
210 /// addRegisterOp - Add register operand.
addRegisterOp(DIE * TheDie,unsigned Reg)211 void CompileUnit::addRegisterOp(DIE *TheDie, unsigned Reg) {
212 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
213 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
214 if (DWReg < 32)
215 addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
216 else {
217 addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
218 addUInt(TheDie, 0, dwarf::DW_FORM_udata, DWReg);
219 }
220 }
221
222 /// addRegisterOffset - Add register offset.
addRegisterOffset(DIE * TheDie,unsigned Reg,int64_t Offset)223 void CompileUnit::addRegisterOffset(DIE *TheDie, unsigned Reg,
224 int64_t Offset) {
225 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
226 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
227 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
228 if (Reg == TRI->getFrameRegister(*Asm->MF))
229 // If variable offset is based in frame register then use fbreg.
230 addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
231 else if (DWReg < 32)
232 addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
233 else {
234 addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
235 addUInt(TheDie, 0, dwarf::DW_FORM_udata, DWReg);
236 }
237 addSInt(TheDie, 0, dwarf::DW_FORM_sdata, Offset);
238 }
239
240 /// addAddress - Add an address attribute to a die based on the location
241 /// provided.
addAddress(DIE * Die,unsigned Attribute,const MachineLocation & Location)242 void CompileUnit::addAddress(DIE *Die, unsigned Attribute,
243 const MachineLocation &Location) {
244 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
245
246 if (Location.isReg())
247 addRegisterOp(Block, Location.getReg());
248 else
249 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
250
251 // Now attach the location information to the DIE.
252 addBlock(Die, Attribute, 0, Block);
253 }
254
255 /// addComplexAddress - Start with the address based on the location provided,
256 /// and generate the DWARF information necessary to find the actual variable
257 /// given the extra address information encoded in the DIVariable, starting from
258 /// the starting location. Add the DWARF information to the die.
259 ///
addComplexAddress(DbgVariable * & DV,DIE * Die,unsigned Attribute,const MachineLocation & Location)260 void CompileUnit::addComplexAddress(DbgVariable *&DV, DIE *Die,
261 unsigned Attribute,
262 const MachineLocation &Location) {
263 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
264 unsigned N = DV->getNumAddrElements();
265 unsigned i = 0;
266 if (Location.isReg()) {
267 if (N >= 2 && DV->getAddrElement(0) == DIBuilder::OpPlus) {
268 // If first address element is OpPlus then emit
269 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
270 addRegisterOffset(Block, Location.getReg(), DV->getAddrElement(1));
271 i = 2;
272 } else
273 addRegisterOp(Block, Location.getReg());
274 }
275 else
276 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
277
278 for (;i < N; ++i) {
279 uint64_t Element = DV->getAddrElement(i);
280 if (Element == DIBuilder::OpPlus) {
281 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
282 addUInt(Block, 0, dwarf::DW_FORM_udata, DV->getAddrElement(++i));
283 } else if (Element == DIBuilder::OpDeref) {
284 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
285 } else llvm_unreachable("unknown DIBuilder Opcode");
286 }
287
288 // Now attach the location information to the DIE.
289 addBlock(Die, Attribute, 0, Block);
290 }
291
292 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
293 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
294 gives the variable VarName either the struct, or a pointer to the struct, as
295 its type. This is necessary for various behind-the-scenes things the
296 compiler needs to do with by-reference variables in Blocks.
297
298 However, as far as the original *programmer* is concerned, the variable
299 should still have type 'SomeType', as originally declared.
300
301 The function getBlockByrefType dives into the __Block_byref_x_VarName
302 struct to find the original type of the variable, which is then assigned to
303 the variable's Debug Information Entry as its real type. So far, so good.
304 However now the debugger will expect the variable VarName to have the type
305 SomeType. So we need the location attribute for the variable to be an
306 expression that explains to the debugger how to navigate through the
307 pointers and struct to find the actual variable of type SomeType.
308
309 The following function does just that. We start by getting
310 the "normal" location for the variable. This will be the location
311 of either the struct __Block_byref_x_VarName or the pointer to the
312 struct __Block_byref_x_VarName.
313
314 The struct will look something like:
315
316 struct __Block_byref_x_VarName {
317 ... <various fields>
318 struct __Block_byref_x_VarName *forwarding;
319 ... <various other fields>
320 SomeType VarName;
321 ... <maybe more fields>
322 };
323
324 If we are given the struct directly (as our starting point) we
325 need to tell the debugger to:
326
327 1). Add the offset of the forwarding field.
328
329 2). Follow that pointer to get the real __Block_byref_x_VarName
330 struct to use (the real one may have been copied onto the heap).
331
332 3). Add the offset for the field VarName, to find the actual variable.
333
334 If we started with a pointer to the struct, then we need to
335 dereference that pointer first, before the other steps.
336 Translating this into DWARF ops, we will need to append the following
337 to the current location description for the variable:
338
339 DW_OP_deref -- optional, if we start with a pointer
340 DW_OP_plus_uconst <forward_fld_offset>
341 DW_OP_deref
342 DW_OP_plus_uconst <varName_fld_offset>
343
344 That is what this function does. */
345
346 /// addBlockByrefAddress - Start with the address based on the location
347 /// provided, and generate the DWARF information necessary to find the
348 /// actual Block variable (navigating the Block struct) based on the
349 /// starting location. Add the DWARF information to the die. For
350 /// more information, read large comment just above here.
351 ///
addBlockByrefAddress(DbgVariable * & DV,DIE * Die,unsigned Attribute,const MachineLocation & Location)352 void CompileUnit::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
353 unsigned Attribute,
354 const MachineLocation &Location) {
355 DIType Ty = DV->getType();
356 DIType TmpTy = Ty;
357 unsigned Tag = Ty.getTag();
358 bool isPointer = false;
359
360 StringRef varName = DV->getName();
361
362 if (Tag == dwarf::DW_TAG_pointer_type) {
363 DIDerivedType DTy = DIDerivedType(Ty);
364 TmpTy = DTy.getTypeDerivedFrom();
365 isPointer = true;
366 }
367
368 DICompositeType blockStruct = DICompositeType(TmpTy);
369
370 // Find the __forwarding field and the variable field in the __Block_byref
371 // struct.
372 DIArray Fields = blockStruct.getTypeArray();
373 DIDescriptor varField = DIDescriptor();
374 DIDescriptor forwardingField = DIDescriptor();
375
376 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
377 DIDescriptor Element = Fields.getElement(i);
378 DIDerivedType DT = DIDerivedType(Element);
379 StringRef fieldName = DT.getName();
380 if (fieldName == "__forwarding")
381 forwardingField = Element;
382 else if (fieldName == varName)
383 varField = Element;
384 }
385
386 // Get the offsets for the forwarding field and the variable field.
387 unsigned forwardingFieldOffset =
388 DIDerivedType(forwardingField).getOffsetInBits() >> 3;
389 unsigned varFieldOffset =
390 DIDerivedType(varField).getOffsetInBits() >> 3;
391
392 // Decode the original location, and use that as the start of the byref
393 // variable's location.
394 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
395 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
396 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
397
398 if (Location.isReg()) {
399 if (Reg < 32)
400 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
401 else {
402 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
403 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
404 }
405 } else {
406 if (Reg < 32)
407 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
408 else {
409 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
410 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
411 }
412
413 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
414 }
415
416 // If we started with a pointer to the __Block_byref... struct, then
417 // the first thing we need to do is dereference the pointer (DW_OP_deref).
418 if (isPointer)
419 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
420
421 // Next add the offset for the '__forwarding' field:
422 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
423 // adding the offset if it's 0.
424 if (forwardingFieldOffset > 0) {
425 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
426 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
427 }
428
429 // Now dereference the __forwarding field to get to the real __Block_byref
430 // struct: DW_OP_deref.
431 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
432
433 // Now that we've got the real __Block_byref... struct, add the offset
434 // for the variable's field to get to the location of the actual variable:
435 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
436 if (varFieldOffset > 0) {
437 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
438 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
439 }
440
441 // Now attach the location information to the DIE.
442 addBlock(Die, Attribute, 0, Block);
443 }
444
445 /// isTypeSigned - Return true if the type is signed.
isTypeSigned(DIType Ty,int * SizeInBits)446 static bool isTypeSigned(DIType Ty, int *SizeInBits) {
447 if (Ty.isDerivedType())
448 return isTypeSigned(DIDerivedType(Ty).getTypeDerivedFrom(), SizeInBits);
449 if (Ty.isBasicType())
450 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed
451 || DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
452 *SizeInBits = Ty.getSizeInBits();
453 return true;
454 }
455 return false;
456 }
457
458 /// addConstantValue - Add constant value entry in variable DIE.
addConstantValue(DIE * Die,const MachineOperand & MO,DIType Ty)459 bool CompileUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
460 DIType Ty) {
461 assert (MO.isImm() && "Invalid machine operand!");
462 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
463 int SizeInBits = -1;
464 bool SignedConstant = isTypeSigned(Ty, &SizeInBits);
465 unsigned Form = SignedConstant ? dwarf::DW_FORM_sdata : dwarf::DW_FORM_udata;
466 switch (SizeInBits) {
467 case 8: Form = dwarf::DW_FORM_data1; break;
468 case 16: Form = dwarf::DW_FORM_data2; break;
469 case 32: Form = dwarf::DW_FORM_data4; break;
470 case 64: Form = dwarf::DW_FORM_data8; break;
471 default: break;
472 }
473 SignedConstant ? addSInt(Block, 0, Form, MO.getImm())
474 : addUInt(Block, 0, Form, MO.getImm());
475
476 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
477 return true;
478 }
479
480 /// addConstantFPValue - Add constant value entry in variable DIE.
addConstantFPValue(DIE * Die,const MachineOperand & MO)481 bool CompileUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
482 assert (MO.isFPImm() && "Invalid machine operand!");
483 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
484 APFloat FPImm = MO.getFPImm()->getValueAPF();
485
486 // Get the raw data form of the floating point.
487 const APInt FltVal = FPImm.bitcastToAPInt();
488 const char *FltPtr = (const char*)FltVal.getRawData();
489
490 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
491 bool LittleEndian = Asm->getTargetData().isLittleEndian();
492 int Incr = (LittleEndian ? 1 : -1);
493 int Start = (LittleEndian ? 0 : NumBytes - 1);
494 int Stop = (LittleEndian ? NumBytes : -1);
495
496 // Output the constant to DWARF one byte at a time.
497 for (; Start != Stop; Start += Incr)
498 addUInt(Block, 0, dwarf::DW_FORM_data1,
499 (unsigned char)0xFF & FltPtr[Start]);
500
501 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
502 return true;
503 }
504
505 /// addConstantValue - Add constant value entry in variable DIE.
addConstantValue(DIE * Die,const ConstantInt * CI,bool Unsigned)506 bool CompileUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
507 bool Unsigned) {
508 unsigned CIBitWidth = CI->getBitWidth();
509 if (CIBitWidth <= 64) {
510 unsigned form = 0;
511 switch (CIBitWidth) {
512 case 8: form = dwarf::DW_FORM_data1; break;
513 case 16: form = dwarf::DW_FORM_data2; break;
514 case 32: form = dwarf::DW_FORM_data4; break;
515 case 64: form = dwarf::DW_FORM_data8; break;
516 default:
517 form = Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata;
518 }
519 if (Unsigned)
520 addUInt(Die, dwarf::DW_AT_const_value, form, CI->getZExtValue());
521 else
522 addSInt(Die, dwarf::DW_AT_const_value, form, CI->getSExtValue());
523 return true;
524 }
525
526 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
527
528 // Get the raw data form of the large APInt.
529 const APInt Val = CI->getValue();
530 const uint64_t *Ptr64 = Val.getRawData();
531
532 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
533 bool LittleEndian = Asm->getTargetData().isLittleEndian();
534
535 // Output the constant to DWARF one byte at a time.
536 for (int i = 0; i < NumBytes; i++) {
537 uint8_t c;
538 if (LittleEndian)
539 c = Ptr64[i / 8] >> (8 * (i & 7));
540 else
541 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
542 addUInt(Block, 0, dwarf::DW_FORM_data1, c);
543 }
544
545 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
546 return true;
547 }
548
549 /// addTemplateParams - Add template parameters in buffer.
addTemplateParams(DIE & Buffer,DIArray TParams)550 void CompileUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
551 // Add template parameters.
552 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
553 DIDescriptor Element = TParams.getElement(i);
554 if (Element.isTemplateTypeParameter())
555 Buffer.addChild(getOrCreateTemplateTypeParameterDIE(
556 DITemplateTypeParameter(Element)));
557 else if (Element.isTemplateValueParameter())
558 Buffer.addChild(getOrCreateTemplateValueParameterDIE(
559 DITemplateValueParameter(Element)));
560 }
561
562 }
563 /// addToContextOwner - Add Die into the list of its context owner's children.
addToContextOwner(DIE * Die,DIDescriptor Context)564 void CompileUnit::addToContextOwner(DIE *Die, DIDescriptor Context) {
565 if (Context.isType()) {
566 DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context));
567 ContextDIE->addChild(Die);
568 } else if (Context.isNameSpace()) {
569 DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context));
570 ContextDIE->addChild(Die);
571 } else if (Context.isSubprogram()) {
572 DIE *ContextDIE = getOrCreateSubprogramDIE(DISubprogram(Context));
573 ContextDIE->addChild(Die);
574 } else if (DIE *ContextDIE = getDIE(Context))
575 ContextDIE->addChild(Die);
576 else
577 addDie(Die);
578 }
579
580 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
581 /// given DIType.
getOrCreateTypeDIE(const MDNode * TyNode)582 DIE *CompileUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
583 DIType Ty(TyNode);
584 if (!Ty.Verify())
585 return NULL;
586 DIE *TyDIE = getDIE(Ty);
587 if (TyDIE)
588 return TyDIE;
589
590 // Create new type.
591 TyDIE = new DIE(dwarf::DW_TAG_base_type);
592 insertDIE(Ty, TyDIE);
593 if (Ty.isBasicType())
594 constructTypeDIE(*TyDIE, DIBasicType(Ty));
595 else if (Ty.isCompositeType())
596 constructTypeDIE(*TyDIE, DICompositeType(Ty));
597 else {
598 assert(Ty.isDerivedType() && "Unknown kind of DIType");
599 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
600 }
601
602 addToContextOwner(TyDIE, Ty.getContext());
603 return TyDIE;
604 }
605
606 /// addType - Add a new type attribute to the specified entity.
addType(DIE * Entity,DIType Ty)607 void CompileUnit::addType(DIE *Entity, DIType Ty) {
608 if (!Ty.Verify())
609 return;
610
611 // Check for pre-existence.
612 DIEEntry *Entry = getDIEEntry(Ty);
613 // If it exists then use the existing value.
614 if (Entry) {
615 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
616 return;
617 }
618
619 // Construct type.
620 DIE *Buffer = getOrCreateTypeDIE(Ty);
621
622 // Set up proxy.
623 Entry = createDIEEntry(Buffer);
624 insertDIEEntry(Ty, Entry);
625 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
626
627 // If this is a complete composite type then include it in the
628 // list of global types.
629 addGlobalType(Ty);
630 }
631
632 /// addGlobalType - Add a new global type to the compile unit.
633 ///
addGlobalType(DIType Ty)634 void CompileUnit::addGlobalType(DIType Ty) {
635 DIDescriptor Context = Ty.getContext();
636 if (Ty.isCompositeType() && !Ty.getName().empty() && !Ty.isForwardDecl()
637 && (!Context || Context.isCompileUnit() || Context.isFile()
638 || Context.isNameSpace()))
639 if (DIEEntry *Entry = getDIEEntry(Ty))
640 GlobalTypes[Ty.getName()] = Entry->getEntry();
641 }
642
643 /// addPubTypes - Add type for pubtypes section.
addPubTypes(DISubprogram SP)644 void CompileUnit::addPubTypes(DISubprogram SP) {
645 DICompositeType SPTy = SP.getType();
646 unsigned SPTag = SPTy.getTag();
647 if (SPTag != dwarf::DW_TAG_subroutine_type)
648 return;
649
650 DIArray Args = SPTy.getTypeArray();
651 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
652 DIType ATy(Args.getElement(i));
653 if (!ATy.Verify())
654 continue;
655 addGlobalType(ATy);
656 }
657 }
658
659 /// constructTypeDIE - Construct basic type die from DIBasicType.
constructTypeDIE(DIE & Buffer,DIBasicType BTy)660 void CompileUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
661 // Get core information.
662 StringRef Name = BTy.getName();
663 // Add name if not anonymous or intermediate type.
664 if (!Name.empty())
665 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
666
667 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type) {
668 Buffer.setTag(dwarf::DW_TAG_unspecified_type);
669 // Unspecified types has only name, nothing else.
670 return;
671 }
672
673 Buffer.setTag(dwarf::DW_TAG_base_type);
674 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
675 BTy.getEncoding());
676
677 uint64_t Size = BTy.getSizeInBits() >> 3;
678 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
679 }
680
681 /// constructTypeDIE - Construct derived type die from DIDerivedType.
constructTypeDIE(DIE & Buffer,DIDerivedType DTy)682 void CompileUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
683 // Get core information.
684 StringRef Name = DTy.getName();
685 uint64_t Size = DTy.getSizeInBits() >> 3;
686 unsigned Tag = DTy.getTag();
687
688 // FIXME - Workaround for templates.
689 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
690
691 Buffer.setTag(Tag);
692
693 // Map to main type, void will not have a type.
694 DIType FromTy = DTy.getTypeDerivedFrom();
695 addType(&Buffer, FromTy);
696
697 // Add name if not anonymous or intermediate type.
698 if (!Name.empty())
699 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
700
701 // Add size if non-zero (derived types might be zero-sized.)
702 if (Size)
703 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
704
705 // Add source line info if available and TyDesc is not a forward declaration.
706 if (!DTy.isForwardDecl())
707 addSourceLine(&Buffer, DTy);
708 }
709
710 /// constructTypeDIE - Construct type DIE from DICompositeType.
constructTypeDIE(DIE & Buffer,DICompositeType CTy)711 void CompileUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
712 // Get core information.
713 StringRef Name = CTy.getName();
714
715 uint64_t Size = CTy.getSizeInBits() >> 3;
716 unsigned Tag = CTy.getTag();
717 Buffer.setTag(Tag);
718
719 switch (Tag) {
720 case dwarf::DW_TAG_vector_type:
721 case dwarf::DW_TAG_array_type:
722 constructArrayTypeDIE(Buffer, &CTy);
723 break;
724 case dwarf::DW_TAG_enumeration_type: {
725 DIArray Elements = CTy.getTypeArray();
726
727 // Add enumerators to enumeration type.
728 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
729 DIE *ElemDie = NULL;
730 DIDescriptor Enum(Elements.getElement(i));
731 if (Enum.isEnumerator()) {
732 ElemDie = constructEnumTypeDIE(DIEnumerator(Enum));
733 Buffer.addChild(ElemDie);
734 }
735 }
736 }
737 break;
738 case dwarf::DW_TAG_subroutine_type: {
739 // Add return type.
740 DIArray Elements = CTy.getTypeArray();
741 DIDescriptor RTy = Elements.getElement(0);
742 addType(&Buffer, DIType(RTy));
743
744 bool isPrototyped = true;
745 // Add arguments.
746 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
747 DIDescriptor Ty = Elements.getElement(i);
748 if (Ty.isUnspecifiedParameter()) {
749 DIE *Arg = new DIE(dwarf::DW_TAG_unspecified_parameters);
750 Buffer.addChild(Arg);
751 isPrototyped = false;
752 } else {
753 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
754 addType(Arg, DIType(Ty));
755 Buffer.addChild(Arg);
756 }
757 }
758 // Add prototype flag.
759 if (isPrototyped)
760 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
761 }
762 break;
763 case dwarf::DW_TAG_structure_type:
764 case dwarf::DW_TAG_union_type:
765 case dwarf::DW_TAG_class_type: {
766 // Add elements to structure type.
767 DIArray Elements = CTy.getTypeArray();
768
769 // A forward struct declared type may not have elements available.
770 unsigned N = Elements.getNumElements();
771 if (N == 0)
772 break;
773
774 // Add elements to structure type.
775 for (unsigned i = 0; i < N; ++i) {
776 DIDescriptor Element = Elements.getElement(i);
777 DIE *ElemDie = NULL;
778 if (Element.isSubprogram()) {
779 DISubprogram SP(Element);
780 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
781 if (SP.isProtected())
782 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
783 dwarf::DW_ACCESS_protected);
784 else if (SP.isPrivate())
785 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
786 dwarf::DW_ACCESS_private);
787 else
788 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
789 dwarf::DW_ACCESS_public);
790 if (SP.isExplicit())
791 addUInt(ElemDie, dwarf::DW_AT_explicit, dwarf::DW_FORM_flag, 1);
792 }
793 else if (Element.isVariable()) {
794 DIVariable DV(Element);
795 ElemDie = new DIE(dwarf::DW_TAG_variable);
796 addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
797 DV.getName());
798 addType(ElemDie, DV.getType());
799 addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
800 addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
801 addSourceLine(ElemDie, DV);
802 } else if (Element.isDerivedType())
803 ElemDie = createMemberDIE(DIDerivedType(Element));
804 else
805 continue;
806 Buffer.addChild(ElemDie);
807 }
808
809 if (CTy.isAppleBlockExtension())
810 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
811
812 unsigned RLang = CTy.getRunTimeLang();
813 if (RLang)
814 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
815 dwarf::DW_FORM_data1, RLang);
816
817 DICompositeType ContainingType = CTy.getContainingType();
818 if (DIDescriptor(ContainingType).isCompositeType())
819 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
820 getOrCreateTypeDIE(DIType(ContainingType)));
821 else {
822 DIDescriptor Context = CTy.getContext();
823 addToContextOwner(&Buffer, Context);
824 }
825
826 if (CTy.isObjcClassComplete())
827 addUInt(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type,
828 dwarf::DW_FORM_flag, 1);
829
830 if (Tag == dwarf::DW_TAG_class_type)
831 addTemplateParams(Buffer, CTy.getTemplateParams());
832
833 break;
834 }
835 default:
836 break;
837 }
838
839 // Add name if not anonymous or intermediate type.
840 if (!Name.empty())
841 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
842
843 if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type
844 || Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
845 {
846 // Add size if non-zero (derived types might be zero-sized.)
847 if (Size)
848 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
849 else {
850 // Add zero size if it is not a forward declaration.
851 if (CTy.isForwardDecl())
852 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
853 else
854 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
855 }
856
857 // Add source line info if available.
858 if (!CTy.isForwardDecl())
859 addSourceLine(&Buffer, CTy);
860 }
861 }
862
863 /// getOrCreateTemplateTypeParameterDIE - Find existing DIE or create new DIE
864 /// for the given DITemplateTypeParameter.
865 DIE *
getOrCreateTemplateTypeParameterDIE(DITemplateTypeParameter TP)866 CompileUnit::getOrCreateTemplateTypeParameterDIE(DITemplateTypeParameter TP) {
867 DIE *ParamDIE = getDIE(TP);
868 if (ParamDIE)
869 return ParamDIE;
870
871 ParamDIE = new DIE(dwarf::DW_TAG_template_type_parameter);
872 addType(ParamDIE, TP.getType());
873 addString(ParamDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string, TP.getName());
874 return ParamDIE;
875 }
876
877 /// getOrCreateTemplateValueParameterDIE - Find existing DIE or create new DIE
878 /// for the given DITemplateValueParameter.
879 DIE *
getOrCreateTemplateValueParameterDIE(DITemplateValueParameter TPV)880 CompileUnit::getOrCreateTemplateValueParameterDIE(DITemplateValueParameter TPV) {
881 DIE *ParamDIE = getDIE(TPV);
882 if (ParamDIE)
883 return ParamDIE;
884
885 ParamDIE = new DIE(dwarf::DW_TAG_template_value_parameter);
886 addType(ParamDIE, TPV.getType());
887 if (!TPV.getName().empty())
888 addString(ParamDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string, TPV.getName());
889 addUInt(ParamDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
890 TPV.getValue());
891 return ParamDIE;
892 }
893
894 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
getOrCreateNameSpace(DINameSpace NS)895 DIE *CompileUnit::getOrCreateNameSpace(DINameSpace NS) {
896 DIE *NDie = getDIE(NS);
897 if (NDie)
898 return NDie;
899 NDie = new DIE(dwarf::DW_TAG_namespace);
900 insertDIE(NS, NDie);
901 if (!NS.getName().empty())
902 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
903 addSourceLine(NDie, NS);
904 addToContextOwner(NDie, NS.getContext());
905 return NDie;
906 }
907
908 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
909 /// printer to not emit usual symbol prefix before the symbol name is used then
910 /// return linkage name after skipping this special LLVM prefix.
getRealLinkageName(StringRef LinkageName)911 static StringRef getRealLinkageName(StringRef LinkageName) {
912 char One = '\1';
913 if (LinkageName.startswith(StringRef(&One, 1)))
914 return LinkageName.substr(1);
915 return LinkageName;
916 }
917
918 /// getOrCreateSubprogramDIE - Create new DIE using SP.
getOrCreateSubprogramDIE(DISubprogram SP)919 DIE *CompileUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
920 DIE *SPDie = getDIE(SP);
921 if (SPDie)
922 return SPDie;
923
924 SPDie = new DIE(dwarf::DW_TAG_subprogram);
925
926 // DW_TAG_inlined_subroutine may refer to this DIE.
927 insertDIE(SP, SPDie);
928
929 // Add to context owner.
930 addToContextOwner(SPDie, SP.getContext());
931
932 // Add function template parameters.
933 addTemplateParams(*SPDie, SP.getTemplateParams());
934
935 StringRef LinkageName = SP.getLinkageName();
936 if (!LinkageName.empty())
937 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
938 dwarf::DW_FORM_string,
939 getRealLinkageName(LinkageName));
940
941 // If this DIE is going to refer declaration info using AT_specification
942 // then there is no need to add other attributes.
943 if (SP.getFunctionDeclaration().isSubprogram())
944 return SPDie;
945
946 // Constructors and operators for anonymous aggregates do not have names.
947 if (!SP.getName().empty())
948 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
949 SP.getName());
950
951 addSourceLine(SPDie, SP);
952
953 if (SP.isPrototyped())
954 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
955
956 // Add Return Type.
957 DICompositeType SPTy = SP.getType();
958 DIArray Args = SPTy.getTypeArray();
959 unsigned SPTag = SPTy.getTag();
960
961 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
962 addType(SPDie, SPTy);
963 else
964 addType(SPDie, DIType(Args.getElement(0)));
965
966 unsigned VK = SP.getVirtuality();
967 if (VK) {
968 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
969 DIEBlock *Block = getDIEBlock();
970 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
971 addUInt(Block, 0, dwarf::DW_FORM_udata, SP.getVirtualIndex());
972 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
973 ContainingTypeMap.insert(std::make_pair(SPDie,
974 SP.getContainingType()));
975 }
976
977 if (!SP.isDefinition()) {
978 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
979
980 // Add arguments. Do not add arguments for subprogram definition. They will
981 // be handled while processing variables.
982 DICompositeType SPTy = SP.getType();
983 DIArray Args = SPTy.getTypeArray();
984 unsigned SPTag = SPTy.getTag();
985
986 if (SPTag == dwarf::DW_TAG_subroutine_type)
987 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
988 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
989 DIType ATy = DIType(DIType(Args.getElement(i)));
990 addType(Arg, ATy);
991 if (ATy.isArtificial())
992 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
993 SPDie->addChild(Arg);
994 }
995 }
996
997 if (SP.isArtificial())
998 addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
999
1000 if (!SP.isLocalToUnit())
1001 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1002
1003 if (SP.isOptimized())
1004 addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1005
1006 if (unsigned isa = Asm->getISAEncoding()) {
1007 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1008 }
1009
1010 return SPDie;
1011 }
1012
1013 // Return const expression if value is a GEP to access merged global
1014 // constant. e.g.
1015 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
getMergedGlobalExpr(const Value * V)1016 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1017 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1018 if (!CE || CE->getNumOperands() != 3 ||
1019 CE->getOpcode() != Instruction::GetElementPtr)
1020 return NULL;
1021
1022 // First operand points to a global struct.
1023 Value *Ptr = CE->getOperand(0);
1024 if (!isa<GlobalValue>(Ptr) ||
1025 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1026 return NULL;
1027
1028 // Second operand is zero.
1029 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1030 if (!CI || !CI->isZero())
1031 return NULL;
1032
1033 // Third operand is offset.
1034 if (!isa<ConstantInt>(CE->getOperand(2)))
1035 return NULL;
1036
1037 return CE;
1038 }
1039
1040 /// createGlobalVariableDIE - create global variable DIE.
createGlobalVariableDIE(const MDNode * N)1041 void CompileUnit::createGlobalVariableDIE(const MDNode *N) {
1042 // Check for pre-existence.
1043 if (getDIE(N))
1044 return;
1045
1046 DIGlobalVariable GV(N);
1047 if (!GV.Verify())
1048 return;
1049
1050 DIE *VariableDIE = new DIE(GV.getTag());
1051 // Add to map.
1052 insertDIE(N, VariableDIE);
1053
1054 // Add name.
1055 addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1056 GV.getDisplayName());
1057 StringRef LinkageName = GV.getLinkageName();
1058 bool isGlobalVariable = GV.getGlobal() != NULL;
1059 if (!LinkageName.empty() && isGlobalVariable)
1060 addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name,
1061 dwarf::DW_FORM_string,
1062 getRealLinkageName(LinkageName));
1063 // Add type.
1064 DIType GTy = GV.getType();
1065 addType(VariableDIE, GTy);
1066
1067 // Add scoping info.
1068 if (!GV.isLocalToUnit()) {
1069 addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1070 // Expose as global.
1071 addGlobal(GV.getName(), VariableDIE);
1072 }
1073 // Add line number info.
1074 addSourceLine(VariableDIE, GV);
1075 // Add to context owner.
1076 DIDescriptor GVContext = GV.getContext();
1077 addToContextOwner(VariableDIE, GVContext);
1078 // Add location.
1079 if (isGlobalVariable) {
1080 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1081 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1082 addLabel(Block, 0, dwarf::DW_FORM_udata,
1083 Asm->Mang->getSymbol(GV.getGlobal()));
1084 // Do not create specification DIE if context is either compile unit
1085 // or a subprogram.
1086 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1087 !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1088 // Create specification DIE.
1089 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1090 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1091 dwarf::DW_FORM_ref4, VariableDIE);
1092 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1093 addUInt(VariableDIE, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag,
1094 1);
1095 addDie(VariableSpecDIE);
1096 } else {
1097 addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1098 }
1099 } else if (const ConstantInt *CI =
1100 dyn_cast_or_null<ConstantInt>(GV.getConstant()))
1101 addConstantValue(VariableDIE, CI, GTy.isUnsignedDIType());
1102 else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) {
1103 // GV is a merged global.
1104 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1105 Value *Ptr = CE->getOperand(0);
1106 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1107 addLabel(Block, 0, dwarf::DW_FORM_udata,
1108 Asm->Mang->getSymbol(cast<GlobalValue>(Ptr)));
1109 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1110 SmallVector<Value*, 3> Idx(CE->op_begin()+1, CE->op_end());
1111 addUInt(Block, 0, dwarf::DW_FORM_udata,
1112 Asm->getTargetData().getIndexedOffset(Ptr->getType(), Idx));
1113 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1114 addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1115 }
1116
1117 return;
1118 }
1119
1120 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
constructSubrangeDIE(DIE & Buffer,DISubrange SR,DIE * IndexTy)1121 void CompileUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1122 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1123 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1124 int64_t L = SR.getLo();
1125 int64_t H = SR.getHi();
1126
1127 // The L value defines the lower bounds which is typically zero for C/C++. The
1128 // H value is the upper bounds. Values are 64 bit. H - L + 1 is the size
1129 // of the array. If L > H then do not emit DW_AT_lower_bound and
1130 // DW_AT_upper_bound attributes. If L is zero and H is also zero then the
1131 // array has one element and in such case do not emit lower bound.
1132
1133 if (L > H) {
1134 Buffer.addChild(DW_Subrange);
1135 return;
1136 }
1137 if (L)
1138 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1139 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1140 Buffer.addChild(DW_Subrange);
1141 }
1142
1143 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
constructArrayTypeDIE(DIE & Buffer,DICompositeType * CTy)1144 void CompileUnit::constructArrayTypeDIE(DIE &Buffer,
1145 DICompositeType *CTy) {
1146 Buffer.setTag(dwarf::DW_TAG_array_type);
1147 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1148 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1149
1150 // Emit derived type.
1151 addType(&Buffer, CTy->getTypeDerivedFrom());
1152 DIArray Elements = CTy->getTypeArray();
1153
1154 // Get an anonymous type for index type.
1155 DIE *IdxTy = getIndexTyDie();
1156 if (!IdxTy) {
1157 // Construct an anonymous type for index type.
1158 IdxTy = new DIE(dwarf::DW_TAG_base_type);
1159 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1160 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1161 dwarf::DW_ATE_signed);
1162 addDie(IdxTy);
1163 setIndexTyDie(IdxTy);
1164 }
1165
1166 // Add subranges to array type.
1167 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1168 DIDescriptor Element = Elements.getElement(i);
1169 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1170 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1171 }
1172 }
1173
1174 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
constructEnumTypeDIE(DIEnumerator ETy)1175 DIE *CompileUnit::constructEnumTypeDIE(DIEnumerator ETy) {
1176 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1177 StringRef Name = ETy.getName();
1178 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1179 int64_t Value = ETy.getEnumValue();
1180 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1181 return Enumerator;
1182 }
1183
1184 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1185 /// vtables.
constructContainingTypeDIEs()1186 void CompileUnit::constructContainingTypeDIEs() {
1187 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1188 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1189 DIE *SPDie = CI->first;
1190 const MDNode *N = CI->second;
1191 if (!N) continue;
1192 DIE *NDie = getDIE(N);
1193 if (!NDie) continue;
1194 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1195 }
1196 }
1197
1198 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
constructVariableDIE(DbgVariable * DV,bool isScopeAbstract)1199 DIE *CompileUnit::constructVariableDIE(DbgVariable *DV, bool isScopeAbstract) {
1200 StringRef Name = DV->getName();
1201 if (Name.empty())
1202 return NULL;
1203
1204 // Translate tag to proper Dwarf tag.
1205 unsigned Tag = DV->getTag();
1206
1207 // Define variable debug information entry.
1208 DIE *VariableDie = new DIE(Tag);
1209 DbgVariable *AbsVar = DV->getAbstractVariable();
1210 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1211 if (AbsDIE)
1212 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1213 dwarf::DW_FORM_ref4, AbsDIE);
1214 else {
1215 addString(VariableDie, dwarf::DW_AT_name,
1216 dwarf::DW_FORM_string, Name);
1217 addSourceLine(VariableDie, DV->getVariable());
1218 addType(VariableDie, DV->getType());
1219 }
1220
1221 if (DV->isArtificial())
1222 addUInt(VariableDie, dwarf::DW_AT_artificial,
1223 dwarf::DW_FORM_flag, 1);
1224
1225 if (isScopeAbstract) {
1226 DV->setDIE(VariableDie);
1227 return VariableDie;
1228 }
1229
1230 // Add variable address.
1231
1232 unsigned Offset = DV->getDotDebugLocOffset();
1233 if (Offset != ~0U) {
1234 addLabel(VariableDie, dwarf::DW_AT_location,
1235 dwarf::DW_FORM_data4,
1236 Asm->GetTempSymbol("debug_loc", Offset));
1237 DV->setDIE(VariableDie);
1238 return VariableDie;
1239 }
1240
1241 // Check if variable is described by a DBG_VALUE instruction.
1242 if (const MachineInstr *DVInsn = DV->getMInsn()) {
1243 bool updated = false;
1244 if (DVInsn->getNumOperands() == 3) {
1245 if (DVInsn->getOperand(0).isReg()) {
1246 const MachineOperand RegOp = DVInsn->getOperand(0);
1247 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1248 if (DVInsn->getOperand(1).isImm() &&
1249 TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
1250 unsigned FrameReg = 0;
1251 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1252 int Offset =
1253 TFI->getFrameIndexReference(*Asm->MF,
1254 DVInsn->getOperand(1).getImm(),
1255 FrameReg);
1256 MachineLocation Location(FrameReg, Offset);
1257 addVariableAddress(DV, VariableDie, Location);
1258
1259 } else if (RegOp.getReg())
1260 addVariableAddress(DV, VariableDie,
1261 MachineLocation(RegOp.getReg()));
1262 updated = true;
1263 }
1264 else if (DVInsn->getOperand(0).isImm())
1265 updated =
1266 addConstantValue(VariableDie, DVInsn->getOperand(0),
1267 DV->getType());
1268 else if (DVInsn->getOperand(0).isFPImm())
1269 updated =
1270 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1271 else if (DVInsn->getOperand(0).isCImm())
1272 updated =
1273 addConstantValue(VariableDie,
1274 DVInsn->getOperand(0).getCImm(),
1275 DV->getType().isUnsignedDIType());
1276 } else {
1277 addVariableAddress(DV, VariableDie,
1278 Asm->getDebugValueLocation(DVInsn));
1279 updated = true;
1280 }
1281 if (!updated) {
1282 // If variableDie is not updated then DBG_VALUE instruction does not
1283 // have valid variable info.
1284 delete VariableDie;
1285 return NULL;
1286 }
1287 DV->setDIE(VariableDie);
1288 return VariableDie;
1289 } else {
1290 // .. else use frame index.
1291 int FI = DV->getFrameIndex();
1292 if (FI != ~0) {
1293 unsigned FrameReg = 0;
1294 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1295 int Offset =
1296 TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1297 MachineLocation Location(FrameReg, Offset);
1298 addVariableAddress(DV, VariableDie, Location);
1299 }
1300 }
1301
1302 DV->setDIE(VariableDie);
1303 return VariableDie;
1304 }
1305
1306 /// createMemberDIE - Create new member DIE.
createMemberDIE(DIDerivedType DT)1307 DIE *CompileUnit::createMemberDIE(DIDerivedType DT) {
1308 DIE *MemberDie = new DIE(DT.getTag());
1309 StringRef Name = DT.getName();
1310 if (!Name.empty())
1311 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1312
1313 addType(MemberDie, DT.getTypeDerivedFrom());
1314
1315 addSourceLine(MemberDie, DT);
1316
1317 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1318 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1319
1320 uint64_t Size = DT.getSizeInBits();
1321 uint64_t FieldSize = DT.getOriginalTypeSize();
1322
1323 if (Size != FieldSize) {
1324 // Handle bitfield.
1325 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1326 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1327
1328 uint64_t Offset = DT.getOffsetInBits();
1329 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1330 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1331 uint64_t FieldOffset = (HiMark - FieldSize);
1332 Offset -= FieldOffset;
1333
1334 // Maybe we need to work from the other end.
1335 if (Asm->getTargetData().isLittleEndian())
1336 Offset = FieldSize - (Offset + Size);
1337 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1338
1339 // Here WD_AT_data_member_location points to the anonymous
1340 // field that includes this bit field.
1341 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1342
1343 } else
1344 // This is not a bitfield.
1345 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1346
1347 if (DT.getTag() == dwarf::DW_TAG_inheritance
1348 && DT.isVirtual()) {
1349
1350 // For C++, virtual base classes are not at fixed offset. Use following
1351 // expression to extract appropriate offset from vtable.
1352 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1353
1354 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1355 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1356 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1357 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1358 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1359 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1360 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1361 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1362
1363 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1364 VBaseLocationDie);
1365 } else
1366 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1367
1368 if (DT.isProtected())
1369 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1370 dwarf::DW_ACCESS_protected);
1371 else if (DT.isPrivate())
1372 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1373 dwarf::DW_ACCESS_private);
1374 // Otherwise C++ member and base classes are considered public.
1375 else
1376 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1377 dwarf::DW_ACCESS_public);
1378 if (DT.isVirtual())
1379 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1380 dwarf::DW_VIRTUALITY_virtual);
1381
1382 // Objective-C properties.
1383 StringRef PropertyName = DT.getObjCPropertyName();
1384 if (!PropertyName.empty()) {
1385 addString(MemberDie, dwarf::DW_AT_APPLE_property_name, dwarf::DW_FORM_string,
1386 PropertyName);
1387 StringRef GetterName = DT.getObjCPropertyGetterName();
1388 if (!GetterName.empty())
1389 addString(MemberDie, dwarf::DW_AT_APPLE_property_getter,
1390 dwarf::DW_FORM_string, GetterName);
1391 StringRef SetterName = DT.getObjCPropertySetterName();
1392 if (!SetterName.empty())
1393 addString(MemberDie, dwarf::DW_AT_APPLE_property_setter,
1394 dwarf::DW_FORM_string, SetterName);
1395 unsigned PropertyAttributes = 0;
1396 if (DT.isReadOnlyObjCProperty())
1397 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1398 if (DT.isReadWriteObjCProperty())
1399 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1400 if (DT.isAssignObjCProperty())
1401 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1402 if (DT.isRetainObjCProperty())
1403 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1404 if (DT.isCopyObjCProperty())
1405 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1406 if (DT.isNonAtomicObjCProperty())
1407 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1408 if (PropertyAttributes)
1409 addUInt(MemberDie, dwarf::DW_AT_APPLE_property_attribute, 0,
1410 PropertyAttributes);
1411 }
1412 return MemberDie;
1413 }
1414