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/TargetFrameLowering.h"
25 #include "llvm/CodeGen/TargetRegisterInfo.h"
26 #include "llvm/CodeGen/TargetSubtargetInfo.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/GlobalVariable.h"
30 #include "llvm/MC/MCSection.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/MC/MCSymbolWasm.h"
34 #include "llvm/MC/MachineLocation.h"
35 #include "llvm/Target/TargetLoweringObjectFile.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include <iterator>
39 #include <string>
40 #include <utility>
41 
42 using namespace llvm;
43 
44 static dwarf::Tag GetCompileUnitType(UnitKind Kind, DwarfDebug *DW) {
45 
46   //  According to DWARF Debugging Information Format Version 5,
47   //  3.1.2 Skeleton Compilation Unit Entries:
48   //  "When generating a split DWARF object file (see Section 7.3.2
49   //  on page 187), the compilation unit in the .debug_info section
50   //  is a "skeleton" compilation unit with the tag DW_TAG_skeleton_unit"
51   if (DW->getDwarfVersion() >= 5 && Kind == UnitKind::Skeleton)
52     return dwarf::DW_TAG_skeleton_unit;
53 
54   return dwarf::DW_TAG_compile_unit;
55 }
56 
57 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
58                                    AsmPrinter *A, DwarfDebug *DW,
59                                    DwarfFile *DWU, UnitKind Kind)
60     : DwarfUnit(GetCompileUnitType(Kind, DW), Node, A, DW, DWU), UniqueID(UID) {
61   insertDIE(Node, &getUnitDie());
62   MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
63 }
64 
65 /// addLabelAddress - Add a dwarf label attribute data and value using
66 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
67 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
68                                        const MCSymbol *Label) {
69   if ((Skeleton || !DD->useSplitDwarf()) && Label)
70     DD->addArangeLabel(SymbolCU(this, Label));
71 
72   // Don't use the address pool in non-fission or in the skeleton unit itself.
73   if ((!DD->useSplitDwarf() || !Skeleton) && DD->getDwarfVersion() < 5)
74     return addLocalLabelAddress(Die, Attribute, Label);
75 
76   bool UseAddrOffsetFormOrExpressions =
77       DD->useAddrOffsetForm() || DD->useAddrOffsetExpressions();
78 
79   const MCSymbol *Base = nullptr;
80   if (Label->isInSection() && UseAddrOffsetFormOrExpressions)
81     Base = DD->getSectionLabel(&Label->getSection());
82 
83   if (!Base || Base == Label) {
84     unsigned idx = DD->getAddressPool().getIndex(Label);
85     addAttribute(Die, Attribute,
86                  DD->getDwarfVersion() >= 5 ? dwarf::DW_FORM_addrx
87                                             : dwarf::DW_FORM_GNU_addr_index,
88                  DIEInteger(idx));
89     return;
90   }
91 
92   // Could be extended to work with DWARFv4 Split DWARF if that's important for
93   // someone. In that case DW_FORM_data would be used.
94   assert(DD->getDwarfVersion() >= 5 &&
95          "Addr+offset expressions are only valuable when using debug_addr (to "
96          "reduce relocations) available in DWARFv5 or higher");
97   if (DD->useAddrOffsetExpressions()) {
98     auto *Loc = new (DIEValueAllocator) DIEBlock();
99     addPoolOpAddress(*Loc, Label);
100     addBlock(Die, Attribute, dwarf::DW_FORM_exprloc, Loc);
101   } else
102     addAttribute(Die, Attribute, dwarf::DW_FORM_LLVM_addrx_offset,
103                  new (DIEValueAllocator) DIEAddrOffset(
104                      DD->getAddressPool().getIndex(Base), Label, Base));
105 }
106 
107 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
108                                             dwarf::Attribute Attribute,
109                                             const MCSymbol *Label) {
110   if (Label)
111     addAttribute(Die, Attribute, dwarf::DW_FORM_addr, DIELabel(Label));
112   else
113     addAttribute(Die, Attribute, dwarf::DW_FORM_addr, DIEInteger(0));
114 }
115 
116 unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
117   // If we print assembly, we can't separate .file entries according to
118   // compile units. Thus all files will belong to the default compile unit.
119 
120   // FIXME: add a better feature test than hasRawTextSupport. Even better,
121   // extend .file to support this.
122   unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
123   if (!File)
124     return Asm->OutStreamer->emitDwarfFileDirective(0, "", "", None, None,
125                                                     CUID);
126 
127   if (LastFile != File) {
128     LastFile = File;
129     LastFileID = Asm->OutStreamer->emitDwarfFileDirective(
130         0, File->getDirectory(), File->getFilename(), DD->getMD5AsBytes(File),
131         File->getSource(), CUID);
132   }
133   return LastFileID;
134 }
135 
136 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
137     const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
138   // Check for pre-existence.
139   if (DIE *Die = getDIE(GV))
140     return Die;
141 
142   assert(GV);
143 
144   auto *GVContext = GV->getScope();
145   const DIType *GTy = GV->getType();
146 
147   auto *CB = GVContext ? dyn_cast<DICommonBlock>(GVContext) : nullptr;
148   DIE *ContextDIE = CB ? getOrCreateCommonBlock(CB, GlobalExprs)
149     : getOrCreateContextDIE(GVContext);
150 
151   // Add to map.
152   DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
153   DIScope *DeclContext;
154   if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
155     DeclContext = SDMDecl->getScope();
156     assert(SDMDecl->isStaticMember() && "Expected static member decl");
157     assert(GV->isDefinition());
158     // We need the declaration DIE that is in the static member's class.
159     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
160     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
161     // If the global variable's type is different from the one in the class
162     // member type, assume that it's more specific and also emit it.
163     if (GTy != SDMDecl->getBaseType())
164       addType(*VariableDIE, GTy);
165   } else {
166     DeclContext = GV->getScope();
167     // Add name and type.
168     StringRef DisplayName = GV->getDisplayName();
169     if (!DisplayName.empty())
170       addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
171     if (GTy)
172       addType(*VariableDIE, GTy);
173 
174     // Add scoping info.
175     if (!GV->isLocalToUnit())
176       addFlag(*VariableDIE, dwarf::DW_AT_external);
177 
178     // Add line number info.
179     addSourceLine(*VariableDIE, GV);
180   }
181 
182   if (!GV->isDefinition())
183     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
184   else
185     addGlobalName(GV->getName(), *VariableDIE, DeclContext);
186 
187   addAnnotation(*VariableDIE, GV->getAnnotations());
188 
189   if (uint32_t AlignInBytes = GV->getAlignInBytes())
190     addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
191             AlignInBytes);
192 
193   if (MDTuple *TP = GV->getTemplateParams())
194     addTemplateParams(*VariableDIE, DINodeArray(TP));
195 
196   // Add location.
197   addLocationAttribute(VariableDIE, GV, GlobalExprs);
198 
199   return VariableDIE;
200 }
201 
202 void DwarfCompileUnit::addLocationAttribute(
203     DIE *VariableDIE, const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
204   bool addToAccelTable = false;
205   DIELoc *Loc = nullptr;
206   Optional<unsigned> NVPTXAddressSpace;
207   std::unique_ptr<DIEDwarfExpression> DwarfExpr;
208   for (const auto &GE : GlobalExprs) {
209     const GlobalVariable *Global = GE.Var;
210     const DIExpression *Expr = GE.Expr;
211 
212     // For compatibility with DWARF 3 and earlier,
213     // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) or
214     // DW_AT_location(DW_OP_consts, X, DW_OP_stack_value) becomes
215     // DW_AT_const_value(X).
216     if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
217       addToAccelTable = true;
218       addConstantValue(
219           *VariableDIE,
220           DIExpression::SignedOrUnsignedConstant::UnsignedConstant ==
221               *Expr->isConstant(),
222           Expr->getElement(1));
223       break;
224     }
225 
226     // We cannot describe the location of dllimport'd variables: the
227     // computation of their address requires loads from the IAT.
228     if (Global && Global->hasDLLImportStorageClass())
229       continue;
230 
231     // Nothing to describe without address or constant.
232     if (!Global && (!Expr || !Expr->isConstant()))
233       continue;
234 
235     if (Global && Global->isThreadLocal() &&
236         !Asm->getObjFileLowering().supportDebugThreadLocalLocation())
237       continue;
238 
239     if (!Loc) {
240       addToAccelTable = true;
241       Loc = new (DIEValueAllocator) DIELoc;
242       DwarfExpr = std::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
243     }
244 
245     if (Expr) {
246       // According to
247       // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
248       // cuda-gdb requires DW_AT_address_class for all variables to be able to
249       // correctly interpret address space of the variable address.
250       // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
251       // sequence for the NVPTX + gdb target.
252       unsigned LocalNVPTXAddressSpace;
253       if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
254         const DIExpression *NewExpr =
255             DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
256         if (NewExpr != Expr) {
257           Expr = NewExpr;
258           NVPTXAddressSpace = LocalNVPTXAddressSpace;
259         }
260       }
261       DwarfExpr->addFragmentOffset(Expr);
262     }
263 
264     if (Global) {
265       const MCSymbol *Sym = Asm->getSymbol(Global);
266       // 16-bit platforms like MSP430 and AVR take this path, so sink this
267       // assert to platforms that use it.
268       auto GetPointerSizedFormAndOp = [this]() {
269         unsigned PointerSize = Asm->getDataLayout().getPointerSize();
270         assert((PointerSize == 4 || PointerSize == 8) &&
271                "Add support for other sizes if necessary");
272         struct FormAndOp {
273           dwarf::Form Form;
274           dwarf::LocationAtom Op;
275         };
276         return PointerSize == 4
277                    ? FormAndOp{dwarf::DW_FORM_data4, dwarf::DW_OP_const4u}
278                    : FormAndOp{dwarf::DW_FORM_data8, dwarf::DW_OP_const8u};
279       };
280       if (Global->isThreadLocal()) {
281         if (Asm->TM.useEmulatedTLS()) {
282           // TODO: add debug info for emulated thread local mode.
283         } else {
284           // FIXME: Make this work with -gsplit-dwarf.
285           // Based on GCC's support for TLS:
286           if (!DD->useSplitDwarf()) {
287             auto FormAndOp = GetPointerSizedFormAndOp();
288             // 1) Start with a constNu of the appropriate pointer size
289             addUInt(*Loc, dwarf::DW_FORM_data1, FormAndOp.Op);
290             // 2) containing the (relocated) offset of the TLS variable
291             //    within the module's TLS block.
292             addExpr(*Loc, FormAndOp.Form,
293                     Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
294           } else {
295             addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
296             addUInt(*Loc, dwarf::DW_FORM_udata,
297                     DD->getAddressPool().getIndex(Sym, /* TLS */ true));
298           }
299           // 3) followed by an OP to make the debugger do a TLS lookup.
300           addUInt(*Loc, dwarf::DW_FORM_data1,
301                   DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
302                                         : dwarf::DW_OP_form_tls_address);
303         }
304       } else if (Asm->TM.getRelocationModel() == Reloc::RWPI ||
305                  Asm->TM.getRelocationModel() == Reloc::ROPI_RWPI) {
306         auto FormAndOp = GetPointerSizedFormAndOp();
307         // Constant
308         addUInt(*Loc, dwarf::DW_FORM_data1, FormAndOp.Op);
309         // Relocation offset
310         addExpr(*Loc, FormAndOp.Form,
311                 Asm->getObjFileLowering().getIndirectSymViaRWPI(Sym));
312         // Base register
313         Register BaseReg = Asm->getObjFileLowering().getStaticBase();
314         BaseReg = Asm->TM.getMCRegisterInfo()->getDwarfRegNum(BaseReg, false);
315         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + BaseReg);
316         // Offset from base register
317         addSInt(*Loc, dwarf::DW_FORM_sdata, 0);
318         // Operation
319         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
320       } else {
321         DD->addArangeLabel(SymbolCU(this, Sym));
322         addOpAddress(*Loc, Sym);
323       }
324     }
325     // Global variables attached to symbols are memory locations.
326     // It would be better if this were unconditional, but malformed input that
327     // mixes non-fragments and fragments for the same variable is too expensive
328     // to detect in the verifier.
329     if (DwarfExpr->isUnknownLocation())
330       DwarfExpr->setMemoryLocationKind();
331     DwarfExpr->addExpression(Expr);
332   }
333   if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
334     // According to
335     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
336     // cuda-gdb requires DW_AT_address_class for all variables to be able to
337     // correctly interpret address space of the variable address.
338     const unsigned NVPTX_ADDR_global_space = 5;
339     addUInt(*VariableDIE, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
340             NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_global_space);
341   }
342   if (Loc)
343     addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
344 
345   if (DD->useAllLinkageNames())
346     addLinkageName(*VariableDIE, GV->getLinkageName());
347 
348   if (addToAccelTable) {
349     DD->addAccelName(*CUNode, GV->getName(), *VariableDIE);
350 
351     // If the linkage name is different than the name, go ahead and output
352     // that as well into the name table.
353     if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
354         DD->useAllLinkageNames())
355       DD->addAccelName(*CUNode, GV->getLinkageName(), *VariableDIE);
356   }
357 }
358 
359 DIE *DwarfCompileUnit::getOrCreateCommonBlock(
360     const DICommonBlock *CB, ArrayRef<GlobalExpr> GlobalExprs) {
361   // Check for pre-existence.
362   if (DIE *NDie = getDIE(CB))
363     return NDie;
364   DIE *ContextDIE = getOrCreateContextDIE(CB->getScope());
365   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_common_block, *ContextDIE, CB);
366   StringRef Name = CB->getName().empty() ? "_BLNK_" : CB->getName();
367   addString(NDie, dwarf::DW_AT_name, Name);
368   addGlobalName(Name, NDie, CB->getScope());
369   if (CB->getFile())
370     addSourceLine(NDie, CB->getLineNo(), CB->getFile());
371   if (DIGlobalVariable *V = CB->getDecl())
372     getCU().addLocationAttribute(&NDie, V, GlobalExprs);
373   return &NDie;
374 }
375 
376 void DwarfCompileUnit::addRange(RangeSpan Range) {
377   DD->insertSectionLabel(Range.Begin);
378 
379   auto *PrevCU = DD->getPrevCU();
380   bool SameAsPrevCU = this == PrevCU;
381   DD->setPrevCU(this);
382   // If we have no current ranges just add the range and return, otherwise,
383   // check the current section and CU against the previous section and CU we
384   // emitted into and the subprogram was contained within. If these are the
385   // same then extend our current range, otherwise add this as a new range.
386   if (CURanges.empty() || !SameAsPrevCU ||
387       (&CURanges.back().End->getSection() !=
388        &Range.End->getSection())) {
389     // Before a new range is added, always terminate the prior line table.
390     if (PrevCU)
391       DD->terminateLineTable(PrevCU);
392     CURanges.push_back(Range);
393     return;
394   }
395 
396   CURanges.back().End = Range.End;
397 }
398 
399 void DwarfCompileUnit::initStmtList() {
400   if (CUNode->isDebugDirectivesOnly())
401     return;
402 
403   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
404   if (DD->useSectionsAsReferences()) {
405     LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
406   } else {
407     LineTableStartSym =
408         Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
409   }
410 
411   // DW_AT_stmt_list is a offset of line number information for this
412   // compile unit in debug_line section. For split dwarf this is
413   // left in the skeleton CU and so not included.
414   // The line table entries are not always emitted in assembly, so it
415   // is not okay to use line_table_start here.
416       addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
417                       TLOF.getDwarfLineSection()->getBeginSymbol());
418 }
419 
420 void DwarfCompileUnit::applyStmtList(DIE &D) {
421   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
422   addSectionLabel(D, dwarf::DW_AT_stmt_list, LineTableStartSym,
423                   TLOF.getDwarfLineSection()->getBeginSymbol());
424 }
425 
426 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
427                                        const MCSymbol *End) {
428   assert(Begin && "Begin label should not be null!");
429   assert(End && "End label should not be null!");
430   assert(Begin->isDefined() && "Invalid starting label");
431   assert(End->isDefined() && "Invalid end label");
432 
433   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
434   if (DD->getDwarfVersion() < 4)
435     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
436   else
437     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
438 }
439 
440 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
441 // and DW_AT_high_pc attributes. If there are global variables in this
442 // scope then create and insert DIEs for these variables.
443 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
444   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
445 
446   SmallVector<RangeSpan, 2> BB_List;
447   // If basic block sections are on, ranges for each basic block section has
448   // to be emitted separately.
449   for (const auto &R : Asm->MBBSectionRanges)
450     BB_List.push_back({R.second.BeginLabel, R.second.EndLabel});
451 
452   attachRangesOrLowHighPC(*SPDie, BB_List);
453 
454   if (DD->useAppleExtensionAttributes() &&
455       !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
456           *DD->getCurrentFunction()))
457     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
458 
459   // Only include DW_AT_frame_base in full debug info
460   if (!includeMinimalInlineScopes()) {
461     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
462     TargetFrameLowering::DwarfFrameBase FrameBase =
463         TFI->getDwarfFrameBase(*Asm->MF);
464     switch (FrameBase.Kind) {
465     case TargetFrameLowering::DwarfFrameBase::Register: {
466       if (Register::isPhysicalRegister(FrameBase.Location.Reg)) {
467         MachineLocation Location(FrameBase.Location.Reg);
468         addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
469       }
470       break;
471     }
472     case TargetFrameLowering::DwarfFrameBase::CFA: {
473       DIELoc *Loc = new (DIEValueAllocator) DIELoc;
474       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa);
475       addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
476       break;
477     }
478     case TargetFrameLowering::DwarfFrameBase::WasmFrameBase: {
479       // FIXME: duplicated from Target/WebAssembly/WebAssembly.h
480       // don't want to depend on target specific headers in this code?
481       const unsigned TI_GLOBAL_RELOC = 3;
482       if (FrameBase.Location.WasmLoc.Kind == TI_GLOBAL_RELOC) {
483         // These need to be relocatable.
484         assert(FrameBase.Location.WasmLoc.Index == 0);  // Only SP so far.
485         auto SPSym = cast<MCSymbolWasm>(
486           Asm->GetExternalSymbolSymbol("__stack_pointer"));
487         // FIXME: this repeats what WebAssemblyMCInstLower::
488         // GetExternalSymbolSymbol does, since if there's no code that
489         // refers to this symbol, we have to set it here.
490         SPSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
491         SPSym->setGlobalType(wasm::WasmGlobalType{
492             uint8_t(Asm->getSubtargetInfo().getTargetTriple().getArch() ==
493                             Triple::wasm64
494                         ? wasm::WASM_TYPE_I64
495                         : wasm::WASM_TYPE_I32),
496             true});
497         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
498         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_WASM_location);
499         addSInt(*Loc, dwarf::DW_FORM_sdata, TI_GLOBAL_RELOC);
500         if (!isDwoUnit()) {
501           addLabel(*Loc, dwarf::DW_FORM_data4, SPSym);
502         } else {
503           // FIXME: when writing dwo, we need to avoid relocations. Probably
504           // the "right" solution is to treat globals the way func and data
505           // symbols are (with entries in .debug_addr).
506           // For now, since we only ever use index 0, this should work as-is.
507           addUInt(*Loc, dwarf::DW_FORM_data4, FrameBase.Location.WasmLoc.Index);
508         }
509         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
510         addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
511       } else {
512         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
513         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
514         DIExpressionCursor Cursor({});
515         DwarfExpr.addWasmLocation(FrameBase.Location.WasmLoc.Kind,
516             FrameBase.Location.WasmLoc.Index);
517         DwarfExpr.addExpression(std::move(Cursor));
518         addBlock(*SPDie, dwarf::DW_AT_frame_base, DwarfExpr.finalize());
519       }
520       break;
521     }
522     }
523   }
524 
525   // Add name to the name table, we do this here because we're guaranteed
526   // to have concrete versions of our DW_TAG_subprogram nodes.
527   DD->addSubprogramNames(*CUNode, SP, *SPDie);
528 
529   return *SPDie;
530 }
531 
532 // Construct a DIE for this scope.
533 void DwarfCompileUnit::constructScopeDIE(LexicalScope *Scope,
534                                          DIE &ParentScopeDIE) {
535   if (!Scope || !Scope->getScopeNode())
536     return;
537 
538   auto *DS = Scope->getScopeNode();
539 
540   assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
541          "Only handle inlined subprograms here, use "
542          "constructSubprogramScopeDIE for non-inlined "
543          "subprograms");
544 
545   // Emit inlined subprograms.
546   if (Scope->getParent() && isa<DISubprogram>(DS)) {
547     DIE *ScopeDIE = constructInlinedScopeDIE(Scope);
548     if (!ScopeDIE)
549       return;
550 
551     ParentScopeDIE.addChild(ScopeDIE);
552     createAndAddScopeChildren(Scope, *ScopeDIE);
553     return;
554   }
555 
556   // Early exit when we know the scope DIE is going to be null.
557   if (DD->isLexicalScopeDIENull(Scope))
558     return;
559 
560   // Emit lexical blocks.
561   DIE *ScopeDIE = constructLexicalScopeDIE(Scope);
562   assert(ScopeDIE && "Scope DIE should not be null.");
563 
564   ParentScopeDIE.addChild(ScopeDIE);
565   createAndAddScopeChildren(Scope, *ScopeDIE);
566 }
567 
568 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
569                                          SmallVector<RangeSpan, 2> Range) {
570 
571   HasRangeLists = true;
572 
573   // Add the range list to the set of ranges to be emitted.
574   auto IndexAndList =
575       (DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU)
576           ->addRange(*(Skeleton ? Skeleton : this), std::move(Range));
577 
578   uint32_t Index = IndexAndList.first;
579   auto &List = *IndexAndList.second;
580 
581   // Under fission, ranges are specified by constant offsets relative to the
582   // CU's DW_AT_GNU_ranges_base.
583   // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
584   // fission until we support the forms using the .debug_addr section
585   // (DW_RLE_startx_endx etc.).
586   if (DD->getDwarfVersion() >= 5)
587     addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_rnglistx, Index);
588   else {
589     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
590     const MCSymbol *RangeSectionSym =
591         TLOF.getDwarfRangesSection()->getBeginSymbol();
592     if (isDwoUnit())
593       addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
594                       RangeSectionSym);
595     else
596       addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
597                       RangeSectionSym);
598   }
599 }
600 
601 void DwarfCompileUnit::attachRangesOrLowHighPC(
602     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
603   assert(!Ranges.empty());
604   if (!DD->useRangesSection() ||
605       (Ranges.size() == 1 &&
606        (!DD->alwaysUseRanges() ||
607         DD->getSectionLabel(&Ranges.front().Begin->getSection()) ==
608             Ranges.front().Begin))) {
609     const RangeSpan &Front = Ranges.front();
610     const RangeSpan &Back = Ranges.back();
611     attachLowHighPC(Die, Front.Begin, Back.End);
612   } else
613     addScopeRangeList(Die, std::move(Ranges));
614 }
615 
616 void DwarfCompileUnit::attachRangesOrLowHighPC(
617     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
618   SmallVector<RangeSpan, 2> List;
619   List.reserve(Ranges.size());
620   for (const InsnRange &R : Ranges) {
621     auto *BeginLabel = DD->getLabelBeforeInsn(R.first);
622     auto *EndLabel = DD->getLabelAfterInsn(R.second);
623 
624     const auto *BeginMBB = R.first->getParent();
625     const auto *EndMBB = R.second->getParent();
626 
627     const auto *MBB = BeginMBB;
628     // Basic block sections allows basic block subsets to be placed in unique
629     // sections. For each section, the begin and end label must be added to the
630     // list. If there is more than one range, debug ranges must be used.
631     // Otherwise, low/high PC can be used.
632     // FIXME: Debug Info Emission depends on block order and this assumes that
633     // the order of blocks will be frozen beyond this point.
634     do {
635       if (MBB->sameSection(EndMBB) || MBB->isEndSection()) {
636         auto MBBSectionRange = Asm->MBBSectionRanges[MBB->getSectionIDNum()];
637         List.push_back(
638             {MBB->sameSection(BeginMBB) ? BeginLabel
639                                         : MBBSectionRange.BeginLabel,
640              MBB->sameSection(EndMBB) ? EndLabel : MBBSectionRange.EndLabel});
641       }
642       if (MBB->sameSection(EndMBB))
643         break;
644       MBB = MBB->getNextNode();
645     } while (true);
646   }
647   attachRangesOrLowHighPC(Die, std::move(List));
648 }
649 
650 // This scope represents inlined body of a function. Construct DIE to
651 // represent this concrete inlined copy of the function.
652 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
653   assert(Scope->getScopeNode());
654   auto *DS = Scope->getScopeNode();
655   auto *InlinedSP = getDISubprogram(DS);
656   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
657   // was inlined from another compile unit.
658   DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
659   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
660 
661   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
662   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
663 
664   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
665 
666   // Add the call site information to the DIE.
667   const DILocation *IA = Scope->getInlinedAt();
668   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
669           getOrCreateSourceID(IA->getFile()));
670   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
671   if (IA->getColumn())
672     addUInt(*ScopeDIE, dwarf::DW_AT_call_column, None, IA->getColumn());
673   if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
674     addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
675             IA->getDiscriminator());
676 
677   // Add name to the name table, we do this here because we're guaranteed
678   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
679   DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
680 
681   return ScopeDIE;
682 }
683 
684 // Construct new DW_TAG_lexical_block for this scope and attach
685 // DW_AT_low_pc/DW_AT_high_pc labels.
686 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
687   if (DD->isLexicalScopeDIENull(Scope))
688     return nullptr;
689 
690   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
691   if (Scope->isAbstractScope())
692     return ScopeDIE;
693 
694   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
695 
696   return ScopeDIE;
697 }
698 
699 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
700 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
701   auto D = constructVariableDIEImpl(DV, Abstract);
702   DV.setDIE(*D);
703   return D;
704 }
705 
706 DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
707                                          const LexicalScope &Scope) {
708   auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
709   insertDIE(DL.getLabel(), LabelDie);
710   DL.setDIE(*LabelDie);
711 
712   if (Scope.isAbstractScope())
713     applyLabelAttributes(DL, *LabelDie);
714 
715   return LabelDie;
716 }
717 
718 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
719                                                 bool Abstract) {
720   // Define variable debug information entry.
721   auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
722   insertDIE(DV.getVariable(), VariableDie);
723 
724   if (Abstract) {
725     applyVariableAttributes(DV, *VariableDie);
726     return VariableDie;
727   }
728 
729   // Add variable address.
730 
731   unsigned Index = DV.getDebugLocListIndex();
732   if (Index != ~0U) {
733     addLocationList(*VariableDie, dwarf::DW_AT_location, Index);
734     auto TagOffset = DV.getDebugLocListTagOffset();
735     if (TagOffset)
736       addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
737               *TagOffset);
738     return VariableDie;
739   }
740 
741   // Check if variable has a single location description.
742   if (auto *DVal = DV.getValueLoc()) {
743     if (!DVal->isVariadic()) {
744       const DbgValueLocEntry *Entry = DVal->getLocEntries().begin();
745       if (Entry->isLocation()) {
746         addVariableAddress(DV, *VariableDie, Entry->getLoc());
747       } else if (Entry->isInt()) {
748         auto *Expr = DV.getSingleExpression();
749         if (Expr && Expr->getNumElements()) {
750           DIELoc *Loc = new (DIEValueAllocator) DIELoc;
751           DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
752           // If there is an expression, emit raw unsigned bytes.
753           DwarfExpr.addFragmentOffset(Expr);
754           DwarfExpr.addUnsignedConstant(Entry->getInt());
755           DwarfExpr.addExpression(Expr);
756           addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
757           if (DwarfExpr.TagOffset)
758             addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset,
759                     dwarf::DW_FORM_data1, *DwarfExpr.TagOffset);
760         } else
761           addConstantValue(*VariableDie, Entry->getInt(), DV.getType());
762       } else if (Entry->isConstantFP()) {
763         addConstantFPValue(*VariableDie, Entry->getConstantFP());
764       } else if (Entry->isConstantInt()) {
765         addConstantValue(*VariableDie, Entry->getConstantInt(), DV.getType());
766       } else if (Entry->isTargetIndexLocation()) {
767         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
768         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
769         const DIBasicType *BT = dyn_cast<DIBasicType>(
770             static_cast<const Metadata *>(DV.getVariable()->getType()));
771         DwarfDebug::emitDebugLocValue(*Asm, BT, *DVal, DwarfExpr);
772         addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
773       }
774       return VariableDie;
775     }
776     // If any of the location entries are registers with the value 0, then the
777     // location is undefined.
778     if (any_of(DVal->getLocEntries(), [](const DbgValueLocEntry &Entry) {
779           return Entry.isLocation() && !Entry.getLoc().getReg();
780         }))
781       return VariableDie;
782     const DIExpression *Expr = DV.getSingleExpression();
783     assert(Expr && "Variadic Debug Value must have an Expression.");
784     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
785     DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
786     DwarfExpr.addFragmentOffset(Expr);
787     DIExpressionCursor Cursor(Expr);
788     const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
789 
790     auto AddEntry = [&](const DbgValueLocEntry &Entry,
791                         DIExpressionCursor &Cursor) {
792       if (Entry.isLocation()) {
793         if (!DwarfExpr.addMachineRegExpression(TRI, Cursor,
794                                                Entry.getLoc().getReg()))
795           return false;
796       } else if (Entry.isInt()) {
797         // If there is an expression, emit raw unsigned bytes.
798         DwarfExpr.addUnsignedConstant(Entry.getInt());
799       } else if (Entry.isConstantFP()) {
800         // DwarfExpression does not support arguments wider than 64 bits
801         // (see PR52584).
802         // TODO: Consider chunking expressions containing overly wide
803         // arguments into separate pointer-sized fragment expressions.
804         APInt RawBytes = Entry.getConstantFP()->getValueAPF().bitcastToAPInt();
805         if (RawBytes.getBitWidth() > 64)
806           return false;
807         DwarfExpr.addUnsignedConstant(RawBytes.getZExtValue());
808       } else if (Entry.isConstantInt()) {
809         APInt RawBytes = Entry.getConstantInt()->getValue();
810         if (RawBytes.getBitWidth() > 64)
811           return false;
812         DwarfExpr.addUnsignedConstant(RawBytes.getZExtValue());
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     if (!DwarfExpr.addExpression(
826             std::move(Cursor),
827             [&](unsigned Idx, DIExpressionCursor &Cursor) -> bool {
828               return AddEntry(DVal->getLocEntries()[Idx], Cursor);
829             }))
830       return VariableDie;
831 
832     // Now attach the location information to the DIE.
833     addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
834     if (DwarfExpr.TagOffset)
835       addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
836               *DwarfExpr.TagOffset);
837 
838     return VariableDie;
839   }
840 
841   // .. else use frame index.
842   if (!DV.hasFrameIndexExprs())
843     return VariableDie;
844 
845   Optional<unsigned> NVPTXAddressSpace;
846   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
847   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
848   for (auto &Fragment : DV.getFrameIndexExprs()) {
849     Register FrameReg;
850     const DIExpression *Expr = Fragment.Expr;
851     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
852     StackOffset Offset =
853         TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
854     DwarfExpr.addFragmentOffset(Expr);
855 
856     auto *TRI = Asm->MF->getSubtarget().getRegisterInfo();
857     SmallVector<uint64_t, 8> Ops;
858     TRI->getOffsetOpcodes(Offset, Ops);
859 
860     // According to
861     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
862     // cuda-gdb requires DW_AT_address_class for all variables to be able to
863     // correctly interpret address space of the variable address.
864     // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
865     // sequence for the NVPTX + gdb target.
866     unsigned LocalNVPTXAddressSpace;
867     if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
868       const DIExpression *NewExpr =
869           DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
870       if (NewExpr != Expr) {
871         Expr = NewExpr;
872         NVPTXAddressSpace = LocalNVPTXAddressSpace;
873       }
874     }
875     if (Expr)
876       Ops.append(Expr->elements_begin(), Expr->elements_end());
877     DIExpressionCursor Cursor(Ops);
878     DwarfExpr.setMemoryLocationKind();
879     if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
880       addOpAddress(*Loc, FrameSymbol);
881     else
882       DwarfExpr.addMachineRegExpression(
883           *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
884     DwarfExpr.addExpression(std::move(Cursor));
885   }
886   if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
887     // According to
888     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
889     // cuda-gdb requires DW_AT_address_class for all variables to be able to
890     // correctly interpret address space of the variable address.
891     const unsigned NVPTX_ADDR_local_space = 6;
892     addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
893             NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space);
894   }
895   addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
896   if (DwarfExpr.TagOffset)
897     addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
898             *DwarfExpr.TagOffset);
899 
900   return VariableDie;
901 }
902 
903 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
904                                             const LexicalScope &Scope,
905                                             DIE *&ObjectPointer) {
906   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
907   if (DV.isObjectPointer())
908     ObjectPointer = Var;
909   return Var;
910 }
911 
912 /// Return all DIVariables that appear in count: expressions.
913 static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
914   SmallVector<const DIVariable *, 2> Result;
915   auto *Array = dyn_cast<DICompositeType>(Var->getType());
916   if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
917     return Result;
918   if (auto *DLVar = Array->getDataLocation())
919     Result.push_back(DLVar);
920   if (auto *AsVar = Array->getAssociated())
921     Result.push_back(AsVar);
922   if (auto *AlVar = Array->getAllocated())
923     Result.push_back(AlVar);
924   for (auto *El : Array->getElements()) {
925     if (auto *Subrange = dyn_cast<DISubrange>(El)) {
926       if (auto Count = Subrange->getCount())
927         if (auto *Dependency = Count.dyn_cast<DIVariable *>())
928           Result.push_back(Dependency);
929       if (auto LB = Subrange->getLowerBound())
930         if (auto *Dependency = LB.dyn_cast<DIVariable *>())
931           Result.push_back(Dependency);
932       if (auto UB = Subrange->getUpperBound())
933         if (auto *Dependency = UB.dyn_cast<DIVariable *>())
934           Result.push_back(Dependency);
935       if (auto ST = Subrange->getStride())
936         if (auto *Dependency = ST.dyn_cast<DIVariable *>())
937           Result.push_back(Dependency);
938     } else if (auto *GenericSubrange = dyn_cast<DIGenericSubrange>(El)) {
939       if (auto Count = GenericSubrange->getCount())
940         if (auto *Dependency = Count.dyn_cast<DIVariable *>())
941           Result.push_back(Dependency);
942       if (auto LB = GenericSubrange->getLowerBound())
943         if (auto *Dependency = LB.dyn_cast<DIVariable *>())
944           Result.push_back(Dependency);
945       if (auto UB = GenericSubrange->getUpperBound())
946         if (auto *Dependency = UB.dyn_cast<DIVariable *>())
947           Result.push_back(Dependency);
948       if (auto ST = GenericSubrange->getStride())
949         if (auto *Dependency = ST.dyn_cast<DIVariable *>())
950           Result.push_back(Dependency);
951     }
952   }
953   return Result;
954 }
955 
956 /// Sort local variables so that variables appearing inside of helper
957 /// expressions come first.
958 static SmallVector<DbgVariable *, 8>
959 sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
960   SmallVector<DbgVariable *, 8> Result;
961   SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
962   // Map back from a DIVariable to its containing DbgVariable.
963   SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
964   // Set of DbgVariables in Result.
965   SmallDenseSet<DbgVariable *, 8> Visited;
966   // For cycle detection.
967   SmallDenseSet<DbgVariable *, 8> Visiting;
968 
969   // Initialize the worklist and the DIVariable lookup table.
970   for (auto Var : reverse(Input)) {
971     DbgVar.insert({Var->getVariable(), Var});
972     WorkList.push_back({Var, 0});
973   }
974 
975   // Perform a stable topological sort by doing a DFS.
976   while (!WorkList.empty()) {
977     auto Item = WorkList.back();
978     DbgVariable *Var = Item.getPointer();
979     bool visitedAllDependencies = Item.getInt();
980     WorkList.pop_back();
981 
982     assert(Var);
983 
984     // Already handled.
985     if (Visited.count(Var))
986       continue;
987 
988     // Add to Result if all dependencies are visited.
989     if (visitedAllDependencies) {
990       Visited.insert(Var);
991       Result.push_back(Var);
992       continue;
993     }
994 
995     // Detect cycles.
996     auto Res = Visiting.insert(Var);
997     if (!Res.second) {
998       assert(false && "dependency cycle in local variables");
999       return Result;
1000     }
1001 
1002     // Push dependencies and this node onto the worklist, so that this node is
1003     // visited again after all of its dependencies are handled.
1004     WorkList.push_back({Var, 1});
1005     for (auto *Dependency : dependencies(Var)) {
1006       // Don't add dependency if it is in a different lexical scope or a global.
1007       if (const auto *Dep = dyn_cast<const DILocalVariable>(Dependency))
1008         if (DbgVariable *Var = DbgVar.lookup(Dep))
1009           WorkList.push_back({Var, 0});
1010     }
1011   }
1012   return Result;
1013 }
1014 
1015 DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub,
1016                                                    LexicalScope *Scope) {
1017   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
1018 
1019   if (Scope) {
1020     assert(!Scope->getInlinedAt());
1021     assert(!Scope->isAbstractScope());
1022     // Collect lexical scope children first.
1023     // ObjectPointer might be a local (non-argument) local variable if it's a
1024     // block's synthetic this pointer.
1025     if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
1026       addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
1027   }
1028 
1029   // If this is a variadic function, add an unspecified parameter.
1030   DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
1031 
1032   // If we have a single element of null, it is a function that returns void.
1033   // If we have more than one elements and the last one is null, it is a
1034   // variadic function.
1035   if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
1036       !includeMinimalInlineScopes())
1037     ScopeDIE.addChild(
1038         DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
1039 
1040   return ScopeDIE;
1041 }
1042 
1043 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
1044                                                  DIE &ScopeDIE) {
1045   DIE *ObjectPointer = nullptr;
1046 
1047   // Emit function arguments (order is significant).
1048   auto Vars = DU->getScopeVariables().lookup(Scope);
1049   for (auto &DV : Vars.Args)
1050     ScopeDIE.addChild(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
1051 
1052   // Emit local variables.
1053   auto Locals = sortLocalVars(Vars.Locals);
1054   for (DbgVariable *DV : Locals)
1055     ScopeDIE.addChild(constructVariableDIE(*DV, *Scope, ObjectPointer));
1056 
1057   // Emit imported entities (skipped in gmlt-like data).
1058   if (!includeMinimalInlineScopes()) {
1059     for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
1060       ScopeDIE.addChild(constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
1061   }
1062 
1063   // Emit labels.
1064   for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
1065     ScopeDIE.addChild(constructLabelDIE(*DL, *Scope));
1066 
1067   // Emit inner lexical scopes.
1068   auto needToEmitLexicalScope = [this](LexicalScope *LS) {
1069     if (isa<DISubprogram>(LS->getScopeNode()))
1070       return true;
1071     auto Vars = DU->getScopeVariables().lookup(LS);
1072     if (!Vars.Args.empty() || !Vars.Locals.empty())
1073       return true;
1074     if (!includeMinimalInlineScopes() &&
1075         !ImportedEntities[LS->getScopeNode()].empty())
1076       return true;
1077     return false;
1078   };
1079   for (LexicalScope *LS : Scope->getChildren()) {
1080     // If the lexical block doesn't have non-scope children, skip
1081     // its emission and put its children directly to the parent scope.
1082     if (needToEmitLexicalScope(LS))
1083       constructScopeDIE(LS, ScopeDIE);
1084     else
1085       createAndAddScopeChildren(LS, ScopeDIE);
1086   }
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     // Round up to smallest number of bytes that contains this number of bits.
1588     addUInt(Die, dwarf::DW_AT_byte_size, None, divideCeil(Btr.BitSize, 8));
1589 
1590     Btr.Die = &Die;
1591   }
1592 }
1593