1 //===- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Units ------------===//
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 constructing a dwarf compile unit.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "DwarfCompileUnit.h"
15 #include "AddressPool.h"
16 #include "DwarfDebug.h"
17 #include "DwarfExpression.h"
18 #include "DwarfUnit.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/STLExtras.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>
52 
53 using namespace llvm;
54 
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");
61 }
62 
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)
73     return addLocalLabelAddress(Die, Attribute, Label);
74 
75   if (Label)
76     DD->addArangeLabel(SymbolCU(this, Label));
77 
78   unsigned idx = DD->getAddressPool().getIndex(Label);
79   Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_GNU_addr_index,
80                DIEInteger(idx));
81 }
82 
83 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
84                                             dwarf::Attribute Attribute,
85                                             const MCSymbol *Label) {
86   if (Label)
87     DD->addArangeLabel(SymbolCU(this, Label));
88 
89   if (Label)
90     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
91                  DIELabel(Label));
92   else
93     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
94                  DIEInteger(0));
95 }
96 
97 unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
98   // If we print assembly, we can't separate .file entries according to
99   // compile units. Thus all files will belong to the default compile unit.
100 
101   // FIXME: add a better feature test than hasRawTextSupport. Even better,
102   // extend .file to support this.
103   unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
104   if (!File)
105     return Asm->OutStreamer->EmitDwarfFileDirective(0, "", "", nullptr, None, CUID);
106   return Asm->OutStreamer->EmitDwarfFileDirective(
107       0, File->getDirectory(), File->getFilename(), getMD5AsBytes(File),
108       File->getSource(), CUID);
109 }
110 
111 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
112     const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
113   // Check for pre-existence.
114   if (DIE *Die = getDIE(GV))
115     return Die;
116 
117   assert(GV);
118 
119   auto *GVContext = GV->getScope();
120   auto *GTy = DD->resolve(GV->getType());
121 
122   // Construct the context before querying for the existence of the DIE in
123   // case such construction creates the DIE.
124   DIE *ContextDIE = getOrCreateContextDIE(GVContext);
125 
126   // Add to map.
127   DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
128   DIScope *DeclContext;
129   if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
130     DeclContext = resolve(SDMDecl->getScope());
131     assert(SDMDecl->isStaticMember() && "Expected static member decl");
132     assert(GV->isDefinition());
133     // We need the declaration DIE that is in the static member's class.
134     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
135     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
136     // If the global variable's type is different from the one in the class
137     // member type, assume that it's more specific and also emit it.
138     if (GTy != DD->resolve(SDMDecl->getBaseType()))
139       addType(*VariableDIE, GTy);
140   } else {
141     DeclContext = GV->getScope();
142     // Add name and type.
143     addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
144     addType(*VariableDIE, GTy);
145 
146     // Add scoping info.
147     if (!GV->isLocalToUnit())
148       addFlag(*VariableDIE, dwarf::DW_AT_external);
149 
150     // Add line number info.
151     addSourceLine(*VariableDIE, GV);
152   }
153 
154   if (!GV->isDefinition())
155     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
156   else
157     addGlobalName(GV->getName(), *VariableDIE, DeclContext);
158 
159   if (uint32_t AlignInBytes = GV->getAlignInBytes())
160     addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
161             AlignInBytes);
162 
163   // Add location.
164   bool addToAccelTable = false;
165   DIELoc *Loc = nullptr;
166   std::unique_ptr<DIEDwarfExpression> DwarfExpr;
167   for (const auto &GE : GlobalExprs) {
168     const GlobalVariable *Global = GE.Var;
169     const DIExpression *Expr = GE.Expr;
170 
171     // For compatibility with DWARF 3 and earlier,
172     // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) becomes
173     // DW_AT_const_value(X).
174     if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
175       addToAccelTable = true;
176       addConstantValue(*VariableDIE, /*Unsigned=*/true, Expr->getElement(1));
177       break;
178     }
179 
180     // We cannot describe the location of dllimport'd variables: the
181     // computation of their address requires loads from the IAT.
182     if (Global && Global->hasDLLImportStorageClass())
183       continue;
184 
185     // Nothing to describe without address or constant.
186     if (!Global && (!Expr || !Expr->isConstant()))
187       continue;
188 
189     if (Global && Global->isThreadLocal() &&
190         !Asm->getObjFileLowering().supportDebugThreadLocalLocation())
191       continue;
192 
193     if (!Loc) {
194       addToAccelTable = true;
195       Loc = new (DIEValueAllocator) DIELoc;
196       DwarfExpr = llvm::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
197     }
198 
199     if (Expr)
200       DwarfExpr->addFragmentOffset(Expr);
201 
202     if (Global) {
203       const MCSymbol *Sym = Asm->getSymbol(Global);
204       if (Global->isThreadLocal()) {
205         if (Asm->TM.useEmulatedTLS()) {
206           // TODO: add debug info for emulated thread local mode.
207         } else {
208           // FIXME: Make this work with -gsplit-dwarf.
209           unsigned PointerSize = Asm->getDataLayout().getPointerSize();
210           assert((PointerSize == 4 || PointerSize == 8) &&
211                  "Add support for other sizes if necessary");
212           // Based on GCC's support for TLS:
213           if (!DD->useSplitDwarf()) {
214             // 1) Start with a constNu of the appropriate pointer size
215             addUInt(*Loc, dwarf::DW_FORM_data1,
216                     PointerSize == 4 ? dwarf::DW_OP_const4u
217                                      : dwarf::DW_OP_const8u);
218             // 2) containing the (relocated) offset of the TLS variable
219             //    within the module's TLS block.
220             addExpr(*Loc, dwarf::DW_FORM_udata,
221                     Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
222           } else {
223             addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
224             addUInt(*Loc, dwarf::DW_FORM_udata,
225                     DD->getAddressPool().getIndex(Sym, /* TLS */ true));
226           }
227           // 3) followed by an OP to make the debugger do a TLS lookup.
228           addUInt(*Loc, dwarf::DW_FORM_data1,
229                   DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
230                                         : dwarf::DW_OP_form_tls_address);
231         }
232       } else {
233         DD->addArangeLabel(SymbolCU(this, Sym));
234         addOpAddress(*Loc, Sym);
235       }
236     }
237     // Global variables attached to symbols are memory locations.
238     // It would be better if this were unconditional, but malformed input that
239     // mixes non-fragments and fragments for the same variable is too expensive
240     // to detect in the verifier.
241     if (DwarfExpr->isUnknownLocation())
242       DwarfExpr->setMemoryLocationKind();
243     DwarfExpr->addExpression(Expr);
244   }
245   if (Loc)
246     addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
247 
248   if (DD->useAllLinkageNames())
249     addLinkageName(*VariableDIE, GV->getLinkageName());
250 
251   if (addToAccelTable) {
252     DD->addAccelName(*CUNode, GV->getName(), *VariableDIE);
253 
254     // If the linkage name is different than the name, go ahead and output
255     // that as well into the name table.
256     if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
257         DD->useAllLinkageNames())
258       DD->addAccelName(*CUNode, GV->getLinkageName(), *VariableDIE);
259   }
260 
261   return VariableDIE;
262 }
263 
264 void DwarfCompileUnit::addRange(RangeSpan Range) {
265   bool SameAsPrevCU = this == DD->getPrevCU();
266   DD->setPrevCU(this);
267   // If we have no current ranges just add the range and return, otherwise,
268   // check the current section and CU against the previous section and CU we
269   // emitted into and the subprogram was contained within. If these are the
270   // same then extend our current range, otherwise add this as a new range.
271   if (CURanges.empty() || !SameAsPrevCU ||
272       (&CURanges.back().getEnd()->getSection() !=
273        &Range.getEnd()->getSection())) {
274     CURanges.push_back(Range);
275     return;
276   }
277 
278   CURanges.back().setEnd(Range.getEnd());
279 }
280 
281 void DwarfCompileUnit::initStmtList() {
282   if (CUNode->isDebugDirectivesOnly())
283     return;
284 
285   // Define start line table label for each Compile Unit.
286   MCSymbol *LineTableStartSym;
287   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
288   if (DD->useSectionsAsReferences()) {
289     LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
290   } else {
291     LineTableStartSym =
292         Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
293   }
294 
295   // DW_AT_stmt_list is a offset of line number information for this
296   // compile unit in debug_line section. For split dwarf this is
297   // left in the skeleton CU and so not included.
298   // The line table entries are not always emitted in assembly, so it
299   // is not okay to use line_table_start here.
300   StmtListValue =
301       addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
302                       TLOF.getDwarfLineSection()->getBeginSymbol());
303 }
304 
305 void DwarfCompileUnit::applyStmtList(DIE &D) {
306   D.addValue(DIEValueAllocator, *StmtListValue);
307 }
308 
309 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
310                                        const MCSymbol *End) {
311   assert(Begin && "Begin label should not be null!");
312   assert(End && "End label should not be null!");
313   assert(Begin->isDefined() && "Invalid starting label");
314   assert(End->isDefined() && "Invalid end label");
315 
316   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
317   if (DD->getDwarfVersion() < 4)
318     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
319   else
320     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
321 }
322 
323 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
324 // and DW_AT_high_pc attributes. If there are global variables in this
325 // scope then create and insert DIEs for these variables.
326 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
327   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
328 
329   attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd());
330   if (DD->useAppleExtensionAttributes() &&
331       !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
332           *DD->getCurrentFunction()))
333     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
334 
335   // Only include DW_AT_frame_base in full debug info
336   if (!includeMinimalInlineScopes()) {
337     if (Asm->MF->getTarget().getTargetTriple().isNVPTX()) {
338       DIELoc *Loc = new (DIEValueAllocator) DIELoc;
339       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa);
340       addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
341     } else {
342       const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo();
343       MachineLocation Location(RI->getFrameRegister(*Asm->MF));
344       if (RI->isPhysicalRegister(Location.getReg()))
345         addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
346     }
347   }
348 
349   // Add name to the name table, we do this here because we're guaranteed
350   // to have concrete versions of our DW_TAG_subprogram nodes.
351   DD->addSubprogramNames(*CUNode, SP, *SPDie);
352 
353   return *SPDie;
354 }
355 
356 // Construct a DIE for this scope.
357 void DwarfCompileUnit::constructScopeDIE(
358     LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
359   if (!Scope || !Scope->getScopeNode())
360     return;
361 
362   auto *DS = Scope->getScopeNode();
363 
364   assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
365          "Only handle inlined subprograms here, use "
366          "constructSubprogramScopeDIE for non-inlined "
367          "subprograms");
368 
369   SmallVector<DIE *, 8> Children;
370 
371   // We try to create the scope DIE first, then the children DIEs. This will
372   // avoid creating un-used children then removing them later when we find out
373   // the scope DIE is null.
374   DIE *ScopeDIE;
375   if (Scope->getParent() && isa<DISubprogram>(DS)) {
376     ScopeDIE = constructInlinedScopeDIE(Scope);
377     if (!ScopeDIE)
378       return;
379     // We create children when the scope DIE is not null.
380     createScopeChildrenDIE(Scope, Children);
381   } else {
382     // Early exit when we know the scope DIE is going to be null.
383     if (DD->isLexicalScopeDIENull(Scope))
384       return;
385 
386     bool HasNonScopeChildren = false;
387 
388     // We create children here when we know the scope DIE is not going to be
389     // null and the children will be added to the scope DIE.
390     createScopeChildrenDIE(Scope, Children, &HasNonScopeChildren);
391 
392     // If there are only other scopes as children, put them directly in the
393     // parent instead, as this scope would serve no purpose.
394     if (!HasNonScopeChildren) {
395       FinalChildren.insert(FinalChildren.end(),
396                            std::make_move_iterator(Children.begin()),
397                            std::make_move_iterator(Children.end()));
398       return;
399     }
400     ScopeDIE = constructLexicalScopeDIE(Scope);
401     assert(ScopeDIE && "Scope DIE should not be null.");
402   }
403 
404   // Add children
405   for (auto &I : Children)
406     ScopeDIE->addChild(std::move(I));
407 
408   FinalChildren.push_back(std::move(ScopeDIE));
409 }
410 
411 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
412                                          SmallVector<RangeSpan, 2> Range) {
413   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
414 
415   // Emit the offset into .debug_ranges or .debug_rnglists as a relocatable
416   // label. emitDIE() will handle emitting it appropriately.
417   const MCSymbol *RangeSectionSym =
418       DD->getDwarfVersion() >= 5
419           ? TLOF.getDwarfRnglistsSection()->getBeginSymbol()
420           : TLOF.getDwarfRangesSection()->getBeginSymbol();
421 
422   RangeSpanList List(Asm->createTempSymbol("debug_ranges"), std::move(Range));
423 
424   // Under fission, ranges are specified by constant offsets relative to the
425   // CU's DW_AT_GNU_ranges_base.
426   // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
427   // fission until we support the forms using the .debug_addr section
428   // (DW_RLE_startx_endx etc.).
429   if (isDwoUnit()) {
430     if (DD->getDwarfVersion() < 5)
431       addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
432                       RangeSectionSym);
433   } else {
434     addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
435                     RangeSectionSym);
436   }
437 
438   // Add the range list to the set of ranges to be emitted.
439   (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
440 }
441 
442 void DwarfCompileUnit::attachRangesOrLowHighPC(
443     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
444   if (Ranges.size() == 1 || !DD->useRangesSection()) {
445     const RangeSpan &Front = Ranges.front();
446     const RangeSpan &Back = Ranges.back();
447     attachLowHighPC(Die, Front.getStart(), Back.getEnd());
448   } else
449     addScopeRangeList(Die, std::move(Ranges));
450 }
451 
452 void DwarfCompileUnit::attachRangesOrLowHighPC(
453     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
454   SmallVector<RangeSpan, 2> List;
455   List.reserve(Ranges.size());
456   for (const InsnRange &R : Ranges)
457     List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
458                              DD->getLabelAfterInsn(R.second)));
459   attachRangesOrLowHighPC(Die, std::move(List));
460 }
461 
462 // This scope represents inlined body of a function. Construct DIE to
463 // represent this concrete inlined copy of the function.
464 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
465   assert(Scope->getScopeNode());
466   auto *DS = Scope->getScopeNode();
467   auto *InlinedSP = getDISubprogram(DS);
468   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
469   // was inlined from another compile unit.
470   DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
471   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
472 
473   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
474   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
475 
476   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
477 
478   // Add the call site information to the DIE.
479   const DILocation *IA = Scope->getInlinedAt();
480   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
481           getOrCreateSourceID(IA->getFile()));
482   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
483   if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
484     addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
485             IA->getDiscriminator());
486 
487   // Add name to the name table, we do this here because we're guaranteed
488   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
489   DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
490 
491   return ScopeDIE;
492 }
493 
494 // Construct new DW_TAG_lexical_block for this scope and attach
495 // DW_AT_low_pc/DW_AT_high_pc labels.
496 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
497   if (DD->isLexicalScopeDIENull(Scope))
498     return nullptr;
499 
500   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
501   if (Scope->isAbstractScope())
502     return ScopeDIE;
503 
504   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
505 
506   return ScopeDIE;
507 }
508 
509 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
510 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
511   auto D = constructVariableDIEImpl(DV, Abstract);
512   DV.setDIE(*D);
513   return D;
514 }
515 
516 DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
517                                          const LexicalScope &Scope) {
518   auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
519   insertDIE(DL.getLabel(), LabelDie);
520   DL.setDIE(*LabelDie);
521 
522   if (Scope.isAbstractScope())
523     applyLabelAttributes(DL, *LabelDie);
524 
525   return LabelDie;
526 }
527 
528 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
529                                                 bool Abstract) {
530   // Define variable debug information entry.
531   auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
532   insertDIE(DV.getVariable(), VariableDie);
533 
534   if (Abstract) {
535     applyVariableAttributes(DV, *VariableDie);
536     return VariableDie;
537   }
538 
539   // Add variable address.
540 
541   unsigned Offset = DV.getDebugLocListIndex();
542   if (Offset != ~0U) {
543     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
544     return VariableDie;
545   }
546 
547   // Check if variable is described by a DBG_VALUE instruction.
548   if (const MachineInstr *DVInsn = DV.getMInsn()) {
549     assert(DVInsn->getNumOperands() == 4);
550     if (DVInsn->getOperand(0).isReg()) {
551       auto RegOp = DVInsn->getOperand(0);
552       auto Op1 = DVInsn->getOperand(1);
553       // If the second operand is an immediate, this is an indirect value.
554       assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
555       MachineLocation Location(RegOp.getReg(), Op1.isImm());
556       addVariableAddress(DV, *VariableDie, Location);
557     } else if (DVInsn->getOperand(0).isImm()) {
558       // This variable is described by a single constant.
559       // Check whether it has a DIExpression.
560       auto *Expr = DV.getSingleExpression();
561       if (Expr && Expr->getNumElements()) {
562         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
563         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
564         // If there is an expression, emit raw unsigned bytes.
565         DwarfExpr.addFragmentOffset(Expr);
566         DwarfExpr.addUnsignedConstant(DVInsn->getOperand(0).getImm());
567         DwarfExpr.addExpression(Expr);
568         addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
569       } else
570         addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
571     } else if (DVInsn->getOperand(0).isFPImm())
572       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
573     else if (DVInsn->getOperand(0).isCImm())
574       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
575                        DV.getType());
576 
577     return VariableDie;
578   }
579 
580   // .. else use frame index.
581   if (!DV.hasFrameIndexExprs())
582     return VariableDie;
583 
584   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
585   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
586   for (auto &Fragment : DV.getFrameIndexExprs()) {
587     unsigned FrameReg = 0;
588     const DIExpression *Expr = Fragment.Expr;
589     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
590     int Offset = TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
591     DwarfExpr.addFragmentOffset(Expr);
592     SmallVector<uint64_t, 8> Ops;
593     Ops.push_back(dwarf::DW_OP_plus_uconst);
594     Ops.push_back(Offset);
595     Ops.append(Expr->elements_begin(), Expr->elements_end());
596     DIExpressionCursor Cursor(Ops);
597     DwarfExpr.setMemoryLocationKind();
598     if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
599       addOpAddress(*Loc, FrameSymbol);
600     else
601       DwarfExpr.addMachineRegExpression(
602           *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
603     DwarfExpr.addExpression(std::move(Cursor));
604   }
605   addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
606 
607   return VariableDie;
608 }
609 
610 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
611                                             const LexicalScope &Scope,
612                                             DIE *&ObjectPointer) {
613   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
614   if (DV.isObjectPointer())
615     ObjectPointer = Var;
616   return Var;
617 }
618 
619 /// Return all DIVariables that appear in count: expressions.
620 static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
621   SmallVector<const DIVariable *, 2> Result;
622   auto *Array = dyn_cast<DICompositeType>(Var->getType());
623   if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
624     return Result;
625   for (auto *El : Array->getElements()) {
626     if (auto *Subrange = dyn_cast<DISubrange>(El)) {
627       auto Count = Subrange->getCount();
628       if (auto *Dependency = Count.dyn_cast<DIVariable *>())
629         Result.push_back(Dependency);
630     }
631   }
632   return Result;
633 }
634 
635 /// Sort local variables so that variables appearing inside of helper
636 /// expressions come first.
637 static SmallVector<DbgVariable *, 8>
638 sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
639   SmallVector<DbgVariable *, 8> Result;
640   SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
641   // Map back from a DIVariable to its containing DbgVariable.
642   SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
643   // Set of DbgVariables in Result.
644   SmallDenseSet<DbgVariable *, 8> Visited;
645   // For cycle detection.
646   SmallDenseSet<DbgVariable *, 8> Visiting;
647 
648   // Initialize the worklist and the DIVariable lookup table.
649   for (auto Var : reverse(Input)) {
650     DbgVar.insert({Var->getVariable(), Var});
651     WorkList.push_back({Var, 0});
652   }
653 
654   // Perform a stable topological sort by doing a DFS.
655   while (!WorkList.empty()) {
656     auto Item = WorkList.back();
657     DbgVariable *Var = Item.getPointer();
658     bool visitedAllDependencies = Item.getInt();
659     WorkList.pop_back();
660 
661     // Dependency is in a different lexical scope or a global.
662     if (!Var)
663       continue;
664 
665     // Already handled.
666     if (Visited.count(Var))
667       continue;
668 
669     // Add to Result if all dependencies are visited.
670     if (visitedAllDependencies) {
671       Visited.insert(Var);
672       Result.push_back(Var);
673       continue;
674     }
675 
676     // Detect cycles.
677     auto Res = Visiting.insert(Var);
678     if (!Res.second) {
679       assert(false && "dependency cycle in local variables");
680       return Result;
681     }
682 
683     // Push dependencies and this node onto the worklist, so that this node is
684     // visited again after all of its dependencies are handled.
685     WorkList.push_back({Var, 1});
686     for (auto *Dependency : dependencies(Var)) {
687       auto Dep = dyn_cast_or_null<const DILocalVariable>(Dependency);
688       WorkList.push_back({DbgVar[Dep], 0});
689     }
690   }
691   return Result;
692 }
693 
694 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
695                                               SmallVectorImpl<DIE *> &Children,
696                                               bool *HasNonScopeChildren) {
697   assert(Children.empty());
698   DIE *ObjectPointer = nullptr;
699 
700   // Emit function arguments (order is significant).
701   auto Vars = DU->getScopeVariables().lookup(Scope);
702   for (auto &DV : Vars.Args)
703     Children.push_back(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
704 
705   // Emit local variables.
706   auto Locals = sortLocalVars(Vars.Locals);
707   for (DbgVariable *DV : Locals)
708     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
709 
710   // Skip imported directives in gmlt-like data.
711   if (!includeMinimalInlineScopes()) {
712     // There is no need to emit empty lexical block DIE.
713     for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
714       Children.push_back(
715           constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
716   }
717 
718   if (HasNonScopeChildren)
719     *HasNonScopeChildren = !Children.empty();
720 
721   for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
722     Children.push_back(constructLabelDIE(*DL, *Scope));
723 
724   for (LexicalScope *LS : Scope->getChildren())
725     constructScopeDIE(LS, Children);
726 
727   return ObjectPointer;
728 }
729 
730 void DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub, LexicalScope *Scope) {
731   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
732 
733   if (Scope) {
734     assert(!Scope->getInlinedAt());
735     assert(!Scope->isAbstractScope());
736     // Collect lexical scope children first.
737     // ObjectPointer might be a local (non-argument) local variable if it's a
738     // block's synthetic this pointer.
739     if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
740       addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
741   }
742 
743   // If this is a variadic function, add an unspecified parameter.
744   DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
745 
746   // If we have a single element of null, it is a function that returns void.
747   // If we have more than one elements and the last one is null, it is a
748   // variadic function.
749   if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
750       !includeMinimalInlineScopes())
751     ScopeDIE.addChild(
752         DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
753 }
754 
755 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
756                                                  DIE &ScopeDIE) {
757   // We create children when the scope DIE is not null.
758   SmallVector<DIE *, 8> Children;
759   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
760 
761   // Add children
762   for (auto &I : Children)
763     ScopeDIE.addChild(std::move(I));
764 
765   return ObjectPointer;
766 }
767 
768 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
769     LexicalScope *Scope) {
770   DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
771   if (AbsDef)
772     return;
773 
774   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
775 
776   DIE *ContextDIE;
777   DwarfCompileUnit *ContextCU = this;
778 
779   if (includeMinimalInlineScopes())
780     ContextDIE = &getUnitDie();
781   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
782   // the important distinction that the debug node is not associated with the
783   // DIE (since the debug node will be associated with the concrete DIE, if
784   // any). It could be refactored to some common utility function.
785   else if (auto *SPDecl = SP->getDeclaration()) {
786     ContextDIE = &getUnitDie();
787     getOrCreateSubprogramDIE(SPDecl);
788   } else {
789     ContextDIE = getOrCreateContextDIE(resolve(SP->getScope()));
790     // The scope may be shared with a subprogram that has already been
791     // constructed in another CU, in which case we need to construct this
792     // subprogram in the same CU.
793     ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
794   }
795 
796   // Passing null as the associated node because the abstract definition
797   // shouldn't be found by lookup.
798   AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
799   ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
800 
801   if (!ContextCU->includeMinimalInlineScopes())
802     ContextCU->addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
803   if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
804     ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
805 }
806 
807 DIE *DwarfCompileUnit::constructImportedEntityDIE(
808     const DIImportedEntity *Module) {
809   DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
810   insertDIE(Module, IMDie);
811   DIE *EntityDie;
812   auto *Entity = resolve(Module->getEntity());
813   if (auto *NS = dyn_cast<DINamespace>(Entity))
814     EntityDie = getOrCreateNameSpace(NS);
815   else if (auto *M = dyn_cast<DIModule>(Entity))
816     EntityDie = getOrCreateModule(M);
817   else if (auto *SP = dyn_cast<DISubprogram>(Entity))
818     EntityDie = getOrCreateSubprogramDIE(SP);
819   else if (auto *T = dyn_cast<DIType>(Entity))
820     EntityDie = getOrCreateTypeDIE(T);
821   else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
822     EntityDie = getOrCreateGlobalVariableDIE(GV, {});
823   else
824     EntityDie = getDIE(Entity);
825   assert(EntityDie);
826   addSourceLine(*IMDie, Module->getLine(), Module->getFile());
827   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
828   StringRef Name = Module->getName();
829   if (!Name.empty())
830     addString(*IMDie, dwarf::DW_AT_name, Name);
831 
832   return IMDie;
833 }
834 
835 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
836   DIE *D = getDIE(SP);
837   if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
838     if (D)
839       // If this subprogram has an abstract definition, reference that
840       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
841   } else {
842     assert(D || includeMinimalInlineScopes());
843     if (D)
844       // And attach the attributes
845       applySubprogramAttributesToDefinition(SP, *D);
846   }
847 }
848 
849 void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
850   DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
851 
852   auto *Die = Entity->getDIE();
853   /// Label may be used to generate DW_AT_low_pc, so put it outside
854   /// if/else block.
855   const DbgLabel *Label = nullptr;
856   if (AbsEntity && AbsEntity->getDIE()) {
857     addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
858     Label = dyn_cast<const DbgLabel>(Entity);
859   } else {
860     if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
861       applyVariableAttributes(*Var, *Die);
862     else if ((Label = dyn_cast<const DbgLabel>(Entity)))
863       applyLabelAttributes(*Label, *Die);
864     else
865       llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
866   }
867 
868   if (Label) {
869     const MCSymbol *Sym = Label->getSymbol();
870     addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
871   }
872 }
873 
874 DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
875   auto &AbstractEntities = getAbstractEntities();
876   auto I = AbstractEntities.find(Node);
877   if (I != AbstractEntities.end())
878     return I->second.get();
879   return nullptr;
880 }
881 
882 void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
883                                             LexicalScope *Scope) {
884   assert(Scope && Scope->isAbstractScope());
885   auto &Entity = getAbstractEntities()[Node];
886   if (isa<const DILocalVariable>(Node)) {
887     Entity = llvm::make_unique<DbgVariable>(
888                         cast<const DILocalVariable>(Node), nullptr /* IA */);;
889     DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
890   } else if (isa<const DILabel>(Node)) {
891     Entity = llvm::make_unique<DbgLabel>(
892                         cast<const DILabel>(Node), nullptr /* IA */);
893     DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
894   }
895 }
896 
897 void DwarfCompileUnit::emitHeader(bool UseOffsets) {
898   // Don't bother labeling the .dwo unit, as its offset isn't used.
899   if (!Skeleton && !DD->useSectionsAsReferences()) {
900     LabelBegin = Asm->createTempSymbol("cu_begin");
901     Asm->OutStreamer->EmitLabel(LabelBegin);
902   }
903 
904   dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
905                                 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
906                                                       : dwarf::DW_UT_compile;
907   DwarfUnit::emitCommonHeader(UseOffsets, UT);
908   if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
909     Asm->emitInt64(getDWOId());
910 }
911 
912 bool DwarfCompileUnit::hasDwarfPubSections() const {
913   switch (CUNode->getNameTableKind()) {
914   case DICompileUnit::DebugNameTableKind::None:
915     return false;
916     // Opting in to GNU Pubnames/types overrides the default to ensure these are
917     // generated for things like Gold's gdb_index generation.
918   case DICompileUnit::DebugNameTableKind::GNU:
919     return true;
920   case DICompileUnit::DebugNameTableKind::Default:
921     return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
922            !CUNode->isDebugDirectivesOnly();
923   }
924   llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
925 }
926 
927 /// addGlobalName - Add a new global name to the compile unit.
928 void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
929                                      const DIScope *Context) {
930   if (!hasDwarfPubSections())
931     return;
932   std::string FullName = getParentContextString(Context) + Name.str();
933   GlobalNames[FullName] = &Die;
934 }
935 
936 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
937                                                 const DIScope *Context) {
938   if (!hasDwarfPubSections())
939     return;
940   std::string FullName = getParentContextString(Context) + Name.str();
941   // Insert, allowing the entry to remain as-is if it's already present
942   // This way the CU-level type DIE is preferred over the "can't describe this
943   // type as a unit offset because it's not really in the CU at all, it's only
944   // in a type unit"
945   GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
946 }
947 
948 /// Add a new global type to the unit.
949 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
950                                      const DIScope *Context) {
951   if (!hasDwarfPubSections())
952     return;
953   std::string FullName = getParentContextString(Context) + Ty->getName().str();
954   GlobalTypes[FullName] = &Die;
955 }
956 
957 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
958                                              const DIScope *Context) {
959   if (!hasDwarfPubSections())
960     return;
961   std::string FullName = getParentContextString(Context) + Ty->getName().str();
962   // Insert, allowing the entry to remain as-is if it's already present
963   // This way the CU-level type DIE is preferred over the "can't describe this
964   // type as a unit offset because it's not really in the CU at all, it's only
965   // in a type unit"
966   GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
967 }
968 
969 /// addVariableAddress - Add DW_AT_location attribute for a
970 /// DbgVariable based on provided MachineLocation.
971 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
972                                           MachineLocation Location) {
973   // addBlockByrefAddress is obsolete and will be removed soon.
974   // The clang frontend always generates block byref variables with a
975   // complex expression that encodes exactly what addBlockByrefAddress
976   // would do.
977   assert((!DV.isBlockByrefVariable() || DV.hasComplexAddress()) &&
978          "block byref variable without a complex expression");
979   if (DV.hasComplexAddress())
980     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
981   else
982     addAddress(Die, dwarf::DW_AT_location, Location);
983 }
984 
985 /// Add an address attribute to a die based on the location provided.
986 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
987                                   const MachineLocation &Location) {
988   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
989   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
990   if (Location.isIndirect())
991     DwarfExpr.setMemoryLocationKind();
992 
993   DIExpressionCursor Cursor({});
994   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
995   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
996     return;
997   DwarfExpr.addExpression(std::move(Cursor));
998 
999   // Now attach the location information to the DIE.
1000   addBlock(Die, Attribute, DwarfExpr.finalize());
1001 }
1002 
1003 /// Start with the address based on the location provided, and generate the
1004 /// DWARF information necessary to find the actual variable given the extra
1005 /// address information encoded in the DbgVariable, starting from the starting
1006 /// location.  Add the DWARF information to the die.
1007 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
1008                                          dwarf::Attribute Attribute,
1009                                          const MachineLocation &Location) {
1010   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1011   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1012   const DIExpression *DIExpr = DV.getSingleExpression();
1013   DwarfExpr.addFragmentOffset(DIExpr);
1014   if (Location.isIndirect())
1015     DwarfExpr.setMemoryLocationKind();
1016 
1017   DIExpressionCursor Cursor(DIExpr);
1018   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1019   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1020     return;
1021   DwarfExpr.addExpression(std::move(Cursor));
1022 
1023   // Now attach the location information to the DIE.
1024   addBlock(Die, Attribute, DwarfExpr.finalize());
1025 }
1026 
1027 /// Add a Dwarf loclistptr attribute data and value.
1028 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
1029                                        unsigned Index) {
1030   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1031                                                 : dwarf::DW_FORM_data4;
1032   Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
1033 }
1034 
1035 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
1036                                                DIE &VariableDie) {
1037   StringRef Name = Var.getName();
1038   if (!Name.empty())
1039     addString(VariableDie, dwarf::DW_AT_name, Name);
1040   const auto *DIVar = Var.getVariable();
1041   if (DIVar)
1042     if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
1043       addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1044               AlignInBytes);
1045 
1046   addSourceLine(VariableDie, DIVar);
1047   addType(VariableDie, Var.getType());
1048   if (Var.isArtificial())
1049     addFlag(VariableDie, dwarf::DW_AT_artificial);
1050 }
1051 
1052 void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
1053                                             DIE &LabelDie) {
1054   StringRef Name = Label.getName();
1055   if (!Name.empty())
1056     addString(LabelDie, dwarf::DW_AT_name, Name);
1057   const auto *DILabel = Label.getLabel();
1058   addSourceLine(LabelDie, DILabel);
1059 }
1060 
1061 /// Add a Dwarf expression attribute data and value.
1062 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
1063                                const MCExpr *Expr) {
1064   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
1065 }
1066 
1067 void DwarfCompileUnit::applySubprogramAttributesToDefinition(
1068     const DISubprogram *SP, DIE &SPDie) {
1069   auto *SPDecl = SP->getDeclaration();
1070   auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope());
1071   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
1072   addGlobalName(SP->getName(), SPDie, Context);
1073 }
1074 
1075 bool DwarfCompileUnit::isDwoUnit() const {
1076   return DD->useSplitDwarf() && Skeleton;
1077 }
1078 
1079 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
1080   return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
1081          (DD->useSplitDwarf() && !Skeleton);
1082 }
1083