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