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