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