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