Reformatting accidentally left out of r219057
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfCompileUnit.cpp
1 #include "DwarfCompileUnit.h"
2
3 #include "llvm/IR/DataLayout.h"
4 #include "llvm/IR/GlobalValue.h"
5 #include "llvm/IR/GlobalVariable.h"
6 #include "llvm/IR/Instruction.h"
7 #include "llvm/MC/MCAsmInfo.h"
8 #include "llvm/MC/MCStreamer.h"
9 #include "llvm/Target/TargetLoweringObjectFile.h"
10
11 namespace llvm {
12
13 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DICompileUnit Node,
14                                    AsmPrinter *A, DwarfDebug *DW,
15                                    DwarfFile *DWU)
16     : DwarfUnit(UID, dwarf::DW_TAG_compile_unit, Node, A, DW, DWU) {
17   insertDIE(Node, &getUnitDie());
18 }
19
20 /// addLabelAddress - Add a dwarf label attribute data and value using
21 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
22 ///
23 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
24                                        const MCSymbol *Label) {
25
26   // Don't use the address pool in non-fission or in the skeleton unit itself.
27   // FIXME: Once GDB supports this, it's probably worthwhile using the address
28   // pool from the skeleton - maybe even in non-fission (possibly fewer
29   // relocations by sharing them in the pool, but we have other ideas about how
30   // to reduce the number of relocations as well/instead).
31   if (!DD->useSplitDwarf() || !Skeleton)
32     return addLocalLabelAddress(Die, Attribute, Label);
33
34   if (Label)
35     DD->addArangeLabel(SymbolCU(this, Label));
36
37   unsigned idx = DD->getAddressPool().getIndex(Label);
38   DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
39   Die.addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
40 }
41
42 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
43                                             dwarf::Attribute Attribute,
44                                             const MCSymbol *Label) {
45   if (Label)
46     DD->addArangeLabel(SymbolCU(this, Label));
47
48   Die.addValue(Attribute, dwarf::DW_FORM_addr,
49                Label ? (DIEValue *)new (DIEValueAllocator) DIELabel(Label)
50                      : new (DIEValueAllocator) DIEInteger(0));
51 }
52
53 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName,
54                                                StringRef DirName) {
55   // If we print assembly, we can't separate .file entries according to
56   // compile units. Thus all files will belong to the default compile unit.
57
58   // FIXME: add a better feature test than hasRawTextSupport. Even better,
59   // extend .file to support this.
60   return Asm->OutStreamer.EmitDwarfFileDirective(
61       0, DirName, FileName,
62       Asm->OutStreamer.hasRawTextSupport() ? 0 : getUniqueID());
63 }
64
65 // Return const expression if value is a GEP to access merged global
66 // constant. e.g.
67 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
68 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
69   const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
70   if (!CE || CE->getNumOperands() != 3 ||
71       CE->getOpcode() != Instruction::GetElementPtr)
72     return nullptr;
73
74   // First operand points to a global struct.
75   Value *Ptr = CE->getOperand(0);
76   if (!isa<GlobalValue>(Ptr) ||
77       !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
78     return nullptr;
79
80   // Second operand is zero.
81   const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
82   if (!CI || !CI->isZero())
83     return nullptr;
84
85   // Third operand is offset.
86   if (!isa<ConstantInt>(CE->getOperand(2)))
87     return nullptr;
88
89   return CE;
90 }
91
92 /// getOrCreateGlobalVariableDIE - get or create global variable DIE.
93 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(DIGlobalVariable GV) {
94   // Check for pre-existence.
95   if (DIE *Die = getDIE(GV))
96     return Die;
97
98   assert(GV.isGlobalVariable());
99
100   DIScope GVContext = GV.getContext();
101   DIType GTy = DD->resolve(GV.getType());
102
103   // If this is a static data member definition, some attributes belong
104   // to the declaration DIE.
105   DIE *VariableDIE = nullptr;
106   bool IsStaticMember = false;
107   DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
108   if (SDMDecl.Verify()) {
109     assert(SDMDecl.isStaticMember() && "Expected static member decl");
110     // We need the declaration DIE that is in the static member's class.
111     VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
112     IsStaticMember = true;
113   }
114
115   // If this is not a static data member definition, create the variable
116   // DIE and add the initial set of attributes to it.
117   if (!VariableDIE) {
118     // Construct the context before querying for the existence of the DIE in
119     // case such construction creates the DIE.
120     DIE *ContextDIE = getOrCreateContextDIE(GVContext);
121
122     // Add to map.
123     VariableDIE = &createAndAddDIE(GV.getTag(), *ContextDIE, GV);
124
125     // Add name and type.
126     addString(*VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
127     addType(*VariableDIE, GTy);
128
129     // Add scoping info.
130     if (!GV.isLocalToUnit())
131       addFlag(*VariableDIE, dwarf::DW_AT_external);
132
133     // Add line number info.
134     addSourceLine(*VariableDIE, GV);
135   }
136
137   // Add location.
138   bool addToAccelTable = false;
139   DIE *VariableSpecDIE = nullptr;
140   bool isGlobalVariable = GV.getGlobal() != nullptr;
141   if (isGlobalVariable) {
142     addToAccelTable = true;
143     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
144     const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
145     if (GV.getGlobal()->isThreadLocal()) {
146       // FIXME: Make this work with -gsplit-dwarf.
147       unsigned PointerSize = Asm->getDataLayout().getPointerSize();
148       assert((PointerSize == 4 || PointerSize == 8) &&
149              "Add support for other sizes if necessary");
150       // Based on GCC's support for TLS:
151       if (!DD->useSplitDwarf()) {
152         // 1) Start with a constNu of the appropriate pointer size
153         addUInt(*Loc, dwarf::DW_FORM_data1,
154                 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
155         // 2) containing the (relocated) offset of the TLS variable
156         //    within the module's TLS block.
157         addExpr(*Loc, dwarf::DW_FORM_udata,
158                 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
159       } else {
160         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
161         addUInt(*Loc, dwarf::DW_FORM_udata,
162                 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
163       }
164       // 3) followed by a custom OP to make the debugger do a TLS lookup.
165       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
166     } else {
167       DD->addArangeLabel(SymbolCU(this, Sym));
168       addOpAddress(*Loc, Sym);
169     }
170     // A static member's declaration is already flagged as such.
171     if (!SDMDecl.Verify() && !GV.isDefinition())
172       addFlag(*VariableDIE, dwarf::DW_AT_declaration);
173     // Do not create specification DIE if context is either compile unit
174     // or a subprogram.
175     if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
176         !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
177       // Create specification DIE.
178       VariableSpecDIE = &createAndAddDIE(dwarf::DW_TAG_variable, UnitDie);
179       addDIEEntry(*VariableSpecDIE, dwarf::DW_AT_specification, *VariableDIE);
180       addBlock(*VariableSpecDIE, dwarf::DW_AT_location, Loc);
181       // A static member's declaration is already flagged as such.
182       if (!SDMDecl.Verify())
183         addFlag(*VariableDIE, dwarf::DW_AT_declaration);
184     } else {
185       addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
186     }
187     // Add the linkage name.
188     StringRef LinkageName = GV.getLinkageName();
189     if (!LinkageName.empty())
190       // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
191       // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
192       // TAG_variable.
193       addString(IsStaticMember && VariableSpecDIE ? *VariableSpecDIE
194                                                   : *VariableDIE,
195                 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
196                                            : dwarf::DW_AT_MIPS_linkage_name,
197                 GlobalValue::getRealLinkageName(LinkageName));
198   } else if (const ConstantInt *CI =
199                  dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
200     // AT_const_value was added when the static member was created. To avoid
201     // emitting AT_const_value multiple times, we only add AT_const_value when
202     // it is not a static member.
203     if (!IsStaticMember)
204       addConstantValue(*VariableDIE, CI, GTy);
205   } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV.getConstant())) {
206     addToAccelTable = true;
207     // GV is a merged global.
208     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
209     Value *Ptr = CE->getOperand(0);
210     MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
211     DD->addArangeLabel(SymbolCU(this, Sym));
212     addOpAddress(*Loc, Sym);
213     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
214     SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
215     addUInt(*Loc, dwarf::DW_FORM_udata,
216             Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
217     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
218     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
219   }
220
221   DIE *ResultDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
222
223   if (addToAccelTable) {
224     DD->addAccelName(GV.getName(), *ResultDIE);
225
226     // If the linkage name is different than the name, go ahead and output
227     // that as well into the name table.
228     if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
229       DD->addAccelName(GV.getLinkageName(), *ResultDIE);
230   }
231
232   addGlobalName(GV.getName(), *ResultDIE, GV.getContext());
233   return ResultDIE;
234 }
235
236 void DwarfCompileUnit::addRange(RangeSpan Range) {
237   bool SameAsPrevCU = this == DD->getPrevCU();
238   DD->setPrevCU(this);
239   // If we have no current ranges just add the range and return, otherwise,
240   // check the current section and CU against the previous section and CU we
241   // emitted into and the subprogram was contained within. If these are the
242   // same then extend our current range, otherwise add this as a new range.
243   if (CURanges.empty() || !SameAsPrevCU ||
244       (&CURanges.back().getEnd()->getSection() !=
245        &Range.getEnd()->getSection())) {
246     CURanges.push_back(Range);
247     return;
248   }
249
250   CURanges.back().setEnd(Range.getEnd());
251 }
252
253 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
254   // Define start line table label for each Compile Unit.
255   MCSymbol *LineTableStartSym =
256       Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
257
258   stmtListIndex = UnitDie.getValues().size();
259
260   // DW_AT_stmt_list is a offset of line number information for this
261   // compile unit in debug_line section. For split dwarf this is
262   // left in the skeleton CU and so not included.
263   // The line table entries are not always emitted in assembly, so it
264   // is not okay to use line_table_start here.
265   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
266     addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym);
267   else
268     addSectionDelta(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
269                     DwarfLineSectionSym);
270 }
271
272 void DwarfCompileUnit::applyStmtList(DIE &D) {
273   D.addValue(dwarf::DW_AT_stmt_list,
274              UnitDie.getAbbrev().getData()[stmtListIndex].getForm(),
275              UnitDie.getValues()[stmtListIndex]);
276 }
277
278 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
279                                        const MCSymbol *End) {
280   assert(Begin && "Begin label should not be null!");
281   assert(End && "End label should not be null!");
282   assert(Begin->isDefined() && "Invalid starting label");
283   assert(End->isDefined() && "Invalid end label");
284
285   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
286   if (DD->getDwarfVersion() < 4)
287     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
288   else
289     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
290 }
291
292 } // end llvm namespace