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