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.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "DwarfCompileUnit.h"
14 #include "AddressPool.h"
15 #include "DwarfExpression.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/BinaryFormat/Dwarf.h"
20 #include "llvm/CodeGen/AsmPrinter.h"
21 #include "llvm/CodeGen/DIE.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineOperand.h"
25 #include "llvm/CodeGen/TargetFrameLowering.h"
26 #include "llvm/CodeGen/TargetRegisterInfo.h"
27 #include "llvm/CodeGen/TargetSubtargetInfo.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/MC/MCSection.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCSymbolWasm.h"
35 #include "llvm/MC/MachineLocation.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include <iterator>
40 #include <string>
41 #include <utility>
42 
43 using namespace llvm;
44 
45 static dwarf::Tag GetCompileUnitType(UnitKind Kind, DwarfDebug *DW) {
46 
47   //  According to DWARF Debugging Information Format Version 5,
48   //  3.1.2 Skeleton Compilation Unit Entries:
49   //  "When generating a split DWARF object file (see Section 7.3.2
50   //  on page 187), the compilation unit in the .debug_info section
51   //  is a "skeleton" compilation unit with the tag DW_TAG_skeleton_unit"
52   if (DW->getDwarfVersion() >= 5 && Kind == UnitKind::Skeleton)
53     return dwarf::DW_TAG_skeleton_unit;
54 
55   return dwarf::DW_TAG_compile_unit;
56 }
57 
58 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
59                                    AsmPrinter *A, DwarfDebug *DW,
60                                    DwarfFile *DWU, UnitKind Kind)
61     : DwarfUnit(GetCompileUnitType(Kind, DW), Node, A, DW, DWU), UniqueID(UID) {
62   insertDIE(Node, &getUnitDie());
63   MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
64 }
65 
66 /// addLabelAddress - Add a dwarf label attribute data and value using
67 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
68 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
69                                        const MCSymbol *Label) {
70   // Don't use the address pool in non-fission or in the skeleton unit itself.
71   if ((!DD->useSplitDwarf() || !Skeleton) && DD->getDwarfVersion() < 5)
72     return addLocalLabelAddress(Die, Attribute, Label);
73 
74   if (Label)
75     DD->addArangeLabel(SymbolCU(this, Label));
76 
77   bool UseAddrOffsetFormOrExpressions =
78       DD->useAddrOffsetForm() || DD->useAddrOffsetExpressions();
79 
80   const MCSymbol *Base = nullptr;
81   if (Label->isInSection() && UseAddrOffsetFormOrExpressions)
82     Base = DD->getSectionLabel(&Label->getSection());
83 
84   if (!Base || Base == Label) {
85     unsigned idx = DD->getAddressPool().getIndex(Label);
86     Die.addValue(DIEValueAllocator, Attribute,
87                  DD->getDwarfVersion() >= 5 ? dwarf::DW_FORM_addrx
88                                             : dwarf::DW_FORM_GNU_addr_index,
89                  DIEInteger(idx));
90     return;
91   }
92 
93   // Could be extended to work with DWARFv4 Split DWARF if that's important for
94   // someone. In that case DW_FORM_data would be used.
95   assert(DD->getDwarfVersion() >= 5 &&
96          "Addr+offset expressions are only valuable when using debug_addr (to "
97          "reduce relocations) available in DWARFv5 or higher");
98   if (DD->useAddrOffsetExpressions()) {
99     auto *Loc = new (DIEValueAllocator) DIEBlock();
100     addPoolOpAddress(*Loc, Label);
101     addBlock(Die, Attribute, dwarf::DW_FORM_exprloc, Loc);
102   } else
103     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_LLVM_addrx_offset,
104                  new (DIEValueAllocator) DIEAddrOffset(
105                      DD->getAddressPool().getIndex(Base), Label, Base));
106 }
107 
108 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
109                                             dwarf::Attribute Attribute,
110                                             const MCSymbol *Label) {
111   if (Label)
112     DD->addArangeLabel(SymbolCU(this, Label));
113 
114   if (Label)
115     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
116                  DIELabel(Label));
117   else
118     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
119                  DIEInteger(0));
120 }
121 
122 unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
123   // If we print assembly, we can't separate .file entries according to
124   // compile units. Thus all files will belong to the default compile unit.
125 
126   // FIXME: add a better feature test than hasRawTextSupport. Even better,
127   // extend .file to support this.
128   unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
129   if (!File)
130     return Asm->OutStreamer->emitDwarfFileDirective(0, "", "", None, None,
131                                                     CUID);
132   return Asm->OutStreamer->emitDwarfFileDirective(
133       0, File->getDirectory(), File->getFilename(), DD->getMD5AsBytes(File),
134       File->getSource(), CUID);
135 }
136 
137 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
138     const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
139   // Check for pre-existence.
140   if (DIE *Die = getDIE(GV))
141     return Die;
142 
143   assert(GV);
144 
145   auto *GVContext = GV->getScope();
146   const DIType *GTy = GV->getType();
147 
148   // Construct the context before querying for the existence of the DIE in
149   // case such construction creates the DIE.
150   auto *CB = GVContext ? dyn_cast<DICommonBlock>(GVContext) : nullptr;
151   DIE *ContextDIE = CB ? getOrCreateCommonBlock(CB, GlobalExprs)
152     : getOrCreateContextDIE(GVContext);
153 
154   // Add to map.
155   DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
156   DIScope *DeclContext;
157   if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
158     DeclContext = SDMDecl->getScope();
159     assert(SDMDecl->isStaticMember() && "Expected static member decl");
160     assert(GV->isDefinition());
161     // We need the declaration DIE that is in the static member's class.
162     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
163     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
164     // If the global variable's type is different from the one in the class
165     // member type, assume that it's more specific and also emit it.
166     if (GTy != SDMDecl->getBaseType())
167       addType(*VariableDIE, GTy);
168   } else {
169     DeclContext = GV->getScope();
170     // Add name and type.
171     addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
172     if (GTy)
173       addType(*VariableDIE, GTy);
174 
175     // Add scoping info.
176     if (!GV->isLocalToUnit())
177       addFlag(*VariableDIE, dwarf::DW_AT_external);
178 
179     // Add line number info.
180     addSourceLine(*VariableDIE, GV);
181   }
182 
183   if (!GV->isDefinition())
184     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
185   else
186     addGlobalName(GV->getName(), *VariableDIE, DeclContext);
187 
188   if (uint32_t AlignInBytes = GV->getAlignInBytes())
189     addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
190             AlignInBytes);
191 
192   if (MDTuple *TP = GV->getTemplateParams())
193     addTemplateParams(*VariableDIE, DINodeArray(TP));
194 
195   // Add location.
196   addLocationAttribute(VariableDIE, GV, GlobalExprs);
197 
198   return VariableDIE;
199 }
200 
201 void DwarfCompileUnit::addLocationAttribute(
202     DIE *VariableDIE, const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
203   bool addToAccelTable = false;
204   DIELoc *Loc = nullptr;
205   Optional<unsigned> NVPTXAddressSpace;
206   std::unique_ptr<DIEDwarfExpression> DwarfExpr;
207   for (const auto &GE : GlobalExprs) {
208     const GlobalVariable *Global = GE.Var;
209     const DIExpression *Expr = GE.Expr;
210 
211     // For compatibility with DWARF 3 and earlier,
212     // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) becomes
213     // DW_AT_const_value(X).
214     if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
215       addToAccelTable = true;
216       addConstantValue(*VariableDIE, /*Unsigned=*/true, Expr->getElement(1));
217       break;
218     }
219 
220     // We cannot describe the location of dllimport'd variables: the
221     // computation of their address requires loads from the IAT.
222     if (Global && Global->hasDLLImportStorageClass())
223       continue;
224 
225     // Nothing to describe without address or constant.
226     if (!Global && (!Expr || !Expr->isConstant()))
227       continue;
228 
229     if (Global && Global->isThreadLocal() &&
230         !Asm->getObjFileLowering().supportDebugThreadLocalLocation())
231       continue;
232 
233     if (!Loc) {
234       addToAccelTable = true;
235       Loc = new (DIEValueAllocator) DIELoc;
236       DwarfExpr = std::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
237     }
238 
239     if (Expr) {
240       // According to
241       // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
242       // cuda-gdb requires DW_AT_address_class for all variables to be able to
243       // correctly interpret address space of the variable address.
244       // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
245       // sequence for the NVPTX + gdb target.
246       unsigned LocalNVPTXAddressSpace;
247       if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
248         const DIExpression *NewExpr =
249             DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
250         if (NewExpr != Expr) {
251           Expr = NewExpr;
252           NVPTXAddressSpace = LocalNVPTXAddressSpace;
253         }
254       }
255       DwarfExpr->addFragmentOffset(Expr);
256     }
257 
258     if (Global) {
259       const MCSymbol *Sym = Asm->getSymbol(Global);
260       if (Global->isThreadLocal()) {
261         if (Asm->TM.useEmulatedTLS()) {
262           // TODO: add debug info for emulated thread local mode.
263         } else {
264           // FIXME: Make this work with -gsplit-dwarf.
265           unsigned PointerSize = Asm->getDataLayout().getPointerSize();
266           assert((PointerSize == 4 || PointerSize == 8) &&
267                  "Add support for other sizes if necessary");
268           // Based on GCC's support for TLS:
269           if (!DD->useSplitDwarf()) {
270             // 1) Start with a constNu of the appropriate pointer size
271             addUInt(*Loc, dwarf::DW_FORM_data1,
272                     PointerSize == 4 ? dwarf::DW_OP_const4u
273                                      : dwarf::DW_OP_const8u);
274             // 2) containing the (relocated) offset of the TLS variable
275             //    within the module's TLS block.
276             addExpr(*Loc,
277                     PointerSize == 4 ? dwarf::DW_FORM_data4
278                                      : dwarf::DW_FORM_data8,
279                     Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
280           } else {
281             addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
282             addUInt(*Loc, dwarf::DW_FORM_udata,
283                     DD->getAddressPool().getIndex(Sym, /* TLS */ true));
284           }
285           // 3) followed by an OP to make the debugger do a TLS lookup.
286           addUInt(*Loc, dwarf::DW_FORM_data1,
287                   DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
288                                         : dwarf::DW_OP_form_tls_address);
289         }
290       } else {
291         DD->addArangeLabel(SymbolCU(this, Sym));
292         addOpAddress(*Loc, Sym);
293       }
294     }
295     // Global variables attached to symbols are memory locations.
296     // It would be better if this were unconditional, but malformed input that
297     // mixes non-fragments and fragments for the same variable is too expensive
298     // to detect in the verifier.
299     if (DwarfExpr->isUnknownLocation())
300       DwarfExpr->setMemoryLocationKind();
301     DwarfExpr->addExpression(Expr);
302   }
303   if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
304     // According to
305     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
306     // cuda-gdb requires DW_AT_address_class for all variables to be able to
307     // correctly interpret address space of the variable address.
308     const unsigned NVPTX_ADDR_global_space = 5;
309     addUInt(*VariableDIE, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
310             NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_global_space);
311   }
312   if (Loc)
313     addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
314 
315   if (DD->useAllLinkageNames())
316     addLinkageName(*VariableDIE, GV->getLinkageName());
317 
318   if (addToAccelTable) {
319     DD->addAccelName(*CUNode, GV->getName(), *VariableDIE);
320 
321     // If the linkage name is different than the name, go ahead and output
322     // that as well into the name table.
323     if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
324         DD->useAllLinkageNames())
325       DD->addAccelName(*CUNode, GV->getLinkageName(), *VariableDIE);
326   }
327 }
328 
329 DIE *DwarfCompileUnit::getOrCreateCommonBlock(
330     const DICommonBlock *CB, ArrayRef<GlobalExpr> GlobalExprs) {
331   // Construct the context before querying for the existence of the DIE in case
332   // such construction creates the DIE.
333   DIE *ContextDIE = getOrCreateContextDIE(CB->getScope());
334 
335   if (DIE *NDie = getDIE(CB))
336     return NDie;
337   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_common_block, *ContextDIE, CB);
338   StringRef Name = CB->getName().empty() ? "_BLNK_" : CB->getName();
339   addString(NDie, dwarf::DW_AT_name, Name);
340   addGlobalName(Name, NDie, CB->getScope());
341   if (CB->getFile())
342     addSourceLine(NDie, CB->getLineNo(), CB->getFile());
343   if (DIGlobalVariable *V = CB->getDecl())
344     getCU().addLocationAttribute(&NDie, V, GlobalExprs);
345   return &NDie;
346 }
347 
348 void DwarfCompileUnit::addRange(RangeSpan Range) {
349   DD->insertSectionLabel(Range.Begin);
350 
351   bool SameAsPrevCU = this == DD->getPrevCU();
352   DD->setPrevCU(this);
353   // If we have no current ranges just add the range and return, otherwise,
354   // check the current section and CU against the previous section and CU we
355   // emitted into and the subprogram was contained within. If these are the
356   // same then extend our current range, otherwise add this as a new range.
357   if (CURanges.empty() || !SameAsPrevCU ||
358       (&CURanges.back().End->getSection() !=
359        &Range.End->getSection())) {
360     CURanges.push_back(Range);
361     return;
362   }
363 
364   CURanges.back().End = Range.End;
365 }
366 
367 void DwarfCompileUnit::initStmtList() {
368   if (CUNode->isDebugDirectivesOnly())
369     return;
370 
371   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
372   if (DD->useSectionsAsReferences()) {
373     LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
374   } else {
375     LineTableStartSym =
376         Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
377   }
378 
379   // DW_AT_stmt_list is a offset of line number information for this
380   // compile unit in debug_line section. For split dwarf this is
381   // left in the skeleton CU and so not included.
382   // The line table entries are not always emitted in assembly, so it
383   // is not okay to use line_table_start here.
384       addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
385                       TLOF.getDwarfLineSection()->getBeginSymbol());
386 }
387 
388 void DwarfCompileUnit::applyStmtList(DIE &D) {
389   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
390   addSectionLabel(D, dwarf::DW_AT_stmt_list, LineTableStartSym,
391                   TLOF.getDwarfLineSection()->getBeginSymbol());
392 }
393 
394 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
395                                        const MCSymbol *End) {
396   assert(Begin && "Begin label should not be null!");
397   assert(End && "End label should not be null!");
398   assert(Begin->isDefined() && "Invalid starting label");
399   assert(End->isDefined() && "Invalid end label");
400 
401   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
402   if (DD->getDwarfVersion() < 4)
403     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
404   else
405     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
406 }
407 
408 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
409 // and DW_AT_high_pc attributes. If there are global variables in this
410 // scope then create and insert DIEs for these variables.
411 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
412   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
413 
414   SmallVector<RangeSpan, 2> BB_List;
415   // If basic block sections are on, ranges for each basic block section has
416   // to be emitted separately.
417   for (const auto &R : Asm->MBBSectionRanges)
418     BB_List.push_back({R.second.BeginLabel, R.second.EndLabel});
419 
420   attachRangesOrLowHighPC(*SPDie, BB_List);
421 
422   if (DD->useAppleExtensionAttributes() &&
423       !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
424           *DD->getCurrentFunction()))
425     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
426 
427   // Only include DW_AT_frame_base in full debug info
428   if (!includeMinimalInlineScopes()) {
429     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
430     TargetFrameLowering::DwarfFrameBase FrameBase =
431         TFI->getDwarfFrameBase(*Asm->MF);
432     switch (FrameBase.Kind) {
433     case TargetFrameLowering::DwarfFrameBase::Register: {
434       if (Register::isPhysicalRegister(FrameBase.Location.Reg)) {
435         MachineLocation Location(FrameBase.Location.Reg);
436         addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
437       }
438       break;
439     }
440     case TargetFrameLowering::DwarfFrameBase::CFA: {
441       DIELoc *Loc = new (DIEValueAllocator) DIELoc;
442       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa);
443       addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
444       break;
445     }
446     case TargetFrameLowering::DwarfFrameBase::WasmFrameBase: {
447       // FIXME: duplicated from Target/WebAssembly/WebAssembly.h
448       // don't want to depend on target specific headers in this code?
449       const unsigned TI_GLOBAL_RELOC = 3;
450       if (FrameBase.Location.WasmLoc.Kind == TI_GLOBAL_RELOC) {
451         // These need to be relocatable.
452         assert(FrameBase.Location.WasmLoc.Index == 0);  // Only SP so far.
453         auto SPSym = cast<MCSymbolWasm>(
454           Asm->GetExternalSymbolSymbol("__stack_pointer"));
455         // FIXME: this repeats what WebAssemblyMCInstLower::
456         // GetExternalSymbolSymbol does, since if there's no code that
457         // refers to this symbol, we have to set it here.
458         SPSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
459         SPSym->setGlobalType(wasm::WasmGlobalType{
460             uint8_t(Asm->getSubtargetInfo().getTargetTriple().getArch() ==
461                             Triple::wasm64
462                         ? wasm::WASM_TYPE_I64
463                         : wasm::WASM_TYPE_I32),
464             true});
465         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
466         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_WASM_location);
467         addSInt(*Loc, dwarf::DW_FORM_sdata, TI_GLOBAL_RELOC);
468         if (!isDwoUnit()) {
469           addLabel(*Loc, dwarf::DW_FORM_data4, SPSym);
470           DD->addArangeLabel(SymbolCU(this, SPSym));
471         } else {
472           // FIXME: when writing dwo, we need to avoid relocations. Probably
473           // the "right" solution is to treat globals the way func and data
474           // symbols are (with entries in .debug_addr).
475           // For now, since we only ever use index 0, this should work as-is.
476           addUInt(*Loc, dwarf::DW_FORM_data4, FrameBase.Location.WasmLoc.Index);
477         }
478         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
479         addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
480       } else {
481         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
482         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
483         DIExpressionCursor Cursor({});
484         DwarfExpr.addWasmLocation(FrameBase.Location.WasmLoc.Kind,
485             FrameBase.Location.WasmLoc.Index);
486         DwarfExpr.addExpression(std::move(Cursor));
487         addBlock(*SPDie, dwarf::DW_AT_frame_base, DwarfExpr.finalize());
488       }
489       break;
490     }
491     }
492   }
493 
494   // Add name to the name table, we do this here because we're guaranteed
495   // to have concrete versions of our DW_TAG_subprogram nodes.
496   DD->addSubprogramNames(*CUNode, SP, *SPDie);
497 
498   return *SPDie;
499 }
500 
501 // Construct a DIE for this scope.
502 void DwarfCompileUnit::constructScopeDIE(
503     LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
504   if (!Scope || !Scope->getScopeNode())
505     return;
506 
507   auto *DS = Scope->getScopeNode();
508 
509   assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
510          "Only handle inlined subprograms here, use "
511          "constructSubprogramScopeDIE for non-inlined "
512          "subprograms");
513 
514   SmallVector<DIE *, 8> Children;
515 
516   // We try to create the scope DIE first, then the children DIEs. This will
517   // avoid creating un-used children then removing them later when we find out
518   // the scope DIE is null.
519   DIE *ScopeDIE;
520   if (Scope->getParent() && isa<DISubprogram>(DS)) {
521     ScopeDIE = constructInlinedScopeDIE(Scope);
522     if (!ScopeDIE)
523       return;
524     // We create children when the scope DIE is not null.
525     createScopeChildrenDIE(Scope, Children);
526   } else {
527     // Early exit when we know the scope DIE is going to be null.
528     if (DD->isLexicalScopeDIENull(Scope))
529       return;
530 
531     bool HasNonScopeChildren = false;
532 
533     // We create children here when we know the scope DIE is not going to be
534     // null and the children will be added to the scope DIE.
535     createScopeChildrenDIE(Scope, Children, &HasNonScopeChildren);
536 
537     // If there are only other scopes as children, put them directly in the
538     // parent instead, as this scope would serve no purpose.
539     if (!HasNonScopeChildren) {
540       FinalChildren.insert(FinalChildren.end(),
541                            std::make_move_iterator(Children.begin()),
542                            std::make_move_iterator(Children.end()));
543       return;
544     }
545     ScopeDIE = constructLexicalScopeDIE(Scope);
546     assert(ScopeDIE && "Scope DIE should not be null.");
547   }
548 
549   // Add children
550   for (auto &I : Children)
551     ScopeDIE->addChild(std::move(I));
552 
553   FinalChildren.push_back(std::move(ScopeDIE));
554 }
555 
556 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
557                                          SmallVector<RangeSpan, 2> Range) {
558 
559   HasRangeLists = true;
560 
561   // Add the range list to the set of ranges to be emitted.
562   auto IndexAndList =
563       (DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU)
564           ->addRange(*(Skeleton ? Skeleton : this), std::move(Range));
565 
566   uint32_t Index = IndexAndList.first;
567   auto &List = *IndexAndList.second;
568 
569   // Under fission, ranges are specified by constant offsets relative to the
570   // CU's DW_AT_GNU_ranges_base.
571   // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
572   // fission until we support the forms using the .debug_addr section
573   // (DW_RLE_startx_endx etc.).
574   if (DD->getDwarfVersion() >= 5)
575     addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_rnglistx, Index);
576   else {
577     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
578     const MCSymbol *RangeSectionSym =
579         TLOF.getDwarfRangesSection()->getBeginSymbol();
580     if (isDwoUnit())
581       addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
582                       RangeSectionSym);
583     else
584       addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
585                       RangeSectionSym);
586   }
587 }
588 
589 void DwarfCompileUnit::attachRangesOrLowHighPC(
590     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
591   assert(!Ranges.empty());
592   if (!DD->useRangesSection() ||
593       (Ranges.size() == 1 &&
594        (!DD->alwaysUseRanges() ||
595         DD->getSectionLabel(&Ranges.front().Begin->getSection()) ==
596             Ranges.front().Begin))) {
597     const RangeSpan &Front = Ranges.front();
598     const RangeSpan &Back = Ranges.back();
599     attachLowHighPC(Die, Front.Begin, Back.End);
600   } else
601     addScopeRangeList(Die, std::move(Ranges));
602 }
603 
604 void DwarfCompileUnit::attachRangesOrLowHighPC(
605     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
606   SmallVector<RangeSpan, 2> List;
607   List.reserve(Ranges.size());
608   for (const InsnRange &R : Ranges) {
609     auto *BeginLabel = DD->getLabelBeforeInsn(R.first);
610     auto *EndLabel = DD->getLabelAfterInsn(R.second);
611 
612     const auto *BeginMBB = R.first->getParent();
613     const auto *EndMBB = R.second->getParent();
614 
615     const auto *MBB = BeginMBB;
616     // Basic block sections allows basic block subsets to be placed in unique
617     // sections. For each section, the begin and end label must be added to the
618     // list. If there is more than one range, debug ranges must be used.
619     // Otherwise, low/high PC can be used.
620     // FIXME: Debug Info Emission depends on block order and this assumes that
621     // the order of blocks will be frozen beyond this point.
622     do {
623       if (MBB->sameSection(EndMBB) || MBB->isEndSection()) {
624         auto MBBSectionRange = Asm->MBBSectionRanges[MBB->getSectionIDNum()];
625         List.push_back(
626             {MBB->sameSection(BeginMBB) ? BeginLabel
627                                         : MBBSectionRange.BeginLabel,
628              MBB->sameSection(EndMBB) ? EndLabel : MBBSectionRange.EndLabel});
629       }
630       if (MBB->sameSection(EndMBB))
631         break;
632       MBB = MBB->getNextNode();
633     } while (true);
634   }
635   attachRangesOrLowHighPC(Die, std::move(List));
636 }
637 
638 // This scope represents inlined body of a function. Construct DIE to
639 // represent this concrete inlined copy of the function.
640 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
641   assert(Scope->getScopeNode());
642   auto *DS = Scope->getScopeNode();
643   auto *InlinedSP = getDISubprogram(DS);
644   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
645   // was inlined from another compile unit.
646   DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
647   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
648 
649   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
650   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
651 
652   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
653 
654   // Add the call site information to the DIE.
655   const DILocation *IA = Scope->getInlinedAt();
656   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
657           getOrCreateSourceID(IA->getFile()));
658   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
659   if (IA->getColumn())
660     addUInt(*ScopeDIE, dwarf::DW_AT_call_column, None, IA->getColumn());
661   if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
662     addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
663             IA->getDiscriminator());
664 
665   // Add name to the name table, we do this here because we're guaranteed
666   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
667   DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
668 
669   return ScopeDIE;
670 }
671 
672 // Construct new DW_TAG_lexical_block for this scope and attach
673 // DW_AT_low_pc/DW_AT_high_pc labels.
674 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
675   if (DD->isLexicalScopeDIENull(Scope))
676     return nullptr;
677 
678   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
679   if (Scope->isAbstractScope())
680     return ScopeDIE;
681 
682   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
683 
684   return ScopeDIE;
685 }
686 
687 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
688 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
689   auto D = constructVariableDIEImpl(DV, Abstract);
690   DV.setDIE(*D);
691   return D;
692 }
693 
694 DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
695                                          const LexicalScope &Scope) {
696   auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
697   insertDIE(DL.getLabel(), LabelDie);
698   DL.setDIE(*LabelDie);
699 
700   if (Scope.isAbstractScope())
701     applyLabelAttributes(DL, *LabelDie);
702 
703   return LabelDie;
704 }
705 
706 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
707                                                 bool Abstract) {
708   // Define variable debug information entry.
709   auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
710   insertDIE(DV.getVariable(), VariableDie);
711 
712   if (Abstract) {
713     applyVariableAttributes(DV, *VariableDie);
714     return VariableDie;
715   }
716 
717   // Add variable address.
718 
719   unsigned Index = DV.getDebugLocListIndex();
720   if (Index != ~0U) {
721     addLocationList(*VariableDie, dwarf::DW_AT_location, Index);
722     auto TagOffset = DV.getDebugLocListTagOffset();
723     if (TagOffset)
724       addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
725               *TagOffset);
726     return VariableDie;
727   }
728 
729   // Check if variable has a single location description.
730   if (auto *DVal = DV.getValueLoc()) {
731     if (!DVal->isVariadic()) {
732       const DbgValueLocEntry *Entry = DVal->getLocEntries().begin();
733       if (Entry->isLocation()) {
734         addVariableAddress(DV, *VariableDie, Entry->getLoc());
735       } else if (Entry->isInt()) {
736         auto *Expr = DV.getSingleExpression();
737         if (Expr && Expr->getNumElements()) {
738           DIELoc *Loc = new (DIEValueAllocator) DIELoc;
739           DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
740           // If there is an expression, emit raw unsigned bytes.
741           DwarfExpr.addFragmentOffset(Expr);
742           DwarfExpr.addUnsignedConstant(Entry->getInt());
743           DwarfExpr.addExpression(Expr);
744           addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
745           if (DwarfExpr.TagOffset)
746             addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset,
747                     dwarf::DW_FORM_data1, *DwarfExpr.TagOffset);
748         } else
749           addConstantValue(*VariableDie, Entry->getInt(), DV.getType());
750       } else if (Entry->isConstantFP()) {
751         addConstantFPValue(*VariableDie, Entry->getConstantFP());
752       } else if (Entry->isConstantInt()) {
753         addConstantValue(*VariableDie, Entry->getConstantInt(), DV.getType());
754       } else if (Entry->isTargetIndexLocation()) {
755         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
756         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
757         const DIBasicType *BT = dyn_cast<DIBasicType>(
758             static_cast<const Metadata *>(DV.getVariable()->getType()));
759         DwarfDebug::emitDebugLocValue(*Asm, BT, *DVal, DwarfExpr);
760         addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
761       }
762       return VariableDie;
763     }
764     // If any of the location entries are registers with the value 0, then the
765     // location is undefined.
766     if (any_of(DVal->getLocEntries(), [](const DbgValueLocEntry &Entry) {
767           return Entry.isLocation() && !Entry.getLoc().getReg();
768         }))
769       return VariableDie;
770     const DIExpression *Expr = DV.getSingleExpression();
771     assert(Expr && "Variadic Debug Value must have an Expression.");
772     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
773     DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
774     DwarfExpr.addFragmentOffset(Expr);
775     DIExpressionCursor Cursor(Expr);
776     const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
777 
778     auto AddEntry = [&](const DbgValueLocEntry &Entry,
779                                             DIExpressionCursor &Cursor) {
780       if (Entry.isLocation()) {
781         if (!DwarfExpr.addMachineRegExpression(TRI, Cursor,
782                                                Entry.getLoc().getReg()))
783           return false;
784       } else if (Entry.isInt()) {
785         // If there is an expression, emit raw unsigned bytes.
786         DwarfExpr.addUnsignedConstant(Entry.getInt());
787       } else if (Entry.isConstantFP()) {
788         APInt RawBytes = Entry.getConstantFP()->getValueAPF().bitcastToAPInt();
789         DwarfExpr.addUnsignedConstant(RawBytes);
790       } else if (Entry.isConstantInt()) {
791         APInt RawBytes = Entry.getConstantInt()->getValue();
792         DwarfExpr.addUnsignedConstant(RawBytes);
793       } else if (Entry.isTargetIndexLocation()) {
794         TargetIndexLocation Loc = Entry.getTargetIndexLocation();
795         // TODO TargetIndexLocation is a target-independent. Currently only the
796         // WebAssembly-specific encoding is supported.
797         assert(Asm->TM.getTargetTriple().isWasm());
798         DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
799       } else {
800         llvm_unreachable("Unsupported Entry type.");
801       }
802       return true;
803     };
804 
805     DwarfExpr.addExpression(
806         std::move(Cursor),
807         [&](unsigned Idx, DIExpressionCursor &Cursor) -> bool {
808           return AddEntry(DVal->getLocEntries()[Idx], Cursor);
809         });
810 
811     // Now attach the location information to the DIE.
812     addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
813     if (DwarfExpr.TagOffset)
814       addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
815               *DwarfExpr.TagOffset);
816 
817     return VariableDie;
818   }
819 
820   // .. else use frame index.
821   if (!DV.hasFrameIndexExprs())
822     return VariableDie;
823 
824   Optional<unsigned> NVPTXAddressSpace;
825   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
826   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
827   for (auto &Fragment : DV.getFrameIndexExprs()) {
828     Register FrameReg;
829     const DIExpression *Expr = Fragment.Expr;
830     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
831     StackOffset Offset =
832         TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
833     DwarfExpr.addFragmentOffset(Expr);
834 
835     auto *TRI = Asm->MF->getSubtarget().getRegisterInfo();
836     SmallVector<uint64_t, 8> Ops;
837     TRI->getOffsetOpcodes(Offset, Ops);
838 
839     // According to
840     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
841     // cuda-gdb requires DW_AT_address_class for all variables to be able to
842     // correctly interpret address space of the variable address.
843     // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
844     // sequence for the NVPTX + gdb target.
845     unsigned LocalNVPTXAddressSpace;
846     if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
847       const DIExpression *NewExpr =
848           DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
849       if (NewExpr != Expr) {
850         Expr = NewExpr;
851         NVPTXAddressSpace = LocalNVPTXAddressSpace;
852       }
853     }
854     if (Expr)
855       Ops.append(Expr->elements_begin(), Expr->elements_end());
856     DIExpressionCursor Cursor(Ops);
857     DwarfExpr.setMemoryLocationKind();
858     if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
859       addOpAddress(*Loc, FrameSymbol);
860     else
861       DwarfExpr.addMachineRegExpression(
862           *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
863     DwarfExpr.addExpression(std::move(Cursor));
864   }
865   if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
866     // According to
867     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
868     // cuda-gdb requires DW_AT_address_class for all variables to be able to
869     // correctly interpret address space of the variable address.
870     const unsigned NVPTX_ADDR_local_space = 6;
871     addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
872             NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space);
873   }
874   addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
875   if (DwarfExpr.TagOffset)
876     addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
877             *DwarfExpr.TagOffset);
878 
879   return VariableDie;
880 }
881 
882 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
883                                             const LexicalScope &Scope,
884                                             DIE *&ObjectPointer) {
885   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
886   if (DV.isObjectPointer())
887     ObjectPointer = Var;
888   return Var;
889 }
890 
891 /// Return all DIVariables that appear in count: expressions.
892 static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
893   SmallVector<const DIVariable *, 2> Result;
894   auto *Array = dyn_cast<DICompositeType>(Var->getType());
895   if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
896     return Result;
897   if (auto *DLVar = Array->getDataLocation())
898     Result.push_back(DLVar);
899   if (auto *AsVar = Array->getAssociated())
900     Result.push_back(AsVar);
901   if (auto *AlVar = Array->getAllocated())
902     Result.push_back(AlVar);
903   for (auto *El : Array->getElements()) {
904     if (auto *Subrange = dyn_cast<DISubrange>(El)) {
905       if (auto Count = Subrange->getCount())
906         if (auto *Dependency = Count.dyn_cast<DIVariable *>())
907           Result.push_back(Dependency);
908       if (auto LB = Subrange->getLowerBound())
909         if (auto *Dependency = LB.dyn_cast<DIVariable *>())
910           Result.push_back(Dependency);
911       if (auto UB = Subrange->getUpperBound())
912         if (auto *Dependency = UB.dyn_cast<DIVariable *>())
913           Result.push_back(Dependency);
914       if (auto ST = Subrange->getStride())
915         if (auto *Dependency = ST.dyn_cast<DIVariable *>())
916           Result.push_back(Dependency);
917     } else if (auto *GenericSubrange = dyn_cast<DIGenericSubrange>(El)) {
918       if (auto Count = GenericSubrange->getCount())
919         if (auto *Dependency = Count.dyn_cast<DIVariable *>())
920           Result.push_back(Dependency);
921       if (auto LB = GenericSubrange->getLowerBound())
922         if (auto *Dependency = LB.dyn_cast<DIVariable *>())
923           Result.push_back(Dependency);
924       if (auto UB = GenericSubrange->getUpperBound())
925         if (auto *Dependency = UB.dyn_cast<DIVariable *>())
926           Result.push_back(Dependency);
927       if (auto ST = GenericSubrange->getStride())
928         if (auto *Dependency = ST.dyn_cast<DIVariable *>())
929           Result.push_back(Dependency);
930     }
931   }
932   return Result;
933 }
934 
935 /// Sort local variables so that variables appearing inside of helper
936 /// expressions come first.
937 static SmallVector<DbgVariable *, 8>
938 sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
939   SmallVector<DbgVariable *, 8> Result;
940   SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
941   // Map back from a DIVariable to its containing DbgVariable.
942   SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
943   // Set of DbgVariables in Result.
944   SmallDenseSet<DbgVariable *, 8> Visited;
945   // For cycle detection.
946   SmallDenseSet<DbgVariable *, 8> Visiting;
947 
948   // Initialize the worklist and the DIVariable lookup table.
949   for (auto Var : reverse(Input)) {
950     DbgVar.insert({Var->getVariable(), Var});
951     WorkList.push_back({Var, 0});
952   }
953 
954   // Perform a stable topological sort by doing a DFS.
955   while (!WorkList.empty()) {
956     auto Item = WorkList.back();
957     DbgVariable *Var = Item.getPointer();
958     bool visitedAllDependencies = Item.getInt();
959     WorkList.pop_back();
960 
961     // Dependency is in a different lexical scope or a global.
962     if (!Var)
963       continue;
964 
965     // Already handled.
966     if (Visited.count(Var))
967       continue;
968 
969     // Add to Result if all dependencies are visited.
970     if (visitedAllDependencies) {
971       Visited.insert(Var);
972       Result.push_back(Var);
973       continue;
974     }
975 
976     // Detect cycles.
977     auto Res = Visiting.insert(Var);
978     if (!Res.second) {
979       assert(false && "dependency cycle in local variables");
980       return Result;
981     }
982 
983     // Push dependencies and this node onto the worklist, so that this node is
984     // visited again after all of its dependencies are handled.
985     WorkList.push_back({Var, 1});
986     for (auto *Dependency : dependencies(Var)) {
987       auto Dep = dyn_cast_or_null<const DILocalVariable>(Dependency);
988       WorkList.push_back({DbgVar[Dep], 0});
989     }
990   }
991   return Result;
992 }
993 
994 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
995                                               SmallVectorImpl<DIE *> &Children,
996                                               bool *HasNonScopeChildren) {
997   assert(Children.empty());
998   DIE *ObjectPointer = nullptr;
999 
1000   // Emit function arguments (order is significant).
1001   auto Vars = DU->getScopeVariables().lookup(Scope);
1002   for (auto &DV : Vars.Args)
1003     Children.push_back(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
1004 
1005   // Emit local variables.
1006   auto Locals = sortLocalVars(Vars.Locals);
1007   for (DbgVariable *DV : Locals)
1008     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
1009 
1010   // Skip imported directives in gmlt-like data.
1011   if (!includeMinimalInlineScopes()) {
1012     // There is no need to emit empty lexical block DIE.
1013     for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
1014       Children.push_back(
1015           constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
1016   }
1017 
1018   if (HasNonScopeChildren)
1019     *HasNonScopeChildren = !Children.empty();
1020 
1021   for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
1022     Children.push_back(constructLabelDIE(*DL, *Scope));
1023 
1024   for (LexicalScope *LS : Scope->getChildren())
1025     constructScopeDIE(LS, Children);
1026 
1027   return ObjectPointer;
1028 }
1029 
1030 DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub,
1031                                                    LexicalScope *Scope) {
1032   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
1033 
1034   if (Scope) {
1035     assert(!Scope->getInlinedAt());
1036     assert(!Scope->isAbstractScope());
1037     // Collect lexical scope children first.
1038     // ObjectPointer might be a local (non-argument) local variable if it's a
1039     // block's synthetic this pointer.
1040     if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
1041       addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
1042   }
1043 
1044   // If this is a variadic function, add an unspecified parameter.
1045   DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
1046 
1047   // If we have a single element of null, it is a function that returns void.
1048   // If we have more than one elements and the last one is null, it is a
1049   // variadic function.
1050   if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
1051       !includeMinimalInlineScopes())
1052     ScopeDIE.addChild(
1053         DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
1054 
1055   return ScopeDIE;
1056 }
1057 
1058 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
1059                                                  DIE &ScopeDIE) {
1060   // We create children when the scope DIE is not null.
1061   SmallVector<DIE *, 8> Children;
1062   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
1063 
1064   // Add children
1065   for (auto &I : Children)
1066     ScopeDIE.addChild(std::move(I));
1067 
1068   return ObjectPointer;
1069 }
1070 
1071 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
1072     LexicalScope *Scope) {
1073   DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
1074   if (AbsDef)
1075     return;
1076 
1077   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
1078 
1079   DIE *ContextDIE;
1080   DwarfCompileUnit *ContextCU = this;
1081 
1082   if (includeMinimalInlineScopes())
1083     ContextDIE = &getUnitDie();
1084   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
1085   // the important distinction that the debug node is not associated with the
1086   // DIE (since the debug node will be associated with the concrete DIE, if
1087   // any). It could be refactored to some common utility function.
1088   else if (auto *SPDecl = SP->getDeclaration()) {
1089     ContextDIE = &getUnitDie();
1090     getOrCreateSubprogramDIE(SPDecl);
1091   } else {
1092     ContextDIE = getOrCreateContextDIE(SP->getScope());
1093     // The scope may be shared with a subprogram that has already been
1094     // constructed in another CU, in which case we need to construct this
1095     // subprogram in the same CU.
1096     ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
1097   }
1098 
1099   // Passing null as the associated node because the abstract definition
1100   // shouldn't be found by lookup.
1101   AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
1102   ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
1103 
1104   if (!ContextCU->includeMinimalInlineScopes())
1105     ContextCU->addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
1106   if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
1107     ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
1108 }
1109 
1110 bool DwarfCompileUnit::useGNUAnalogForDwarf5Feature() const {
1111   return DD->getDwarfVersion() == 4 && !DD->tuneForLLDB();
1112 }
1113 
1114 dwarf::Tag DwarfCompileUnit::getDwarf5OrGNUTag(dwarf::Tag Tag) const {
1115   if (!useGNUAnalogForDwarf5Feature())
1116     return Tag;
1117   switch (Tag) {
1118   case dwarf::DW_TAG_call_site:
1119     return dwarf::DW_TAG_GNU_call_site;
1120   case dwarf::DW_TAG_call_site_parameter:
1121     return dwarf::DW_TAG_GNU_call_site_parameter;
1122   default:
1123     llvm_unreachable("DWARF5 tag with no GNU analog");
1124   }
1125 }
1126 
1127 dwarf::Attribute
1128 DwarfCompileUnit::getDwarf5OrGNUAttr(dwarf::Attribute Attr) const {
1129   if (!useGNUAnalogForDwarf5Feature())
1130     return Attr;
1131   switch (Attr) {
1132   case dwarf::DW_AT_call_all_calls:
1133     return dwarf::DW_AT_GNU_all_call_sites;
1134   case dwarf::DW_AT_call_target:
1135     return dwarf::DW_AT_GNU_call_site_target;
1136   case dwarf::DW_AT_call_origin:
1137     return dwarf::DW_AT_abstract_origin;
1138   case dwarf::DW_AT_call_return_pc:
1139     return dwarf::DW_AT_low_pc;
1140   case dwarf::DW_AT_call_value:
1141     return dwarf::DW_AT_GNU_call_site_value;
1142   case dwarf::DW_AT_call_tail_call:
1143     return dwarf::DW_AT_GNU_tail_call;
1144   default:
1145     llvm_unreachable("DWARF5 attribute with no GNU analog");
1146   }
1147 }
1148 
1149 dwarf::LocationAtom
1150 DwarfCompileUnit::getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const {
1151   if (!useGNUAnalogForDwarf5Feature())
1152     return Loc;
1153   switch (Loc) {
1154   case dwarf::DW_OP_entry_value:
1155     return dwarf::DW_OP_GNU_entry_value;
1156   default:
1157     llvm_unreachable("DWARF5 location atom with no GNU analog");
1158   }
1159 }
1160 
1161 DIE &DwarfCompileUnit::constructCallSiteEntryDIE(DIE &ScopeDIE,
1162                                                  DIE *CalleeDIE,
1163                                                  bool IsTail,
1164                                                  const MCSymbol *PCAddr,
1165                                                  const MCSymbol *CallAddr,
1166                                                  unsigned CallReg) {
1167   // Insert a call site entry DIE within ScopeDIE.
1168   DIE &CallSiteDIE = createAndAddDIE(getDwarf5OrGNUTag(dwarf::DW_TAG_call_site),
1169                                      ScopeDIE, nullptr);
1170 
1171   if (CallReg) {
1172     // Indirect call.
1173     addAddress(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_target),
1174                MachineLocation(CallReg));
1175   } else {
1176     assert(CalleeDIE && "No DIE for call site entry origin");
1177     addDIEEntry(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_origin),
1178                 *CalleeDIE);
1179   }
1180 
1181   if (IsTail) {
1182     // Attach DW_AT_call_tail_call to tail calls for standards compliance.
1183     addFlag(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_tail_call));
1184 
1185     // Attach the address of the branch instruction to allow the debugger to
1186     // show where the tail call occurred. This attribute has no GNU analog.
1187     //
1188     // GDB works backwards from non-standard usage of DW_AT_low_pc (in DWARF4
1189     // mode -- equivalently, in DWARF5 mode, DW_AT_call_return_pc) at tail-call
1190     // site entries to figure out the PC of tail-calling branch instructions.
1191     // This means it doesn't need the compiler to emit DW_AT_call_pc, so we
1192     // don't emit it here.
1193     //
1194     // There's no need to tie non-GDB debuggers to this non-standardness, as it
1195     // adds unnecessary complexity to the debugger. For non-GDB debuggers, emit
1196     // the standard DW_AT_call_pc info.
1197     if (!useGNUAnalogForDwarf5Feature())
1198       addLabelAddress(CallSiteDIE, dwarf::DW_AT_call_pc, CallAddr);
1199   }
1200 
1201   // Attach the return PC to allow the debugger to disambiguate call paths
1202   // from one function to another.
1203   //
1204   // The return PC is only really needed when the call /isn't/ a tail call, but
1205   // GDB expects it in DWARF4 mode, even for tail calls (see the comment above
1206   // the DW_AT_call_pc emission logic for an explanation).
1207   if (!IsTail || useGNUAnalogForDwarf5Feature()) {
1208     assert(PCAddr && "Missing return PC information for a call");
1209     addLabelAddress(CallSiteDIE,
1210                     getDwarf5OrGNUAttr(dwarf::DW_AT_call_return_pc), PCAddr);
1211   }
1212 
1213   return CallSiteDIE;
1214 }
1215 
1216 void DwarfCompileUnit::constructCallSiteParmEntryDIEs(
1217     DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) {
1218   for (const auto &Param : Params) {
1219     unsigned Register = Param.getRegister();
1220     auto CallSiteDieParam =
1221         DIE::get(DIEValueAllocator,
1222                  getDwarf5OrGNUTag(dwarf::DW_TAG_call_site_parameter));
1223     insertDIE(CallSiteDieParam);
1224     addAddress(*CallSiteDieParam, dwarf::DW_AT_location,
1225                MachineLocation(Register));
1226 
1227     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1228     DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1229     DwarfExpr.setCallSiteParamValueFlag();
1230 
1231     DwarfDebug::emitDebugLocValue(*Asm, nullptr, Param.getValue(), DwarfExpr);
1232 
1233     addBlock(*CallSiteDieParam, getDwarf5OrGNUAttr(dwarf::DW_AT_call_value),
1234              DwarfExpr.finalize());
1235 
1236     CallSiteDIE.addChild(CallSiteDieParam);
1237   }
1238 }
1239 
1240 DIE *DwarfCompileUnit::constructImportedEntityDIE(
1241     const DIImportedEntity *Module) {
1242   DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
1243   insertDIE(Module, IMDie);
1244   DIE *EntityDie;
1245   auto *Entity = Module->getEntity();
1246   if (auto *NS = dyn_cast<DINamespace>(Entity))
1247     EntityDie = getOrCreateNameSpace(NS);
1248   else if (auto *M = dyn_cast<DIModule>(Entity))
1249     EntityDie = getOrCreateModule(M);
1250   else if (auto *SP = dyn_cast<DISubprogram>(Entity))
1251     EntityDie = getOrCreateSubprogramDIE(SP);
1252   else if (auto *T = dyn_cast<DIType>(Entity))
1253     EntityDie = getOrCreateTypeDIE(T);
1254   else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
1255     EntityDie = getOrCreateGlobalVariableDIE(GV, {});
1256   else
1257     EntityDie = getDIE(Entity);
1258   assert(EntityDie);
1259   addSourceLine(*IMDie, Module->getLine(), Module->getFile());
1260   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
1261   StringRef Name = Module->getName();
1262   if (!Name.empty())
1263     addString(*IMDie, dwarf::DW_AT_name, Name);
1264 
1265   return IMDie;
1266 }
1267 
1268 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
1269   DIE *D = getDIE(SP);
1270   if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
1271     if (D)
1272       // If this subprogram has an abstract definition, reference that
1273       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
1274   } else {
1275     assert(D || includeMinimalInlineScopes());
1276     if (D)
1277       // And attach the attributes
1278       applySubprogramAttributesToDefinition(SP, *D);
1279   }
1280 }
1281 
1282 void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
1283   DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
1284 
1285   auto *Die = Entity->getDIE();
1286   /// Label may be used to generate DW_AT_low_pc, so put it outside
1287   /// if/else block.
1288   const DbgLabel *Label = nullptr;
1289   if (AbsEntity && AbsEntity->getDIE()) {
1290     addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
1291     Label = dyn_cast<const DbgLabel>(Entity);
1292   } else {
1293     if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
1294       applyVariableAttributes(*Var, *Die);
1295     else if ((Label = dyn_cast<const DbgLabel>(Entity)))
1296       applyLabelAttributes(*Label, *Die);
1297     else
1298       llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
1299   }
1300 
1301   if (Label)
1302     if (const auto *Sym = Label->getSymbol())
1303       addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
1304 }
1305 
1306 DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
1307   auto &AbstractEntities = getAbstractEntities();
1308   auto I = AbstractEntities.find(Node);
1309   if (I != AbstractEntities.end())
1310     return I->second.get();
1311   return nullptr;
1312 }
1313 
1314 void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
1315                                             LexicalScope *Scope) {
1316   assert(Scope && Scope->isAbstractScope());
1317   auto &Entity = getAbstractEntities()[Node];
1318   if (isa<const DILocalVariable>(Node)) {
1319     Entity = std::make_unique<DbgVariable>(
1320                         cast<const DILocalVariable>(Node), nullptr /* IA */);;
1321     DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
1322   } else if (isa<const DILabel>(Node)) {
1323     Entity = std::make_unique<DbgLabel>(
1324                         cast<const DILabel>(Node), nullptr /* IA */);
1325     DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
1326   }
1327 }
1328 
1329 void DwarfCompileUnit::emitHeader(bool UseOffsets) {
1330   // Don't bother labeling the .dwo unit, as its offset isn't used.
1331   if (!Skeleton && !DD->useSectionsAsReferences()) {
1332     LabelBegin = Asm->createTempSymbol("cu_begin");
1333     Asm->OutStreamer->emitLabel(LabelBegin);
1334   }
1335 
1336   dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
1337                                 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
1338                                                       : dwarf::DW_UT_compile;
1339   DwarfUnit::emitCommonHeader(UseOffsets, UT);
1340   if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
1341     Asm->emitInt64(getDWOId());
1342 }
1343 
1344 bool DwarfCompileUnit::hasDwarfPubSections() const {
1345   switch (CUNode->getNameTableKind()) {
1346   case DICompileUnit::DebugNameTableKind::None:
1347     return false;
1348     // Opting in to GNU Pubnames/types overrides the default to ensure these are
1349     // generated for things like Gold's gdb_index generation.
1350   case DICompileUnit::DebugNameTableKind::GNU:
1351     return true;
1352   case DICompileUnit::DebugNameTableKind::Default:
1353     return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
1354            !CUNode->isDebugDirectivesOnly() &&
1355            DD->getAccelTableKind() != AccelTableKind::Apple &&
1356            DD->getDwarfVersion() < 5;
1357   }
1358   llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
1359 }
1360 
1361 /// addGlobalName - Add a new global name to the compile unit.
1362 void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
1363                                      const DIScope *Context) {
1364   if (!hasDwarfPubSections())
1365     return;
1366   std::string FullName = getParentContextString(Context) + Name.str();
1367   GlobalNames[FullName] = &Die;
1368 }
1369 
1370 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
1371                                                 const DIScope *Context) {
1372   if (!hasDwarfPubSections())
1373     return;
1374   std::string FullName = getParentContextString(Context) + Name.str();
1375   // Insert, allowing the entry to remain as-is if it's already present
1376   // This way the CU-level type DIE is preferred over the "can't describe this
1377   // type as a unit offset because it's not really in the CU at all, it's only
1378   // in a type unit"
1379   GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1380 }
1381 
1382 /// Add a new global type to the unit.
1383 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1384                                      const DIScope *Context) {
1385   if (!hasDwarfPubSections())
1386     return;
1387   std::string FullName = getParentContextString(Context) + Ty->getName().str();
1388   GlobalTypes[FullName] = &Die;
1389 }
1390 
1391 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
1392                                              const DIScope *Context) {
1393   if (!hasDwarfPubSections())
1394     return;
1395   std::string FullName = getParentContextString(Context) + Ty->getName().str();
1396   // Insert, allowing the entry to remain as-is if it's already present
1397   // This way the CU-level type DIE is preferred over the "can't describe this
1398   // type as a unit offset because it's not really in the CU at all, it's only
1399   // in a type unit"
1400   GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1401 }
1402 
1403 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
1404                                           MachineLocation Location) {
1405   if (DV.hasComplexAddress())
1406     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
1407   else
1408     addAddress(Die, dwarf::DW_AT_location, Location);
1409 }
1410 
1411 /// Add an address attribute to a die based on the location provided.
1412 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
1413                                   const MachineLocation &Location) {
1414   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1415   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1416   if (Location.isIndirect())
1417     DwarfExpr.setMemoryLocationKind();
1418 
1419   DIExpressionCursor Cursor({});
1420   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1421   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1422     return;
1423   DwarfExpr.addExpression(std::move(Cursor));
1424 
1425   // Now attach the location information to the DIE.
1426   addBlock(Die, Attribute, DwarfExpr.finalize());
1427 
1428   if (DwarfExpr.TagOffset)
1429     addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1430             *DwarfExpr.TagOffset);
1431 }
1432 
1433 /// Start with the address based on the location provided, and generate the
1434 /// DWARF information necessary to find the actual variable given the extra
1435 /// address information encoded in the DbgVariable, starting from the starting
1436 /// location.  Add the DWARF information to the die.
1437 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
1438                                          dwarf::Attribute Attribute,
1439                                          const MachineLocation &Location) {
1440   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1441   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1442   const DIExpression *DIExpr = DV.getSingleExpression();
1443   DwarfExpr.addFragmentOffset(DIExpr);
1444   DwarfExpr.setLocation(Location, DIExpr);
1445 
1446   DIExpressionCursor Cursor(DIExpr);
1447 
1448   if (DIExpr->isEntryValue())
1449     DwarfExpr.beginEntryValueExpression(Cursor);
1450 
1451   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1452   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1453     return;
1454   DwarfExpr.addExpression(std::move(Cursor));
1455 
1456   // Now attach the location information to the DIE.
1457   addBlock(Die, Attribute, DwarfExpr.finalize());
1458 
1459   if (DwarfExpr.TagOffset)
1460     addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1461             *DwarfExpr.TagOffset);
1462 }
1463 
1464 /// Add a Dwarf loclistptr attribute data and value.
1465 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
1466                                        unsigned Index) {
1467   dwarf::Form Form = (DD->getDwarfVersion() >= 5)
1468                          ? dwarf::DW_FORM_loclistx
1469                          : DD->getDwarfSectionOffsetForm();
1470   Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
1471 }
1472 
1473 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
1474                                                DIE &VariableDie) {
1475   StringRef Name = Var.getName();
1476   if (!Name.empty())
1477     addString(VariableDie, dwarf::DW_AT_name, Name);
1478   const auto *DIVar = Var.getVariable();
1479   if (DIVar)
1480     if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
1481       addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1482               AlignInBytes);
1483 
1484   addSourceLine(VariableDie, DIVar);
1485   addType(VariableDie, Var.getType());
1486   if (Var.isArtificial())
1487     addFlag(VariableDie, dwarf::DW_AT_artificial);
1488 }
1489 
1490 void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
1491                                             DIE &LabelDie) {
1492   StringRef Name = Label.getName();
1493   if (!Name.empty())
1494     addString(LabelDie, dwarf::DW_AT_name, Name);
1495   const auto *DILabel = Label.getLabel();
1496   addSourceLine(LabelDie, DILabel);
1497 }
1498 
1499 /// Add a Dwarf expression attribute data and value.
1500 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
1501                                const MCExpr *Expr) {
1502   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
1503 }
1504 
1505 void DwarfCompileUnit::applySubprogramAttributesToDefinition(
1506     const DISubprogram *SP, DIE &SPDie) {
1507   auto *SPDecl = SP->getDeclaration();
1508   auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope();
1509   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
1510   addGlobalName(SP->getName(), SPDie, Context);
1511 }
1512 
1513 bool DwarfCompileUnit::isDwoUnit() const {
1514   return DD->useSplitDwarf() && Skeleton;
1515 }
1516 
1517 void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
1518   constructTypeDIE(D, CTy);
1519 }
1520 
1521 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
1522   return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
1523          (DD->useSplitDwarf() && !Skeleton);
1524 }
1525 
1526 void DwarfCompileUnit::addAddrTableBase() {
1527   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1528   MCSymbol *Label = DD->getAddressPool().getLabel();
1529   addSectionLabel(getUnitDie(),
1530                   DD->getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
1531                                              : dwarf::DW_AT_GNU_addr_base,
1532                   Label, TLOF.getDwarfAddrSection()->getBeginSymbol());
1533 }
1534 
1535 void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) {
1536   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, dwarf::DW_FORM_udata,
1537                new (DIEValueAllocator) DIEBaseTypeRef(this, Idx));
1538 }
1539 
1540 void DwarfCompileUnit::createBaseTypeDIEs() {
1541   // Insert the base_type DIEs directly after the CU so that their offsets will
1542   // fit in the fixed size ULEB128 used inside the location expressions.
1543   // Maintain order by iterating backwards and inserting to the front of CU
1544   // child list.
1545   for (auto &Btr : reverse(ExprRefedBaseTypes)) {
1546     DIE &Die = getUnitDie().addChildFront(
1547       DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type));
1548     SmallString<32> Str;
1549     addString(Die, dwarf::DW_AT_name,
1550               Twine(dwarf::AttributeEncodingString(Btr.Encoding) +
1551                     "_" + Twine(Btr.BitSize)).toStringRef(Str));
1552     addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding);
1553     addUInt(Die, dwarf::DW_AT_byte_size, None, Btr.BitSize / 8);
1554 
1555     Btr.Die = &Die;
1556   }
1557 }
1558