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