[Alignment][NFC] Use Align with TargetLowering::setMinFunctionAlignment
[llvm-core.git] / lib / CodeGen / AsmPrinter / DwarfCompileUnit.cpp
blob626486a5761e1990fad2423ca9d7d372949efa79
1 //===- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Units ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for constructing a dwarf compile unit.
11 //===----------------------------------------------------------------------===//
13 #include "DwarfCompileUnit.h"
14 #include "AddressPool.h"
15 #include "DwarfDebug.h"
16 #include "DwarfExpression.h"
17 #include "DwarfUnit.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/BinaryFormat/Dwarf.h"
24 #include "llvm/CodeGen/AsmPrinter.h"
25 #include "llvm/CodeGen/DIE.h"
26 #include "llvm/CodeGen/LexicalScopes.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineOperand.h"
30 #include "llvm/CodeGen/TargetFrameLowering.h"
31 #include "llvm/CodeGen/TargetRegisterInfo.h"
32 #include "llvm/CodeGen/TargetSubtargetInfo.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/DebugInfo.h"
35 #include "llvm/IR/DebugInfoMetadata.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/MC/MCSection.h"
38 #include "llvm/MC/MCStreamer.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/MC/MachineLocation.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Target/TargetLoweringObjectFile.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include <algorithm>
46 #include <cassert>
47 #include <cstdint>
48 #include <iterator>
49 #include <memory>
50 #include <string>
51 #include <utility>
53 using namespace llvm;
55 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
56 AsmPrinter *A, DwarfDebug *DW,
57 DwarfFile *DWU)
58 : DwarfUnit(dwarf::DW_TAG_compile_unit, Node, A, DW, DWU), UniqueID(UID) {
59 insertDIE(Node, &getUnitDie());
60 MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
63 /// addLabelAddress - Add a dwarf label attribute data and value using
64 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
65 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
66 const MCSymbol *Label) {
67 // Don't use the address pool in non-fission or in the skeleton unit itself.
68 // FIXME: Once GDB supports this, it's probably worthwhile using the address
69 // pool from the skeleton - maybe even in non-fission (possibly fewer
70 // relocations by sharing them in the pool, but we have other ideas about how
71 // to reduce the number of relocations as well/instead).
72 if ((!DD->useSplitDwarf() || !Skeleton) && DD->getDwarfVersion() < 5)
73 return addLocalLabelAddress(Die, Attribute, Label);
75 if (Label)
76 DD->addArangeLabel(SymbolCU(this, Label));
78 unsigned idx = DD->getAddressPool().getIndex(Label);
79 Die.addValue(DIEValueAllocator, Attribute,
80 DD->getDwarfVersion() >= 5 ? dwarf::DW_FORM_addrx
81 : dwarf::DW_FORM_GNU_addr_index,
82 DIEInteger(idx));
85 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
86 dwarf::Attribute Attribute,
87 const MCSymbol *Label) {
88 if (Label)
89 DD->addArangeLabel(SymbolCU(this, Label));
91 if (Label)
92 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
93 DIELabel(Label));
94 else
95 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
96 DIEInteger(0));
99 unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
100 // If we print assembly, we can't separate .file entries according to
101 // compile units. Thus all files will belong to the default compile unit.
103 // FIXME: add a better feature test than hasRawTextSupport. Even better,
104 // extend .file to support this.
105 unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
106 if (!File)
107 return Asm->OutStreamer->EmitDwarfFileDirective(0, "", "", None, None, CUID);
108 return Asm->OutStreamer->EmitDwarfFileDirective(
109 0, File->getDirectory(), File->getFilename(), getMD5AsBytes(File),
110 File->getSource(), CUID);
113 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
114 const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
115 // Check for pre-existence.
116 if (DIE *Die = getDIE(GV))
117 return Die;
119 assert(GV);
121 auto *GVContext = GV->getScope();
122 const DIType *GTy = GV->getType();
124 // Construct the context before querying for the existence of the DIE in
125 // case such construction creates the DIE.
126 auto *CB = GVContext ? dyn_cast<DICommonBlock>(GVContext) : nullptr;
127 DIE *ContextDIE = CB ? getOrCreateCommonBlock(CB, GlobalExprs)
128 : getOrCreateContextDIE(GVContext);
130 // Add to map.
131 DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
132 DIScope *DeclContext;
133 if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
134 DeclContext = SDMDecl->getScope();
135 assert(SDMDecl->isStaticMember() && "Expected static member decl");
136 assert(GV->isDefinition());
137 // We need the declaration DIE that is in the static member's class.
138 DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
139 addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
140 // If the global variable's type is different from the one in the class
141 // member type, assume that it's more specific and also emit it.
142 if (GTy != SDMDecl->getBaseType())
143 addType(*VariableDIE, GTy);
144 } else {
145 DeclContext = GV->getScope();
146 // Add name and type.
147 addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
148 addType(*VariableDIE, GTy);
150 // Add scoping info.
151 if (!GV->isLocalToUnit())
152 addFlag(*VariableDIE, dwarf::DW_AT_external);
154 // Add line number info.
155 addSourceLine(*VariableDIE, GV);
158 if (!GV->isDefinition())
159 addFlag(*VariableDIE, dwarf::DW_AT_declaration);
160 else
161 addGlobalName(GV->getName(), *VariableDIE, DeclContext);
163 if (uint32_t AlignInBytes = GV->getAlignInBytes())
164 addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
165 AlignInBytes);
167 if (MDTuple *TP = GV->getTemplateParams())
168 addTemplateParams(*VariableDIE, DINodeArray(TP));
170 // Add location.
171 addLocationAttribute(VariableDIE, GV, GlobalExprs);
173 return VariableDIE;
176 void DwarfCompileUnit::addLocationAttribute(
177 DIE *VariableDIE, const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
178 bool addToAccelTable = false;
179 DIELoc *Loc = nullptr;
180 Optional<unsigned> NVPTXAddressSpace;
181 std::unique_ptr<DIEDwarfExpression> DwarfExpr;
182 for (const auto &GE : GlobalExprs) {
183 const GlobalVariable *Global = GE.Var;
184 const DIExpression *Expr = GE.Expr;
186 // For compatibility with DWARF 3 and earlier,
187 // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) becomes
188 // DW_AT_const_value(X).
189 if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
190 addToAccelTable = true;
191 addConstantValue(*VariableDIE, /*Unsigned=*/true, Expr->getElement(1));
192 break;
195 // We cannot describe the location of dllimport'd variables: the
196 // computation of their address requires loads from the IAT.
197 if (Global && Global->hasDLLImportStorageClass())
198 continue;
200 // Nothing to describe without address or constant.
201 if (!Global && (!Expr || !Expr->isConstant()))
202 continue;
204 if (Global && Global->isThreadLocal() &&
205 !Asm->getObjFileLowering().supportDebugThreadLocalLocation())
206 continue;
208 if (!Loc) {
209 addToAccelTable = true;
210 Loc = new (DIEValueAllocator) DIELoc;
211 DwarfExpr = std::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
214 if (Expr) {
215 // According to
216 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
217 // cuda-gdb requires DW_AT_address_class for all variables to be able to
218 // correctly interpret address space of the variable address.
219 // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
220 // sequence for the NVPTX + gdb target.
221 unsigned LocalNVPTXAddressSpace;
222 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
223 const DIExpression *NewExpr =
224 DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
225 if (NewExpr != Expr) {
226 Expr = NewExpr;
227 NVPTXAddressSpace = LocalNVPTXAddressSpace;
230 DwarfExpr->addFragmentOffset(Expr);
233 if (Global) {
234 const MCSymbol *Sym = Asm->getSymbol(Global);
235 if (Global->isThreadLocal()) {
236 if (Asm->TM.useEmulatedTLS()) {
237 // TODO: add debug info for emulated thread local mode.
238 } else {
239 // FIXME: Make this work with -gsplit-dwarf.
240 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
241 assert((PointerSize == 4 || PointerSize == 8) &&
242 "Add support for other sizes if necessary");
243 // Based on GCC's support for TLS:
244 if (!DD->useSplitDwarf()) {
245 // 1) Start with a constNu of the appropriate pointer size
246 addUInt(*Loc, dwarf::DW_FORM_data1,
247 PointerSize == 4 ? dwarf::DW_OP_const4u
248 : dwarf::DW_OP_const8u);
249 // 2) containing the (relocated) offset of the TLS variable
250 // within the module's TLS block.
251 addExpr(*Loc, dwarf::DW_FORM_udata,
252 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
253 } else {
254 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
255 addUInt(*Loc, dwarf::DW_FORM_udata,
256 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
258 // 3) followed by an OP to make the debugger do a TLS lookup.
259 addUInt(*Loc, dwarf::DW_FORM_data1,
260 DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
261 : dwarf::DW_OP_form_tls_address);
263 } else {
264 DD->addArangeLabel(SymbolCU(this, Sym));
265 addOpAddress(*Loc, Sym);
268 // Global variables attached to symbols are memory locations.
269 // It would be better if this were unconditional, but malformed input that
270 // mixes non-fragments and fragments for the same variable is too expensive
271 // to detect in the verifier.
272 if (DwarfExpr->isUnknownLocation())
273 DwarfExpr->setMemoryLocationKind();
274 DwarfExpr->addExpression(Expr);
276 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
277 // According to
278 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
279 // cuda-gdb requires DW_AT_address_class for all variables to be able to
280 // correctly interpret address space of the variable address.
281 const unsigned NVPTX_ADDR_global_space = 5;
282 addUInt(*VariableDIE, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
283 NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_global_space);
285 if (Loc)
286 addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
288 if (DD->useAllLinkageNames())
289 addLinkageName(*VariableDIE, GV->getLinkageName());
291 if (addToAccelTable) {
292 DD->addAccelName(*CUNode, GV->getName(), *VariableDIE);
294 // If the linkage name is different than the name, go ahead and output
295 // that as well into the name table.
296 if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
297 DD->useAllLinkageNames())
298 DD->addAccelName(*CUNode, GV->getLinkageName(), *VariableDIE);
302 DIE *DwarfCompileUnit::getOrCreateCommonBlock(
303 const DICommonBlock *CB, ArrayRef<GlobalExpr> GlobalExprs) {
304 // Construct the context before querying for the existence of the DIE in case
305 // such construction creates the DIE.
306 DIE *ContextDIE = getOrCreateContextDIE(CB->getScope());
308 if (DIE *NDie = getDIE(CB))
309 return NDie;
310 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_common_block, *ContextDIE, CB);
311 StringRef Name = CB->getName().empty() ? "_BLNK_" : CB->getName();
312 addString(NDie, dwarf::DW_AT_name, Name);
313 addGlobalName(Name, NDie, CB->getScope());
314 if (CB->getFile())
315 addSourceLine(NDie, CB->getLineNo(), CB->getFile());
316 if (DIGlobalVariable *V = CB->getDecl())
317 getCU().addLocationAttribute(&NDie, V, GlobalExprs);
318 return &NDie;
321 void DwarfCompileUnit::addRange(RangeSpan Range) {
322 bool SameAsPrevCU = this == DD->getPrevCU();
323 DD->setPrevCU(this);
324 // If we have no current ranges just add the range and return, otherwise,
325 // check the current section and CU against the previous section and CU we
326 // emitted into and the subprogram was contained within. If these are the
327 // same then extend our current range, otherwise add this as a new range.
328 if (CURanges.empty() || !SameAsPrevCU ||
329 (&CURanges.back().getEnd()->getSection() !=
330 &Range.getEnd()->getSection())) {
331 CURanges.push_back(Range);
332 DD->addSectionLabel(Range.getStart());
333 return;
336 CURanges.back().setEnd(Range.getEnd());
339 void DwarfCompileUnit::initStmtList() {
340 if (CUNode->isDebugDirectivesOnly())
341 return;
343 // Define start line table label for each Compile Unit.
344 MCSymbol *LineTableStartSym;
345 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
346 if (DD->useSectionsAsReferences()) {
347 LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
348 } else {
349 LineTableStartSym =
350 Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
353 // DW_AT_stmt_list is a offset of line number information for this
354 // compile unit in debug_line section. For split dwarf this is
355 // left in the skeleton CU and so not included.
356 // The line table entries are not always emitted in assembly, so it
357 // is not okay to use line_table_start here.
358 StmtListValue =
359 addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
360 TLOF.getDwarfLineSection()->getBeginSymbol());
363 void DwarfCompileUnit::applyStmtList(DIE &D) {
364 D.addValue(DIEValueAllocator, *StmtListValue);
367 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
368 const MCSymbol *End) {
369 assert(Begin && "Begin label should not be null!");
370 assert(End && "End label should not be null!");
371 assert(Begin->isDefined() && "Invalid starting label");
372 assert(End->isDefined() && "Invalid end label");
374 addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
375 if (DD->getDwarfVersion() < 4)
376 addLabelAddress(D, dwarf::DW_AT_high_pc, End);
377 else
378 addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
381 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
382 // and DW_AT_high_pc attributes. If there are global variables in this
383 // scope then create and insert DIEs for these variables.
384 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
385 DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
387 attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd());
388 if (DD->useAppleExtensionAttributes() &&
389 !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
390 *DD->getCurrentFunction()))
391 addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
393 // Only include DW_AT_frame_base in full debug info
394 if (!includeMinimalInlineScopes()) {
395 if (Asm->MF->getTarget().getTargetTriple().isNVPTX()) {
396 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
397 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa);
398 addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
399 } else {
400 const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo();
401 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
402 if (Register::isPhysicalRegister(Location.getReg()))
403 addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
407 // Add name to the name table, we do this here because we're guaranteed
408 // to have concrete versions of our DW_TAG_subprogram nodes.
409 DD->addSubprogramNames(*CUNode, SP, *SPDie);
411 return *SPDie;
414 // Construct a DIE for this scope.
415 void DwarfCompileUnit::constructScopeDIE(
416 LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
417 if (!Scope || !Scope->getScopeNode())
418 return;
420 auto *DS = Scope->getScopeNode();
422 assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
423 "Only handle inlined subprograms here, use "
424 "constructSubprogramScopeDIE for non-inlined "
425 "subprograms");
427 SmallVector<DIE *, 8> Children;
429 // We try to create the scope DIE first, then the children DIEs. This will
430 // avoid creating un-used children then removing them later when we find out
431 // the scope DIE is null.
432 DIE *ScopeDIE;
433 if (Scope->getParent() && isa<DISubprogram>(DS)) {
434 ScopeDIE = constructInlinedScopeDIE(Scope);
435 if (!ScopeDIE)
436 return;
437 // We create children when the scope DIE is not null.
438 createScopeChildrenDIE(Scope, Children);
439 } else {
440 // Early exit when we know the scope DIE is going to be null.
441 if (DD->isLexicalScopeDIENull(Scope))
442 return;
444 bool HasNonScopeChildren = false;
446 // We create children here when we know the scope DIE is not going to be
447 // null and the children will be added to the scope DIE.
448 createScopeChildrenDIE(Scope, Children, &HasNonScopeChildren);
450 // If there are only other scopes as children, put them directly in the
451 // parent instead, as this scope would serve no purpose.
452 if (!HasNonScopeChildren) {
453 FinalChildren.insert(FinalChildren.end(),
454 std::make_move_iterator(Children.begin()),
455 std::make_move_iterator(Children.end()));
456 return;
458 ScopeDIE = constructLexicalScopeDIE(Scope);
459 assert(ScopeDIE && "Scope DIE should not be null.");
462 // Add children
463 for (auto &I : Children)
464 ScopeDIE->addChild(std::move(I));
466 FinalChildren.push_back(std::move(ScopeDIE));
469 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
470 SmallVector<RangeSpan, 2> Range) {
471 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
473 // Emit the offset into .debug_ranges or .debug_rnglists as a relocatable
474 // label. emitDIE() will handle emitting it appropriately.
475 const MCSymbol *RangeSectionSym =
476 DD->getDwarfVersion() >= 5
477 ? TLOF.getDwarfRnglistsSection()->getBeginSymbol()
478 : TLOF.getDwarfRangesSection()->getBeginSymbol();
480 HasRangeLists = true;
482 // Add the range list to the set of ranges to be emitted.
483 auto IndexAndList =
484 (DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU)
485 ->addRange(*(Skeleton ? Skeleton : this), std::move(Range));
487 uint32_t Index = IndexAndList.first;
488 auto &List = *IndexAndList.second;
490 // Under fission, ranges are specified by constant offsets relative to the
491 // CU's DW_AT_GNU_ranges_base.
492 // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
493 // fission until we support the forms using the .debug_addr section
494 // (DW_RLE_startx_endx etc.).
495 if (DD->getDwarfVersion() >= 5)
496 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_rnglistx, Index);
497 else if (isDwoUnit())
498 addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
499 RangeSectionSym);
500 else
501 addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
502 RangeSectionSym);
505 void DwarfCompileUnit::attachRangesOrLowHighPC(
506 DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
507 if (Ranges.size() == 1 || !DD->useRangesSection()) {
508 const RangeSpan &Front = Ranges.front();
509 const RangeSpan &Back = Ranges.back();
510 attachLowHighPC(Die, Front.getStart(), Back.getEnd());
511 } else
512 addScopeRangeList(Die, std::move(Ranges));
515 void DwarfCompileUnit::attachRangesOrLowHighPC(
516 DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
517 SmallVector<RangeSpan, 2> List;
518 List.reserve(Ranges.size());
519 for (const InsnRange &R : Ranges)
520 List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
521 DD->getLabelAfterInsn(R.second)));
522 attachRangesOrLowHighPC(Die, std::move(List));
525 // This scope represents inlined body of a function. Construct DIE to
526 // represent this concrete inlined copy of the function.
527 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
528 assert(Scope->getScopeNode());
529 auto *DS = Scope->getScopeNode();
530 auto *InlinedSP = getDISubprogram(DS);
531 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
532 // was inlined from another compile unit.
533 DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
534 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
536 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
537 addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
539 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
541 // Add the call site information to the DIE.
542 const DILocation *IA = Scope->getInlinedAt();
543 addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
544 getOrCreateSourceID(IA->getFile()));
545 addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
546 if (IA->getColumn())
547 addUInt(*ScopeDIE, dwarf::DW_AT_call_column, None, IA->getColumn());
548 if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
549 addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
550 IA->getDiscriminator());
552 // Add name to the name table, we do this here because we're guaranteed
553 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
554 DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
556 return ScopeDIE;
559 // Construct new DW_TAG_lexical_block for this scope and attach
560 // DW_AT_low_pc/DW_AT_high_pc labels.
561 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
562 if (DD->isLexicalScopeDIENull(Scope))
563 return nullptr;
565 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
566 if (Scope->isAbstractScope())
567 return ScopeDIE;
569 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
571 return ScopeDIE;
574 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
575 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
576 auto D = constructVariableDIEImpl(DV, Abstract);
577 DV.setDIE(*D);
578 return D;
581 DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
582 const LexicalScope &Scope) {
583 auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
584 insertDIE(DL.getLabel(), LabelDie);
585 DL.setDIE(*LabelDie);
587 if (Scope.isAbstractScope())
588 applyLabelAttributes(DL, *LabelDie);
590 return LabelDie;
593 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
594 bool Abstract) {
595 // Define variable debug information entry.
596 auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
597 insertDIE(DV.getVariable(), VariableDie);
599 if (Abstract) {
600 applyVariableAttributes(DV, *VariableDie);
601 return VariableDie;
604 // Add variable address.
606 unsigned Offset = DV.getDebugLocListIndex();
607 if (Offset != ~0U) {
608 addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
609 return VariableDie;
612 // Check if variable has a single location description.
613 if (auto *DVal = DV.getValueLoc()) {
614 if (DVal->isLocation())
615 addVariableAddress(DV, *VariableDie, DVal->getLoc());
616 else if (DVal->isInt()) {
617 auto *Expr = DV.getSingleExpression();
618 if (Expr && Expr->getNumElements()) {
619 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
620 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
621 // If there is an expression, emit raw unsigned bytes.
622 DwarfExpr.addFragmentOffset(Expr);
623 DwarfExpr.addUnsignedConstant(DVal->getInt());
624 DwarfExpr.addExpression(Expr);
625 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
626 } else
627 addConstantValue(*VariableDie, DVal->getInt(), DV.getType());
628 } else if (DVal->isConstantFP()) {
629 addConstantFPValue(*VariableDie, DVal->getConstantFP());
630 } else if (DVal->isConstantInt()) {
631 addConstantValue(*VariableDie, DVal->getConstantInt(), DV.getType());
633 return VariableDie;
636 // .. else use frame index.
637 if (!DV.hasFrameIndexExprs())
638 return VariableDie;
640 Optional<unsigned> NVPTXAddressSpace;
641 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
642 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
643 for (auto &Fragment : DV.getFrameIndexExprs()) {
644 unsigned FrameReg = 0;
645 const DIExpression *Expr = Fragment.Expr;
646 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
647 int Offset = TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
648 DwarfExpr.addFragmentOffset(Expr);
649 SmallVector<uint64_t, 8> Ops;
650 Ops.push_back(dwarf::DW_OP_plus_uconst);
651 Ops.push_back(Offset);
652 // According to
653 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
654 // cuda-gdb requires DW_AT_address_class for all variables to be able to
655 // correctly interpret address space of the variable address.
656 // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
657 // sequence for the NVPTX + gdb target.
658 unsigned LocalNVPTXAddressSpace;
659 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
660 const DIExpression *NewExpr =
661 DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
662 if (NewExpr != Expr) {
663 Expr = NewExpr;
664 NVPTXAddressSpace = LocalNVPTXAddressSpace;
667 if (Expr)
668 Ops.append(Expr->elements_begin(), Expr->elements_end());
669 DIExpressionCursor Cursor(Ops);
670 DwarfExpr.setMemoryLocationKind();
671 if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
672 addOpAddress(*Loc, FrameSymbol);
673 else
674 DwarfExpr.addMachineRegExpression(
675 *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
676 DwarfExpr.addExpression(std::move(Cursor));
678 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
679 // According to
680 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
681 // cuda-gdb requires DW_AT_address_class for all variables to be able to
682 // correctly interpret address space of the variable address.
683 const unsigned NVPTX_ADDR_local_space = 6;
684 addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
685 NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space);
687 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
688 if (DwarfExpr.TagOffset)
689 addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
690 *DwarfExpr.TagOffset);
692 return VariableDie;
695 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
696 const LexicalScope &Scope,
697 DIE *&ObjectPointer) {
698 auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
699 if (DV.isObjectPointer())
700 ObjectPointer = Var;
701 return Var;
704 /// Return all DIVariables that appear in count: expressions.
705 static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
706 SmallVector<const DIVariable *, 2> Result;
707 auto *Array = dyn_cast<DICompositeType>(Var->getType());
708 if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
709 return Result;
710 for (auto *El : Array->getElements()) {
711 if (auto *Subrange = dyn_cast<DISubrange>(El)) {
712 auto Count = Subrange->getCount();
713 if (auto *Dependency = Count.dyn_cast<DIVariable *>())
714 Result.push_back(Dependency);
717 return Result;
720 /// Sort local variables so that variables appearing inside of helper
721 /// expressions come first.
722 static SmallVector<DbgVariable *, 8>
723 sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
724 SmallVector<DbgVariable *, 8> Result;
725 SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
726 // Map back from a DIVariable to its containing DbgVariable.
727 SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
728 // Set of DbgVariables in Result.
729 SmallDenseSet<DbgVariable *, 8> Visited;
730 // For cycle detection.
731 SmallDenseSet<DbgVariable *, 8> Visiting;
733 // Initialize the worklist and the DIVariable lookup table.
734 for (auto Var : reverse(Input)) {
735 DbgVar.insert({Var->getVariable(), Var});
736 WorkList.push_back({Var, 0});
739 // Perform a stable topological sort by doing a DFS.
740 while (!WorkList.empty()) {
741 auto Item = WorkList.back();
742 DbgVariable *Var = Item.getPointer();
743 bool visitedAllDependencies = Item.getInt();
744 WorkList.pop_back();
746 // Dependency is in a different lexical scope or a global.
747 if (!Var)
748 continue;
750 // Already handled.
751 if (Visited.count(Var))
752 continue;
754 // Add to Result if all dependencies are visited.
755 if (visitedAllDependencies) {
756 Visited.insert(Var);
757 Result.push_back(Var);
758 continue;
761 // Detect cycles.
762 auto Res = Visiting.insert(Var);
763 if (!Res.second) {
764 assert(false && "dependency cycle in local variables");
765 return Result;
768 // Push dependencies and this node onto the worklist, so that this node is
769 // visited again after all of its dependencies are handled.
770 WorkList.push_back({Var, 1});
771 for (auto *Dependency : dependencies(Var)) {
772 auto Dep = dyn_cast_or_null<const DILocalVariable>(Dependency);
773 WorkList.push_back({DbgVar[Dep], 0});
776 return Result;
779 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
780 SmallVectorImpl<DIE *> &Children,
781 bool *HasNonScopeChildren) {
782 assert(Children.empty());
783 DIE *ObjectPointer = nullptr;
785 // Emit function arguments (order is significant).
786 auto Vars = DU->getScopeVariables().lookup(Scope);
787 for (auto &DV : Vars.Args)
788 Children.push_back(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
790 // Emit local variables.
791 auto Locals = sortLocalVars(Vars.Locals);
792 for (DbgVariable *DV : Locals)
793 Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
795 // Skip imported directives in gmlt-like data.
796 if (!includeMinimalInlineScopes()) {
797 // There is no need to emit empty lexical block DIE.
798 for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
799 Children.push_back(
800 constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
803 if (HasNonScopeChildren)
804 *HasNonScopeChildren = !Children.empty();
806 for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
807 Children.push_back(constructLabelDIE(*DL, *Scope));
809 for (LexicalScope *LS : Scope->getChildren())
810 constructScopeDIE(LS, Children);
812 return ObjectPointer;
815 DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub,
816 LexicalScope *Scope) {
817 DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
819 if (Scope) {
820 assert(!Scope->getInlinedAt());
821 assert(!Scope->isAbstractScope());
822 // Collect lexical scope children first.
823 // ObjectPointer might be a local (non-argument) local variable if it's a
824 // block's synthetic this pointer.
825 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
826 addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
829 // If this is a variadic function, add an unspecified parameter.
830 DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
832 // If we have a single element of null, it is a function that returns void.
833 // If we have more than one elements and the last one is null, it is a
834 // variadic function.
835 if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
836 !includeMinimalInlineScopes())
837 ScopeDIE.addChild(
838 DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
840 return ScopeDIE;
843 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
844 DIE &ScopeDIE) {
845 // We create children when the scope DIE is not null.
846 SmallVector<DIE *, 8> Children;
847 DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
849 // Add children
850 for (auto &I : Children)
851 ScopeDIE.addChild(std::move(I));
853 return ObjectPointer;
856 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
857 LexicalScope *Scope) {
858 DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
859 if (AbsDef)
860 return;
862 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
864 DIE *ContextDIE;
865 DwarfCompileUnit *ContextCU = this;
867 if (includeMinimalInlineScopes())
868 ContextDIE = &getUnitDie();
869 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
870 // the important distinction that the debug node is not associated with the
871 // DIE (since the debug node will be associated with the concrete DIE, if
872 // any). It could be refactored to some common utility function.
873 else if (auto *SPDecl = SP->getDeclaration()) {
874 ContextDIE = &getUnitDie();
875 getOrCreateSubprogramDIE(SPDecl);
876 } else {
877 ContextDIE = getOrCreateContextDIE(SP->getScope());
878 // The scope may be shared with a subprogram that has already been
879 // constructed in another CU, in which case we need to construct this
880 // subprogram in the same CU.
881 ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
884 // Passing null as the associated node because the abstract definition
885 // shouldn't be found by lookup.
886 AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
887 ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
889 if (!ContextCU->includeMinimalInlineScopes())
890 ContextCU->addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
891 if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
892 ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
895 /// Whether to use the GNU analog for a DWARF5 tag, attribute, or location atom.
896 static bool useGNUAnalogForDwarf5Feature(DwarfDebug *DD) {
897 return DD->getDwarfVersion() == 4 && DD->tuneForGDB();
900 dwarf::Tag DwarfCompileUnit::getDwarf5OrGNUTag(dwarf::Tag Tag) const {
901 if (!useGNUAnalogForDwarf5Feature(DD))
902 return Tag;
903 switch (Tag) {
904 case dwarf::DW_TAG_call_site:
905 return dwarf::DW_TAG_GNU_call_site;
906 case dwarf::DW_TAG_call_site_parameter:
907 return dwarf::DW_TAG_GNU_call_site_parameter;
908 default:
909 llvm_unreachable("DWARF5 tag with no GNU analog");
913 dwarf::Attribute
914 DwarfCompileUnit::getDwarf5OrGNUAttr(dwarf::Attribute Attr) const {
915 if (!useGNUAnalogForDwarf5Feature(DD))
916 return Attr;
917 switch (Attr) {
918 case dwarf::DW_AT_call_all_calls:
919 return dwarf::DW_AT_GNU_all_call_sites;
920 case dwarf::DW_AT_call_target:
921 return dwarf::DW_AT_GNU_call_site_target;
922 case dwarf::DW_AT_call_origin:
923 return dwarf::DW_AT_abstract_origin;
924 case dwarf::DW_AT_call_pc:
925 return dwarf::DW_AT_low_pc;
926 case dwarf::DW_AT_call_value:
927 return dwarf::DW_AT_GNU_call_site_value;
928 case dwarf::DW_AT_call_tail_call:
929 return dwarf::DW_AT_GNU_tail_call;
930 default:
931 llvm_unreachable("DWARF5 attribute with no GNU analog");
935 dwarf::LocationAtom
936 DwarfCompileUnit::getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const {
937 if (!useGNUAnalogForDwarf5Feature(DD))
938 return Loc;
939 switch (Loc) {
940 case dwarf::DW_OP_entry_value:
941 return dwarf::DW_OP_GNU_entry_value;
942 default:
943 llvm_unreachable("DWARF5 location atom with no GNU analog");
947 DIE &DwarfCompileUnit::constructCallSiteEntryDIE(
948 DIE &ScopeDIE, const DISubprogram *CalleeSP, bool IsTail,
949 const MCSymbol *PCAddr, const MCExpr *PCOffset, unsigned CallReg) {
950 // Insert a call site entry DIE within ScopeDIE.
951 DIE &CallSiteDIE = createAndAddDIE(getDwarf5OrGNUTag(dwarf::DW_TAG_call_site),
952 ScopeDIE, nullptr);
954 if (CallReg) {
955 // Indirect call.
956 addAddress(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_target),
957 MachineLocation(CallReg));
958 } else {
959 DIE *CalleeDIE = getOrCreateSubprogramDIE(CalleeSP);
960 assert(CalleeDIE && "Could not create DIE for call site entry origin");
961 addDIEEntry(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_origin),
962 *CalleeDIE);
965 if (IsTail)
966 // Attach DW_AT_call_tail_call to tail calls for standards compliance.
967 addFlag(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_tail_call));
969 // Attach the return PC to allow the debugger to disambiguate call paths
970 // from one function to another.
971 if (DD->getDwarfVersion() == 4 && DD->tuneForGDB()) {
972 assert(PCAddr && "Missing PC information for a call");
973 addLabelAddress(CallSiteDIE, dwarf::DW_AT_low_pc, PCAddr);
974 } else if (!IsTail || DD->tuneForGDB()) {
975 assert(PCOffset && "Missing return PC information for a call");
976 addAddressExpr(CallSiteDIE, dwarf::DW_AT_call_return_pc, PCOffset);
979 return CallSiteDIE;
982 void DwarfCompileUnit::constructCallSiteParmEntryDIEs(
983 DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) {
984 for (const auto &Param : Params) {
985 unsigned Register = Param.getRegister();
986 auto CallSiteDieParam =
987 DIE::get(DIEValueAllocator,
988 getDwarf5OrGNUTag(dwarf::DW_TAG_call_site_parameter));
989 insertDIE(CallSiteDieParam);
990 addAddress(*CallSiteDieParam, dwarf::DW_AT_location,
991 MachineLocation(Register));
993 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
994 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
995 DwarfExpr.setCallSiteParamValueFlag();
997 DwarfDebug::emitDebugLocValue(*Asm, nullptr, Param.getValue(), DwarfExpr);
999 addBlock(*CallSiteDieParam, getDwarf5OrGNUAttr(dwarf::DW_AT_call_value),
1000 DwarfExpr.finalize());
1002 CallSiteDIE.addChild(CallSiteDieParam);
1006 DIE *DwarfCompileUnit::constructImportedEntityDIE(
1007 const DIImportedEntity *Module) {
1008 DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
1009 insertDIE(Module, IMDie);
1010 DIE *EntityDie;
1011 auto *Entity = Module->getEntity();
1012 if (auto *NS = dyn_cast<DINamespace>(Entity))
1013 EntityDie = getOrCreateNameSpace(NS);
1014 else if (auto *M = dyn_cast<DIModule>(Entity))
1015 EntityDie = getOrCreateModule(M);
1016 else if (auto *SP = dyn_cast<DISubprogram>(Entity))
1017 EntityDie = getOrCreateSubprogramDIE(SP);
1018 else if (auto *T = dyn_cast<DIType>(Entity))
1019 EntityDie = getOrCreateTypeDIE(T);
1020 else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
1021 EntityDie = getOrCreateGlobalVariableDIE(GV, {});
1022 else
1023 EntityDie = getDIE(Entity);
1024 assert(EntityDie);
1025 addSourceLine(*IMDie, Module->getLine(), Module->getFile());
1026 addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
1027 StringRef Name = Module->getName();
1028 if (!Name.empty())
1029 addString(*IMDie, dwarf::DW_AT_name, Name);
1031 return IMDie;
1034 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
1035 DIE *D = getDIE(SP);
1036 if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
1037 if (D)
1038 // If this subprogram has an abstract definition, reference that
1039 addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
1040 } else {
1041 assert(D || includeMinimalInlineScopes());
1042 if (D)
1043 // And attach the attributes
1044 applySubprogramAttributesToDefinition(SP, *D);
1048 void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
1049 DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
1051 auto *Die = Entity->getDIE();
1052 /// Label may be used to generate DW_AT_low_pc, so put it outside
1053 /// if/else block.
1054 const DbgLabel *Label = nullptr;
1055 if (AbsEntity && AbsEntity->getDIE()) {
1056 addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
1057 Label = dyn_cast<const DbgLabel>(Entity);
1058 } else {
1059 if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
1060 applyVariableAttributes(*Var, *Die);
1061 else if ((Label = dyn_cast<const DbgLabel>(Entity)))
1062 applyLabelAttributes(*Label, *Die);
1063 else
1064 llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
1067 if (Label)
1068 if (const auto *Sym = Label->getSymbol())
1069 addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
1072 DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
1073 auto &AbstractEntities = getAbstractEntities();
1074 auto I = AbstractEntities.find(Node);
1075 if (I != AbstractEntities.end())
1076 return I->second.get();
1077 return nullptr;
1080 void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
1081 LexicalScope *Scope) {
1082 assert(Scope && Scope->isAbstractScope());
1083 auto &Entity = getAbstractEntities()[Node];
1084 if (isa<const DILocalVariable>(Node)) {
1085 Entity = std::make_unique<DbgVariable>(
1086 cast<const DILocalVariable>(Node), nullptr /* IA */);;
1087 DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
1088 } else if (isa<const DILabel>(Node)) {
1089 Entity = std::make_unique<DbgLabel>(
1090 cast<const DILabel>(Node), nullptr /* IA */);
1091 DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
1095 void DwarfCompileUnit::emitHeader(bool UseOffsets) {
1096 // Don't bother labeling the .dwo unit, as its offset isn't used.
1097 if (!Skeleton && !DD->useSectionsAsReferences()) {
1098 LabelBegin = Asm->createTempSymbol("cu_begin");
1099 Asm->OutStreamer->EmitLabel(LabelBegin);
1102 dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
1103 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
1104 : dwarf::DW_UT_compile;
1105 DwarfUnit::emitCommonHeader(UseOffsets, UT);
1106 if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
1107 Asm->emitInt64(getDWOId());
1110 bool DwarfCompileUnit::hasDwarfPubSections() const {
1111 switch (CUNode->getNameTableKind()) {
1112 case DICompileUnit::DebugNameTableKind::None:
1113 return false;
1114 // Opting in to GNU Pubnames/types overrides the default to ensure these are
1115 // generated for things like Gold's gdb_index generation.
1116 case DICompileUnit::DebugNameTableKind::GNU:
1117 return true;
1118 case DICompileUnit::DebugNameTableKind::Default:
1119 return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
1120 !CUNode->isDebugDirectivesOnly() &&
1121 DD->getAccelTableKind() != AccelTableKind::Apple &&
1122 DD->getDwarfVersion() < 5;
1124 llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
1127 /// addGlobalName - Add a new global name to the compile unit.
1128 void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
1129 const DIScope *Context) {
1130 if (!hasDwarfPubSections())
1131 return;
1132 std::string FullName = getParentContextString(Context) + Name.str();
1133 GlobalNames[FullName] = &Die;
1136 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
1137 const DIScope *Context) {
1138 if (!hasDwarfPubSections())
1139 return;
1140 std::string FullName = getParentContextString(Context) + Name.str();
1141 // Insert, allowing the entry to remain as-is if it's already present
1142 // This way the CU-level type DIE is preferred over the "can't describe this
1143 // type as a unit offset because it's not really in the CU at all, it's only
1144 // in a type unit"
1145 GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1148 /// Add a new global type to the unit.
1149 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1150 const DIScope *Context) {
1151 if (!hasDwarfPubSections())
1152 return;
1153 std::string FullName = getParentContextString(Context) + Ty->getName().str();
1154 GlobalTypes[FullName] = &Die;
1157 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
1158 const DIScope *Context) {
1159 if (!hasDwarfPubSections())
1160 return;
1161 std::string FullName = getParentContextString(Context) + Ty->getName().str();
1162 // Insert, allowing the entry to remain as-is if it's already present
1163 // This way the CU-level type DIE is preferred over the "can't describe this
1164 // type as a unit offset because it's not really in the CU at all, it's only
1165 // in a type unit"
1166 GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1169 /// addVariableAddress - Add DW_AT_location attribute for a
1170 /// DbgVariable based on provided MachineLocation.
1171 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
1172 MachineLocation Location) {
1173 // addBlockByrefAddress is obsolete and will be removed soon.
1174 // The clang frontend always generates block byref variables with a
1175 // complex expression that encodes exactly what addBlockByrefAddress
1176 // would do.
1177 assert((!DV.isBlockByrefVariable() || DV.hasComplexAddress()) &&
1178 "block byref variable without a complex expression");
1179 if (DV.hasComplexAddress())
1180 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
1181 else
1182 addAddress(Die, dwarf::DW_AT_location, Location);
1185 /// Add an address attribute to a die based on the location provided.
1186 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
1187 const MachineLocation &Location) {
1188 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1189 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1190 if (Location.isIndirect())
1191 DwarfExpr.setMemoryLocationKind();
1193 DIExpressionCursor Cursor({});
1194 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1195 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1196 return;
1197 DwarfExpr.addExpression(std::move(Cursor));
1199 // Now attach the location information to the DIE.
1200 addBlock(Die, Attribute, DwarfExpr.finalize());
1203 /// Start with the address based on the location provided, and generate the
1204 /// DWARF information necessary to find the actual variable given the extra
1205 /// address information encoded in the DbgVariable, starting from the starting
1206 /// location. Add the DWARF information to the die.
1207 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
1208 dwarf::Attribute Attribute,
1209 const MachineLocation &Location) {
1210 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1211 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1212 const DIExpression *DIExpr = DV.getSingleExpression();
1213 DwarfExpr.addFragmentOffset(DIExpr);
1214 if (Location.isIndirect())
1215 DwarfExpr.setMemoryLocationKind();
1217 DIExpressionCursor Cursor(DIExpr);
1219 if (DIExpr->isEntryValue()) {
1220 DwarfExpr.setEntryValueFlag();
1221 DwarfExpr.addEntryValueExpression(Cursor);
1224 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1225 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1226 return;
1227 DwarfExpr.addExpression(std::move(Cursor));
1229 // Now attach the location information to the DIE.
1230 addBlock(Die, Attribute, DwarfExpr.finalize());
1233 /// Add a Dwarf loclistptr attribute data and value.
1234 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
1235 unsigned Index) {
1236 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1237 : dwarf::DW_FORM_data4;
1238 Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
1241 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
1242 DIE &VariableDie) {
1243 StringRef Name = Var.getName();
1244 if (!Name.empty())
1245 addString(VariableDie, dwarf::DW_AT_name, Name);
1246 const auto *DIVar = Var.getVariable();
1247 if (DIVar)
1248 if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
1249 addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1250 AlignInBytes);
1252 addSourceLine(VariableDie, DIVar);
1253 addType(VariableDie, Var.getType());
1254 if (Var.isArtificial())
1255 addFlag(VariableDie, dwarf::DW_AT_artificial);
1258 void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
1259 DIE &LabelDie) {
1260 StringRef Name = Label.getName();
1261 if (!Name.empty())
1262 addString(LabelDie, dwarf::DW_AT_name, Name);
1263 const auto *DILabel = Label.getLabel();
1264 addSourceLine(LabelDie, DILabel);
1267 /// Add a Dwarf expression attribute data and value.
1268 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
1269 const MCExpr *Expr) {
1270 Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
1273 void DwarfCompileUnit::addAddressExpr(DIE &Die, dwarf::Attribute Attribute,
1274 const MCExpr *Expr) {
1275 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
1276 DIEExpr(Expr));
1279 void DwarfCompileUnit::applySubprogramAttributesToDefinition(
1280 const DISubprogram *SP, DIE &SPDie) {
1281 auto *SPDecl = SP->getDeclaration();
1282 auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope();
1283 applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
1284 addGlobalName(SP->getName(), SPDie, Context);
1287 bool DwarfCompileUnit::isDwoUnit() const {
1288 return DD->useSplitDwarf() && Skeleton;
1291 void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
1292 constructTypeDIE(D, CTy);
1295 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
1296 return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
1297 (DD->useSplitDwarf() && !Skeleton);
1300 void DwarfCompileUnit::addAddrTableBase() {
1301 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1302 MCSymbol *Label = DD->getAddressPool().getLabel();
1303 addSectionLabel(getUnitDie(),
1304 getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
1305 : dwarf::DW_AT_GNU_addr_base,
1306 Label, TLOF.getDwarfAddrSection()->getBeginSymbol());
1309 void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) {
1310 Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, dwarf::DW_FORM_udata,
1311 new (DIEValueAllocator) DIEBaseTypeRef(this, Idx));
1314 void DwarfCompileUnit::createBaseTypeDIEs() {
1315 // Insert the base_type DIEs directly after the CU so that their offsets will
1316 // fit in the fixed size ULEB128 used inside the location expressions.
1317 // Maintain order by iterating backwards and inserting to the front of CU
1318 // child list.
1319 for (auto &Btr : reverse(ExprRefedBaseTypes)) {
1320 DIE &Die = getUnitDie().addChildFront(
1321 DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type));
1322 SmallString<32> Str;
1323 addString(Die, dwarf::DW_AT_name,
1324 Twine(dwarf::AttributeEncodingString(Btr.Encoding) +
1325 "_" + Twine(Btr.BitSize)).toStringRef(Str));
1326 addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding);
1327 addUInt(Die, dwarf::DW_AT_byte_size, None, Btr.BitSize / 8);
1329 Btr.Die = &Die;