1 #include "DwarfCompileUnit.h"
3 #include "llvm/CodeGen/MachineFunction.h"
4 #include "llvm/IR/DataLayout.h"
5 #include "llvm/IR/GlobalValue.h"
6 #include "llvm/IR/GlobalVariable.h"
7 #include "llvm/IR/Instruction.h"
8 #include "llvm/MC/MCAsmInfo.h"
9 #include "llvm/MC/MCStreamer.h"
10 #include "llvm/Target/TargetFrameLowering.h"
11 #include "llvm/Target/TargetLoweringObjectFile.h"
12 #include "llvm/Target/TargetMachine.h"
13 #include "llvm/Target/TargetSubtargetInfo.h"
14 #include "llvm/Target/TargetRegisterInfo.h"
18 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DICompileUnit Node,
19 AsmPrinter *A, DwarfDebug *DW,
21 : DwarfUnit(UID, dwarf::DW_TAG_compile_unit, Node, A, DW, DWU) {
22 insertDIE(Node, &getUnitDie());
25 /// addLabelAddress - Add a dwarf label attribute data and value using
26 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
28 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
29 const MCSymbol *Label) {
31 // Don't use the address pool in non-fission or in the skeleton unit itself.
32 // FIXME: Once GDB supports this, it's probably worthwhile using the address
33 // pool from the skeleton - maybe even in non-fission (possibly fewer
34 // relocations by sharing them in the pool, but we have other ideas about how
35 // to reduce the number of relocations as well/instead).
36 if (!DD->useSplitDwarf() || !Skeleton)
37 return addLocalLabelAddress(Die, Attribute, Label);
40 DD->addArangeLabel(SymbolCU(this, Label));
42 unsigned idx = DD->getAddressPool().getIndex(Label);
43 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
44 Die.addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
47 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
48 dwarf::Attribute Attribute,
49 const MCSymbol *Label) {
51 DD->addArangeLabel(SymbolCU(this, Label));
53 Die.addValue(Attribute, dwarf::DW_FORM_addr,
54 Label ? (DIEValue *)new (DIEValueAllocator) DIELabel(Label)
55 : new (DIEValueAllocator) DIEInteger(0));
58 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName,
60 // If we print assembly, we can't separate .file entries according to
61 // compile units. Thus all files will belong to the default compile unit.
63 // FIXME: add a better feature test than hasRawTextSupport. Even better,
64 // extend .file to support this.
65 return Asm->OutStreamer.EmitDwarfFileDirective(
67 Asm->OutStreamer.hasRawTextSupport() ? 0 : getUniqueID());
70 // Return const expression if value is a GEP to access merged global
72 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
73 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
74 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
75 if (!CE || CE->getNumOperands() != 3 ||
76 CE->getOpcode() != Instruction::GetElementPtr)
79 // First operand points to a global struct.
80 Value *Ptr = CE->getOperand(0);
81 if (!isa<GlobalValue>(Ptr) ||
82 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
85 // Second operand is zero.
86 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
87 if (!CI || !CI->isZero())
90 // Third operand is offset.
91 if (!isa<ConstantInt>(CE->getOperand(2)))
97 /// getOrCreateGlobalVariableDIE - get or create global variable DIE.
98 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(DIGlobalVariable GV) {
99 // Check for pre-existence.
100 if (DIE *Die = getDIE(GV))
103 assert(GV.isGlobalVariable());
105 DIScope GVContext = GV.getContext();
106 DIType GTy = DD->resolve(GV.getType());
108 // If this is a static data member definition, some attributes belong
109 // to the declaration DIE.
110 DIE *VariableDIE = nullptr;
111 bool IsStaticMember = false;
112 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
113 if (SDMDecl.Verify()) {
114 assert(SDMDecl.isStaticMember() && "Expected static member decl");
115 // We need the declaration DIE that is in the static member's class.
116 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
117 IsStaticMember = true;
120 // If this is not a static data member definition, create the variable
121 // DIE and add the initial set of attributes to it.
123 // Construct the context before querying for the existence of the DIE in
124 // case such construction creates the DIE.
125 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
128 VariableDIE = &createAndAddDIE(GV.getTag(), *ContextDIE, GV);
130 // Add name and type.
131 addString(*VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
132 addType(*VariableDIE, GTy);
135 if (!GV.isLocalToUnit())
136 addFlag(*VariableDIE, dwarf::DW_AT_external);
138 // Add line number info.
139 addSourceLine(*VariableDIE, GV);
143 bool addToAccelTable = false;
144 DIE *VariableSpecDIE = nullptr;
145 bool isGlobalVariable = GV.getGlobal() != nullptr;
146 if (isGlobalVariable) {
147 addToAccelTable = true;
148 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
149 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
150 if (GV.getGlobal()->isThreadLocal()) {
151 // FIXME: Make this work with -gsplit-dwarf.
152 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
153 assert((PointerSize == 4 || PointerSize == 8) &&
154 "Add support for other sizes if necessary");
155 // Based on GCC's support for TLS:
156 if (!DD->useSplitDwarf()) {
157 // 1) Start with a constNu of the appropriate pointer size
158 addUInt(*Loc, dwarf::DW_FORM_data1,
159 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
160 // 2) containing the (relocated) offset of the TLS variable
161 // within the module's TLS block.
162 addExpr(*Loc, dwarf::DW_FORM_udata,
163 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
165 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
166 addUInt(*Loc, dwarf::DW_FORM_udata,
167 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
169 // 3) followed by a custom OP to make the debugger do a TLS lookup.
170 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
172 DD->addArangeLabel(SymbolCU(this, Sym));
173 addOpAddress(*Loc, Sym);
175 // A static member's declaration is already flagged as such.
176 if (!SDMDecl.Verify() && !GV.isDefinition())
177 addFlag(*VariableDIE, dwarf::DW_AT_declaration);
178 // Do not create specification DIE if context is either compile unit
180 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
181 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
182 // Create specification DIE.
183 VariableSpecDIE = &createAndAddDIE(dwarf::DW_TAG_variable, UnitDie);
184 addDIEEntry(*VariableSpecDIE, dwarf::DW_AT_specification, *VariableDIE);
185 addBlock(*VariableSpecDIE, dwarf::DW_AT_location, Loc);
186 // A static member's declaration is already flagged as such.
187 if (!SDMDecl.Verify())
188 addFlag(*VariableDIE, dwarf::DW_AT_declaration);
190 addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
192 // Add the linkage name.
193 StringRef LinkageName = GV.getLinkageName();
194 if (!LinkageName.empty())
195 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
196 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
198 addString(IsStaticMember && VariableSpecDIE ? *VariableSpecDIE
200 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
201 : dwarf::DW_AT_MIPS_linkage_name,
202 GlobalValue::getRealLinkageName(LinkageName));
203 } else if (const ConstantInt *CI =
204 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
205 // AT_const_value was added when the static member was created. To avoid
206 // emitting AT_const_value multiple times, we only add AT_const_value when
207 // it is not a static member.
209 addConstantValue(*VariableDIE, CI, GTy);
210 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV.getConstant())) {
211 addToAccelTable = true;
212 // GV is a merged global.
213 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
214 Value *Ptr = CE->getOperand(0);
215 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
216 DD->addArangeLabel(SymbolCU(this, Sym));
217 addOpAddress(*Loc, Sym);
218 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
219 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
220 addUInt(*Loc, dwarf::DW_FORM_udata,
221 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
222 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
223 addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
226 DIE *ResultDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
228 if (addToAccelTable) {
229 DD->addAccelName(GV.getName(), *ResultDIE);
231 // If the linkage name is different than the name, go ahead and output
232 // that as well into the name table.
233 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
234 DD->addAccelName(GV.getLinkageName(), *ResultDIE);
237 addGlobalName(GV.getName(), *ResultDIE, GV.getContext());
241 void DwarfCompileUnit::addRange(RangeSpan Range) {
242 bool SameAsPrevCU = this == DD->getPrevCU();
244 // If we have no current ranges just add the range and return, otherwise,
245 // check the current section and CU against the previous section and CU we
246 // emitted into and the subprogram was contained within. If these are the
247 // same then extend our current range, otherwise add this as a new range.
248 if (CURanges.empty() || !SameAsPrevCU ||
249 (&CURanges.back().getEnd()->getSection() !=
250 &Range.getEnd()->getSection())) {
251 CURanges.push_back(Range);
255 CURanges.back().setEnd(Range.getEnd());
258 void DwarfCompileUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
259 const MCSymbol *Label,
260 const MCSymbol *Sec) {
261 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
262 addLabel(Die, Attribute,
263 DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
264 : dwarf::DW_FORM_data4,
267 addSectionDelta(Die, Attribute, Label, Sec);
270 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
271 // Define start line table label for each Compile Unit.
272 MCSymbol *LineTableStartSym =
273 Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
275 stmtListIndex = UnitDie.getValues().size();
277 // DW_AT_stmt_list is a offset of line number information for this
278 // compile unit in debug_line section. For split dwarf this is
279 // left in the skeleton CU and so not included.
280 // The line table entries are not always emitted in assembly, so it
281 // is not okay to use line_table_start here.
282 addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
283 DwarfLineSectionSym);
286 void DwarfCompileUnit::applyStmtList(DIE &D) {
287 D.addValue(dwarf::DW_AT_stmt_list,
288 UnitDie.getAbbrev().getData()[stmtListIndex].getForm(),
289 UnitDie.getValues()[stmtListIndex]);
292 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
293 const MCSymbol *End) {
294 assert(Begin && "Begin label should not be null!");
295 assert(End && "End label should not be null!");
296 assert(Begin->isDefined() && "Invalid starting label");
297 assert(End->isDefined() && "Invalid end label");
299 addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
300 if (DD->getDwarfVersion() < 4)
301 addLabelAddress(D, dwarf::DW_AT_high_pc, End);
303 addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
306 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
307 // and DW_AT_high_pc attributes. If there are global variables in this
308 // scope then create and insert DIEs for these variables.
309 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(DISubprogram SP) {
310 DIE *SPDie = getOrCreateSubprogramDIE(SP);
312 attachLowHighPC(*SPDie, DD->getFunctionBeginSym(), DD->getFunctionEndSym());
313 if (!DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
314 *DD->getCurrentFunction()))
315 addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
317 // Only include DW_AT_frame_base in full debug info
318 if (getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly) {
319 const TargetRegisterInfo *RI =
320 Asm->TM.getSubtargetImpl()->getRegisterInfo();
321 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
322 addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
325 // Add name to the name table, we do this here because we're guaranteed
326 // to have concrete versions of our DW_TAG_subprogram nodes.
327 DD->addSubprogramNames(SP, *SPDie);
332 // Construct a DIE for this scope.
333 void DwarfCompileUnit::constructScopeDIE(
334 LexicalScope *Scope, SmallVectorImpl<std::unique_ptr<DIE>> &FinalChildren) {
335 if (!Scope || !Scope->getScopeNode())
338 DIScope DS(Scope->getScopeNode());
340 assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
341 "Only handle inlined subprograms here, use "
342 "constructSubprogramScopeDIE for non-inlined "
345 SmallVector<std::unique_ptr<DIE>, 8> Children;
347 // We try to create the scope DIE first, then the children DIEs. This will
348 // avoid creating un-used children then removing them later when we find out
349 // the scope DIE is null.
350 std::unique_ptr<DIE> ScopeDIE;
351 if (Scope->getParent() && DS.isSubprogram()) {
352 ScopeDIE = constructInlinedScopeDIE(Scope);
355 // We create children when the scope DIE is not null.
356 DD->createScopeChildrenDIE(*this, Scope, Children);
358 // Early exit when we know the scope DIE is going to be null.
359 if (DD->isLexicalScopeDIENull(Scope))
362 unsigned ChildScopeCount;
364 // We create children here when we know the scope DIE is not going to be
365 // null and the children will be added to the scope DIE.
366 DD->createScopeChildrenDIE(*this, Scope, Children, &ChildScopeCount);
368 // There is no need to emit empty lexical block DIE.
369 for (const auto &E : DD->findImportedEntitiesForScope(DS))
371 constructImportedEntityDIE(DIImportedEntity(E.second)));
372 // If there are only other scopes as children, put them directly in the
373 // parent instead, as this scope would serve no purpose.
374 if (Children.size() == ChildScopeCount) {
375 FinalChildren.insert(FinalChildren.end(),
376 std::make_move_iterator(Children.begin()),
377 std::make_move_iterator(Children.end()));
380 ScopeDIE = constructLexicalScopeDIE(Scope);
381 assert(ScopeDIE && "Scope DIE should not be null.");
385 for (auto &I : Children)
386 ScopeDIE->addChild(std::move(I));
388 FinalChildren.push_back(std::move(ScopeDIE));
391 void DwarfCompileUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
392 const MCSymbol *Hi, const MCSymbol *Lo) {
393 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
394 Die.addValue(Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
395 : dwarf::DW_FORM_data4,
400 DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
401 const SmallVectorImpl<InsnRange> &Range) {
402 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
403 // emitting it appropriately.
405 Asm->GetTempSymbol("debug_ranges", DD->getNextRangeNumber());
407 auto *RangeSectionSym = DD->getRangeSectionSym();
409 // Under fission, ranges are specified by constant offsets relative to the
410 // CU's DW_AT_GNU_ranges_base.
411 if (DD->useSplitDwarf())
412 addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym, RangeSectionSym);
414 addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, RangeSym, RangeSectionSym);
416 RangeSpanList List(RangeSym);
417 for (const InsnRange &R : Range)
418 List.addRange(RangeSpan(DD->getLabelBeforeInsn(R.first),
419 DD->getLabelAfterInsn(R.second)));
421 // Add the range list to the set of ranges to be emitted.
422 addRangeList(std::move(List));
425 void DwarfCompileUnit::attachRangesOrLowHighPC(
426 DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
427 assert(!Ranges.empty());
428 if (Ranges.size() == 1)
429 attachLowHighPC(Die, DD->getLabelBeforeInsn(Ranges.front().first),
430 DD->getLabelAfterInsn(Ranges.front().second));
432 addScopeRangeList(Die, Ranges);
435 // This scope represents inlined body of a function. Construct DIE to
436 // represent this concrete inlined copy of the function.
438 DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
439 assert(Scope->getScopeNode());
440 DIScope DS(Scope->getScopeNode());
441 DISubprogram InlinedSP = getDISubprogram(DS);
442 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
443 // was inlined from another compile unit.
444 DIE *OriginDIE = DD->getAbstractSPDies()[InlinedSP];
445 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
447 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
448 addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
450 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
452 // Add the call site information to the DIE.
453 DILocation DL(Scope->getInlinedAt());
454 addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
455 getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
456 addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
458 // Add name to the name table, we do this here because we're guaranteed
459 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
460 DD->addSubprogramNames(InlinedSP, *ScopeDIE);
465 // Construct new DW_TAG_lexical_block for this scope and attach
466 // DW_AT_low_pc/DW_AT_high_pc labels.
468 DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
469 if (DD->isLexicalScopeDIENull(Scope))
472 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
473 if (Scope->isAbstractScope())
476 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
481 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
482 std::unique_ptr<DIE> DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
484 auto D = constructVariableDIEImpl(DV, Abstract);
490 DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
492 // Define variable debug information entry.
493 auto VariableDie = make_unique<DIE>(DV.getTag());
496 applyVariableAttributes(DV, *VariableDie);
500 // Add variable address.
502 unsigned Offset = DV.getDotDebugLocOffset();
504 addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
508 // Check if variable is described by a DBG_VALUE instruction.
509 if (const MachineInstr *DVInsn = DV.getMInsn()) {
510 assert(DVInsn->getNumOperands() == 4);
511 if (DVInsn->getOperand(0).isReg()) {
512 const MachineOperand RegOp = DVInsn->getOperand(0);
513 // If the second operand is an immediate, this is an indirect value.
514 if (DVInsn->getOperand(1).isImm()) {
515 MachineLocation Location(RegOp.getReg(),
516 DVInsn->getOperand(1).getImm());
517 addVariableAddress(DV, *VariableDie, Location);
518 } else if (RegOp.getReg())
519 addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
520 } else if (DVInsn->getOperand(0).isImm())
521 addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
522 else if (DVInsn->getOperand(0).isFPImm())
523 addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
524 else if (DVInsn->getOperand(0).isCImm())
525 addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
531 // .. else use frame index.
532 int FI = DV.getFrameIndex();
534 unsigned FrameReg = 0;
535 const TargetFrameLowering *TFI =
536 Asm->TM.getSubtargetImpl()->getFrameLowering();
537 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
538 MachineLocation Location(FrameReg, Offset);
539 addVariableAddress(DV, *VariableDie, Location);
545 } // end llvm namespace