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