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