xref: /openbsd-src/gnu/llvm/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp (revision 097a140d792de8b2bbe59ad827d39eabf9b4280a)
109467b48Spatrick //===- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Units ------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file contains support for constructing a dwarf compile unit.
1009467b48Spatrick //
1109467b48Spatrick //===----------------------------------------------------------------------===//
1209467b48Spatrick 
1309467b48Spatrick #include "DwarfCompileUnit.h"
1409467b48Spatrick #include "AddressPool.h"
1509467b48Spatrick #include "DwarfDebug.h"
1609467b48Spatrick #include "DwarfExpression.h"
1709467b48Spatrick #include "DwarfUnit.h"
1809467b48Spatrick #include "llvm/ADT/None.h"
1909467b48Spatrick #include "llvm/ADT/STLExtras.h"
2009467b48Spatrick #include "llvm/ADT/SmallString.h"
2109467b48Spatrick #include "llvm/ADT/SmallVector.h"
2209467b48Spatrick #include "llvm/ADT/StringRef.h"
2309467b48Spatrick #include "llvm/BinaryFormat/Dwarf.h"
2409467b48Spatrick #include "llvm/CodeGen/AsmPrinter.h"
2509467b48Spatrick #include "llvm/CodeGen/DIE.h"
2609467b48Spatrick #include "llvm/CodeGen/LexicalScopes.h"
2709467b48Spatrick #include "llvm/CodeGen/MachineFunction.h"
2809467b48Spatrick #include "llvm/CodeGen/MachineInstr.h"
2909467b48Spatrick #include "llvm/CodeGen/MachineOperand.h"
3009467b48Spatrick #include "llvm/CodeGen/TargetFrameLowering.h"
3109467b48Spatrick #include "llvm/CodeGen/TargetRegisterInfo.h"
3209467b48Spatrick #include "llvm/CodeGen/TargetSubtargetInfo.h"
3309467b48Spatrick #include "llvm/IR/DataLayout.h"
3409467b48Spatrick #include "llvm/IR/DebugInfo.h"
3509467b48Spatrick #include "llvm/IR/DebugInfoMetadata.h"
3609467b48Spatrick #include "llvm/IR/GlobalVariable.h"
3709467b48Spatrick #include "llvm/MC/MCSection.h"
3809467b48Spatrick #include "llvm/MC/MCStreamer.h"
3909467b48Spatrick #include "llvm/MC/MCSymbol.h"
40*097a140dSpatrick #include "llvm/MC/MCSymbolWasm.h"
4109467b48Spatrick #include "llvm/MC/MachineLocation.h"
4209467b48Spatrick #include "llvm/Support/Casting.h"
4309467b48Spatrick #include "llvm/Target/TargetLoweringObjectFile.h"
4409467b48Spatrick #include "llvm/Target/TargetMachine.h"
4509467b48Spatrick #include "llvm/Target/TargetOptions.h"
4609467b48Spatrick #include <algorithm>
4709467b48Spatrick #include <cassert>
4809467b48Spatrick #include <cstdint>
4909467b48Spatrick #include <iterator>
5009467b48Spatrick #include <memory>
5109467b48Spatrick #include <string>
5209467b48Spatrick #include <utility>
5309467b48Spatrick 
5409467b48Spatrick using namespace llvm;
5509467b48Spatrick 
5609467b48Spatrick static dwarf::Tag GetCompileUnitType(UnitKind Kind, DwarfDebug *DW) {
5709467b48Spatrick 
5809467b48Spatrick   //  According to DWARF Debugging Information Format Version 5,
5909467b48Spatrick   //  3.1.2 Skeleton Compilation Unit Entries:
6009467b48Spatrick   //  "When generating a split DWARF object file (see Section 7.3.2
6109467b48Spatrick   //  on page 187), the compilation unit in the .debug_info section
6209467b48Spatrick   //  is a "skeleton" compilation unit with the tag DW_TAG_skeleton_unit"
6309467b48Spatrick   if (DW->getDwarfVersion() >= 5 && Kind == UnitKind::Skeleton)
6409467b48Spatrick     return dwarf::DW_TAG_skeleton_unit;
6509467b48Spatrick 
6609467b48Spatrick   return dwarf::DW_TAG_compile_unit;
6709467b48Spatrick }
6809467b48Spatrick 
6909467b48Spatrick DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
7009467b48Spatrick                                    AsmPrinter *A, DwarfDebug *DW,
7109467b48Spatrick                                    DwarfFile *DWU, UnitKind Kind)
7209467b48Spatrick     : DwarfUnit(GetCompileUnitType(Kind, DW), Node, A, DW, DWU), UniqueID(UID) {
7309467b48Spatrick   insertDIE(Node, &getUnitDie());
7409467b48Spatrick   MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
7509467b48Spatrick }
7609467b48Spatrick 
7709467b48Spatrick /// addLabelAddress - Add a dwarf label attribute data and value using
7809467b48Spatrick /// DW_FORM_addr or DW_FORM_GNU_addr_index.
7909467b48Spatrick void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
8009467b48Spatrick                                        const MCSymbol *Label) {
8109467b48Spatrick   // Don't use the address pool in non-fission or in the skeleton unit itself.
8209467b48Spatrick   if ((!DD->useSplitDwarf() || !Skeleton) && DD->getDwarfVersion() < 5)
8309467b48Spatrick     return addLocalLabelAddress(Die, Attribute, Label);
8409467b48Spatrick 
8509467b48Spatrick   if (Label)
8609467b48Spatrick     DD->addArangeLabel(SymbolCU(this, Label));
8709467b48Spatrick 
8809467b48Spatrick   unsigned idx = DD->getAddressPool().getIndex(Label);
8909467b48Spatrick   Die.addValue(DIEValueAllocator, Attribute,
9009467b48Spatrick                DD->getDwarfVersion() >= 5 ? dwarf::DW_FORM_addrx
9109467b48Spatrick                                           : dwarf::DW_FORM_GNU_addr_index,
9209467b48Spatrick                DIEInteger(idx));
9309467b48Spatrick }
9409467b48Spatrick 
9509467b48Spatrick void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
9609467b48Spatrick                                             dwarf::Attribute Attribute,
9709467b48Spatrick                                             const MCSymbol *Label) {
9809467b48Spatrick   if (Label)
9909467b48Spatrick     DD->addArangeLabel(SymbolCU(this, Label));
10009467b48Spatrick 
10109467b48Spatrick   if (Label)
10209467b48Spatrick     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
10309467b48Spatrick                  DIELabel(Label));
10409467b48Spatrick   else
10509467b48Spatrick     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
10609467b48Spatrick                  DIEInteger(0));
10709467b48Spatrick }
10809467b48Spatrick 
10909467b48Spatrick unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
11009467b48Spatrick   // If we print assembly, we can't separate .file entries according to
11109467b48Spatrick   // compile units. Thus all files will belong to the default compile unit.
11209467b48Spatrick 
11309467b48Spatrick   // FIXME: add a better feature test than hasRawTextSupport. Even better,
11409467b48Spatrick   // extend .file to support this.
11509467b48Spatrick   unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
11609467b48Spatrick   if (!File)
117*097a140dSpatrick     return Asm->OutStreamer->emitDwarfFileDirective(0, "", "", None, None,
118*097a140dSpatrick                                                     CUID);
119*097a140dSpatrick   return Asm->OutStreamer->emitDwarfFileDirective(
12009467b48Spatrick       0, File->getDirectory(), File->getFilename(), getMD5AsBytes(File),
12109467b48Spatrick       File->getSource(), CUID);
12209467b48Spatrick }
12309467b48Spatrick 
12409467b48Spatrick DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
12509467b48Spatrick     const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
12609467b48Spatrick   // Check for pre-existence.
12709467b48Spatrick   if (DIE *Die = getDIE(GV))
12809467b48Spatrick     return Die;
12909467b48Spatrick 
13009467b48Spatrick   assert(GV);
13109467b48Spatrick 
13209467b48Spatrick   auto *GVContext = GV->getScope();
13309467b48Spatrick   const DIType *GTy = GV->getType();
13409467b48Spatrick 
13509467b48Spatrick   // Construct the context before querying for the existence of the DIE in
13609467b48Spatrick   // case such construction creates the DIE.
13709467b48Spatrick   auto *CB = GVContext ? dyn_cast<DICommonBlock>(GVContext) : nullptr;
13809467b48Spatrick   DIE *ContextDIE = CB ? getOrCreateCommonBlock(CB, GlobalExprs)
13909467b48Spatrick     : getOrCreateContextDIE(GVContext);
14009467b48Spatrick 
14109467b48Spatrick   // Add to map.
14209467b48Spatrick   DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
14309467b48Spatrick   DIScope *DeclContext;
14409467b48Spatrick   if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
14509467b48Spatrick     DeclContext = SDMDecl->getScope();
14609467b48Spatrick     assert(SDMDecl->isStaticMember() && "Expected static member decl");
14709467b48Spatrick     assert(GV->isDefinition());
14809467b48Spatrick     // We need the declaration DIE that is in the static member's class.
14909467b48Spatrick     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
15009467b48Spatrick     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
15109467b48Spatrick     // If the global variable's type is different from the one in the class
15209467b48Spatrick     // member type, assume that it's more specific and also emit it.
15309467b48Spatrick     if (GTy != SDMDecl->getBaseType())
15409467b48Spatrick       addType(*VariableDIE, GTy);
15509467b48Spatrick   } else {
15609467b48Spatrick     DeclContext = GV->getScope();
15709467b48Spatrick     // Add name and type.
15809467b48Spatrick     addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
159*097a140dSpatrick     if (GTy)
16009467b48Spatrick       addType(*VariableDIE, GTy);
16109467b48Spatrick 
16209467b48Spatrick     // Add scoping info.
16309467b48Spatrick     if (!GV->isLocalToUnit())
16409467b48Spatrick       addFlag(*VariableDIE, dwarf::DW_AT_external);
16509467b48Spatrick 
16609467b48Spatrick     // Add line number info.
16709467b48Spatrick     addSourceLine(*VariableDIE, GV);
16809467b48Spatrick   }
16909467b48Spatrick 
17009467b48Spatrick   if (!GV->isDefinition())
17109467b48Spatrick     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
17209467b48Spatrick   else
17309467b48Spatrick     addGlobalName(GV->getName(), *VariableDIE, DeclContext);
17409467b48Spatrick 
17509467b48Spatrick   if (uint32_t AlignInBytes = GV->getAlignInBytes())
17609467b48Spatrick     addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
17709467b48Spatrick             AlignInBytes);
17809467b48Spatrick 
17909467b48Spatrick   if (MDTuple *TP = GV->getTemplateParams())
18009467b48Spatrick     addTemplateParams(*VariableDIE, DINodeArray(TP));
18109467b48Spatrick 
18209467b48Spatrick   // Add location.
18309467b48Spatrick   addLocationAttribute(VariableDIE, GV, GlobalExprs);
18409467b48Spatrick 
18509467b48Spatrick   return VariableDIE;
18609467b48Spatrick }
18709467b48Spatrick 
18809467b48Spatrick void DwarfCompileUnit::addLocationAttribute(
18909467b48Spatrick     DIE *VariableDIE, const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
19009467b48Spatrick   bool addToAccelTable = false;
19109467b48Spatrick   DIELoc *Loc = nullptr;
19209467b48Spatrick   Optional<unsigned> NVPTXAddressSpace;
19309467b48Spatrick   std::unique_ptr<DIEDwarfExpression> DwarfExpr;
19409467b48Spatrick   for (const auto &GE : GlobalExprs) {
19509467b48Spatrick     const GlobalVariable *Global = GE.Var;
19609467b48Spatrick     const DIExpression *Expr = GE.Expr;
19709467b48Spatrick 
19809467b48Spatrick     // For compatibility with DWARF 3 and earlier,
19909467b48Spatrick     // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) becomes
20009467b48Spatrick     // DW_AT_const_value(X).
20109467b48Spatrick     if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
20209467b48Spatrick       addToAccelTable = true;
20309467b48Spatrick       addConstantValue(*VariableDIE, /*Unsigned=*/true, Expr->getElement(1));
20409467b48Spatrick       break;
20509467b48Spatrick     }
20609467b48Spatrick 
20709467b48Spatrick     // We cannot describe the location of dllimport'd variables: the
20809467b48Spatrick     // computation of their address requires loads from the IAT.
20909467b48Spatrick     if (Global && Global->hasDLLImportStorageClass())
21009467b48Spatrick       continue;
21109467b48Spatrick 
21209467b48Spatrick     // Nothing to describe without address or constant.
21309467b48Spatrick     if (!Global && (!Expr || !Expr->isConstant()))
21409467b48Spatrick       continue;
21509467b48Spatrick 
21609467b48Spatrick     if (Global && Global->isThreadLocal() &&
21709467b48Spatrick         !Asm->getObjFileLowering().supportDebugThreadLocalLocation())
21809467b48Spatrick       continue;
21909467b48Spatrick 
22009467b48Spatrick     if (!Loc) {
22109467b48Spatrick       addToAccelTable = true;
22209467b48Spatrick       Loc = new (DIEValueAllocator) DIELoc;
22309467b48Spatrick       DwarfExpr = std::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
22409467b48Spatrick     }
22509467b48Spatrick 
22609467b48Spatrick     if (Expr) {
22709467b48Spatrick       // According to
22809467b48Spatrick       // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
22909467b48Spatrick       // cuda-gdb requires DW_AT_address_class for all variables to be able to
23009467b48Spatrick       // correctly interpret address space of the variable address.
23109467b48Spatrick       // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
23209467b48Spatrick       // sequence for the NVPTX + gdb target.
23309467b48Spatrick       unsigned LocalNVPTXAddressSpace;
23409467b48Spatrick       if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
23509467b48Spatrick         const DIExpression *NewExpr =
23609467b48Spatrick             DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
23709467b48Spatrick         if (NewExpr != Expr) {
23809467b48Spatrick           Expr = NewExpr;
23909467b48Spatrick           NVPTXAddressSpace = LocalNVPTXAddressSpace;
24009467b48Spatrick         }
24109467b48Spatrick       }
24209467b48Spatrick       DwarfExpr->addFragmentOffset(Expr);
24309467b48Spatrick     }
24409467b48Spatrick 
24509467b48Spatrick     if (Global) {
24609467b48Spatrick       const MCSymbol *Sym = Asm->getSymbol(Global);
24709467b48Spatrick       if (Global->isThreadLocal()) {
24809467b48Spatrick         if (Asm->TM.useEmulatedTLS()) {
24909467b48Spatrick           // TODO: add debug info for emulated thread local mode.
25009467b48Spatrick         } else {
25109467b48Spatrick           // FIXME: Make this work with -gsplit-dwarf.
25209467b48Spatrick           unsigned PointerSize = Asm->getDataLayout().getPointerSize();
25309467b48Spatrick           assert((PointerSize == 4 || PointerSize == 8) &&
25409467b48Spatrick                  "Add support for other sizes if necessary");
25509467b48Spatrick           // Based on GCC's support for TLS:
25609467b48Spatrick           if (!DD->useSplitDwarf()) {
25709467b48Spatrick             // 1) Start with a constNu of the appropriate pointer size
25809467b48Spatrick             addUInt(*Loc, dwarf::DW_FORM_data1,
25909467b48Spatrick                     PointerSize == 4 ? dwarf::DW_OP_const4u
26009467b48Spatrick                                      : dwarf::DW_OP_const8u);
26109467b48Spatrick             // 2) containing the (relocated) offset of the TLS variable
26209467b48Spatrick             //    within the module's TLS block.
26309467b48Spatrick             addExpr(*Loc, dwarf::DW_FORM_udata,
26409467b48Spatrick                     Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
26509467b48Spatrick           } else {
26609467b48Spatrick             addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
26709467b48Spatrick             addUInt(*Loc, dwarf::DW_FORM_udata,
26809467b48Spatrick                     DD->getAddressPool().getIndex(Sym, /* TLS */ true));
26909467b48Spatrick           }
27009467b48Spatrick           // 3) followed by an OP to make the debugger do a TLS lookup.
27109467b48Spatrick           addUInt(*Loc, dwarf::DW_FORM_data1,
27209467b48Spatrick                   DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
27309467b48Spatrick                                         : dwarf::DW_OP_form_tls_address);
27409467b48Spatrick         }
27509467b48Spatrick       } else {
27609467b48Spatrick         DD->addArangeLabel(SymbolCU(this, Sym));
27709467b48Spatrick         addOpAddress(*Loc, Sym);
27809467b48Spatrick       }
27909467b48Spatrick     }
28009467b48Spatrick     // Global variables attached to symbols are memory locations.
28109467b48Spatrick     // It would be better if this were unconditional, but malformed input that
28209467b48Spatrick     // mixes non-fragments and fragments for the same variable is too expensive
28309467b48Spatrick     // to detect in the verifier.
28409467b48Spatrick     if (DwarfExpr->isUnknownLocation())
28509467b48Spatrick       DwarfExpr->setMemoryLocationKind();
28609467b48Spatrick     DwarfExpr->addExpression(Expr);
28709467b48Spatrick   }
28809467b48Spatrick   if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
28909467b48Spatrick     // According to
29009467b48Spatrick     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
29109467b48Spatrick     // cuda-gdb requires DW_AT_address_class for all variables to be able to
29209467b48Spatrick     // correctly interpret address space of the variable address.
29309467b48Spatrick     const unsigned NVPTX_ADDR_global_space = 5;
29409467b48Spatrick     addUInt(*VariableDIE, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
29509467b48Spatrick             NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_global_space);
29609467b48Spatrick   }
29709467b48Spatrick   if (Loc)
29809467b48Spatrick     addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
29909467b48Spatrick 
30009467b48Spatrick   if (DD->useAllLinkageNames())
30109467b48Spatrick     addLinkageName(*VariableDIE, GV->getLinkageName());
30209467b48Spatrick 
30309467b48Spatrick   if (addToAccelTable) {
30409467b48Spatrick     DD->addAccelName(*CUNode, GV->getName(), *VariableDIE);
30509467b48Spatrick 
30609467b48Spatrick     // If the linkage name is different than the name, go ahead and output
30709467b48Spatrick     // that as well into the name table.
30809467b48Spatrick     if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
30909467b48Spatrick         DD->useAllLinkageNames())
31009467b48Spatrick       DD->addAccelName(*CUNode, GV->getLinkageName(), *VariableDIE);
31109467b48Spatrick   }
31209467b48Spatrick }
31309467b48Spatrick 
31409467b48Spatrick DIE *DwarfCompileUnit::getOrCreateCommonBlock(
31509467b48Spatrick     const DICommonBlock *CB, ArrayRef<GlobalExpr> GlobalExprs) {
31609467b48Spatrick   // Construct the context before querying for the existence of the DIE in case
31709467b48Spatrick   // such construction creates the DIE.
31809467b48Spatrick   DIE *ContextDIE = getOrCreateContextDIE(CB->getScope());
31909467b48Spatrick 
32009467b48Spatrick   if (DIE *NDie = getDIE(CB))
32109467b48Spatrick     return NDie;
32209467b48Spatrick   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_common_block, *ContextDIE, CB);
32309467b48Spatrick   StringRef Name = CB->getName().empty() ? "_BLNK_" : CB->getName();
32409467b48Spatrick   addString(NDie, dwarf::DW_AT_name, Name);
32509467b48Spatrick   addGlobalName(Name, NDie, CB->getScope());
32609467b48Spatrick   if (CB->getFile())
32709467b48Spatrick     addSourceLine(NDie, CB->getLineNo(), CB->getFile());
32809467b48Spatrick   if (DIGlobalVariable *V = CB->getDecl())
32909467b48Spatrick     getCU().addLocationAttribute(&NDie, V, GlobalExprs);
33009467b48Spatrick   return &NDie;
33109467b48Spatrick }
33209467b48Spatrick 
33309467b48Spatrick void DwarfCompileUnit::addRange(RangeSpan Range) {
334*097a140dSpatrick   DD->insertSectionLabel(Range.Begin);
335*097a140dSpatrick 
33609467b48Spatrick   bool SameAsPrevCU = this == DD->getPrevCU();
33709467b48Spatrick   DD->setPrevCU(this);
33809467b48Spatrick   // If we have no current ranges just add the range and return, otherwise,
33909467b48Spatrick   // check the current section and CU against the previous section and CU we
34009467b48Spatrick   // emitted into and the subprogram was contained within. If these are the
34109467b48Spatrick   // same then extend our current range, otherwise add this as a new range.
34209467b48Spatrick   if (CURanges.empty() || !SameAsPrevCU ||
34309467b48Spatrick       (&CURanges.back().End->getSection() !=
34409467b48Spatrick        &Range.End->getSection())) {
34509467b48Spatrick     CURanges.push_back(Range);
34609467b48Spatrick     return;
34709467b48Spatrick   }
34809467b48Spatrick 
34909467b48Spatrick   CURanges.back().End = Range.End;
35009467b48Spatrick }
35109467b48Spatrick 
35209467b48Spatrick void DwarfCompileUnit::initStmtList() {
35309467b48Spatrick   if (CUNode->isDebugDirectivesOnly())
35409467b48Spatrick     return;
35509467b48Spatrick 
35609467b48Spatrick   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
35709467b48Spatrick   if (DD->useSectionsAsReferences()) {
35809467b48Spatrick     LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
35909467b48Spatrick   } else {
36009467b48Spatrick     LineTableStartSym =
36109467b48Spatrick         Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
36209467b48Spatrick   }
36309467b48Spatrick 
36409467b48Spatrick   // DW_AT_stmt_list is a offset of line number information for this
36509467b48Spatrick   // compile unit in debug_line section. For split dwarf this is
36609467b48Spatrick   // left in the skeleton CU and so not included.
36709467b48Spatrick   // The line table entries are not always emitted in assembly, so it
36809467b48Spatrick   // is not okay to use line_table_start here.
36909467b48Spatrick       addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
37009467b48Spatrick                       TLOF.getDwarfLineSection()->getBeginSymbol());
37109467b48Spatrick }
37209467b48Spatrick 
37309467b48Spatrick void DwarfCompileUnit::applyStmtList(DIE &D) {
374*097a140dSpatrick   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
375*097a140dSpatrick   addSectionLabel(D, dwarf::DW_AT_stmt_list, LineTableStartSym,
376*097a140dSpatrick                   TLOF.getDwarfLineSection()->getBeginSymbol());
37709467b48Spatrick }
37809467b48Spatrick 
37909467b48Spatrick void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
38009467b48Spatrick                                        const MCSymbol *End) {
38109467b48Spatrick   assert(Begin && "Begin label should not be null!");
38209467b48Spatrick   assert(End && "End label should not be null!");
38309467b48Spatrick   assert(Begin->isDefined() && "Invalid starting label");
38409467b48Spatrick   assert(End->isDefined() && "Invalid end label");
38509467b48Spatrick 
38609467b48Spatrick   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
38709467b48Spatrick   if (DD->getDwarfVersion() < 4)
38809467b48Spatrick     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
38909467b48Spatrick   else
39009467b48Spatrick     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
39109467b48Spatrick }
39209467b48Spatrick 
39309467b48Spatrick // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
39409467b48Spatrick // and DW_AT_high_pc attributes. If there are global variables in this
39509467b48Spatrick // scope then create and insert DIEs for these variables.
39609467b48Spatrick DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
39709467b48Spatrick   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
39809467b48Spatrick 
399*097a140dSpatrick   SmallVector<RangeSpan, 2> BB_List;
400*097a140dSpatrick   // If basic block sections are on, ranges for each basic block section has
401*097a140dSpatrick   // to be emitted separately.
402*097a140dSpatrick   for (const auto &R : Asm->MBBSectionRanges)
403*097a140dSpatrick     BB_List.push_back({R.second.BeginLabel, R.second.EndLabel});
404*097a140dSpatrick 
405*097a140dSpatrick   attachRangesOrLowHighPC(*SPDie, BB_List);
406*097a140dSpatrick 
40709467b48Spatrick   if (DD->useAppleExtensionAttributes() &&
40809467b48Spatrick       !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
40909467b48Spatrick           *DD->getCurrentFunction()))
41009467b48Spatrick     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
41109467b48Spatrick 
41209467b48Spatrick   // Only include DW_AT_frame_base in full debug info
41309467b48Spatrick   if (!includeMinimalInlineScopes()) {
414*097a140dSpatrick     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
415*097a140dSpatrick     TargetFrameLowering::DwarfFrameBase FrameBase =
416*097a140dSpatrick         TFI->getDwarfFrameBase(*Asm->MF);
417*097a140dSpatrick     switch (FrameBase.Kind) {
418*097a140dSpatrick     case TargetFrameLowering::DwarfFrameBase::Register: {
419*097a140dSpatrick       if (Register::isPhysicalRegister(FrameBase.Location.Reg)) {
420*097a140dSpatrick         MachineLocation Location(FrameBase.Location.Reg);
421*097a140dSpatrick         addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
422*097a140dSpatrick       }
423*097a140dSpatrick       break;
424*097a140dSpatrick     }
425*097a140dSpatrick     case TargetFrameLowering::DwarfFrameBase::CFA: {
42609467b48Spatrick       DIELoc *Loc = new (DIEValueAllocator) DIELoc;
42709467b48Spatrick       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa);
42809467b48Spatrick       addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
429*097a140dSpatrick       break;
430*097a140dSpatrick     }
431*097a140dSpatrick     case TargetFrameLowering::DwarfFrameBase::WasmFrameBase: {
432*097a140dSpatrick       // FIXME: duplicated from Target/WebAssembly/WebAssembly.h
433*097a140dSpatrick       // don't want to depend on target specific headers in this code?
434*097a140dSpatrick       const unsigned TI_GLOBAL_RELOC = 3;
435*097a140dSpatrick       if (FrameBase.Location.WasmLoc.Kind == TI_GLOBAL_RELOC) {
436*097a140dSpatrick         // These need to be relocatable.
437*097a140dSpatrick         assert(FrameBase.Location.WasmLoc.Index == 0);  // Only SP so far.
438*097a140dSpatrick         auto SPSym = cast<MCSymbolWasm>(
439*097a140dSpatrick           Asm->GetExternalSymbolSymbol("__stack_pointer"));
440*097a140dSpatrick         // FIXME: this repeats what WebAssemblyMCInstLower::
441*097a140dSpatrick         // GetExternalSymbolSymbol does, since if there's no code that
442*097a140dSpatrick         // refers to this symbol, we have to set it here.
443*097a140dSpatrick         SPSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
444*097a140dSpatrick         SPSym->setGlobalType(wasm::WasmGlobalType{
445*097a140dSpatrick             uint8_t(Asm->getSubtargetInfo().getTargetTriple().getArch() ==
446*097a140dSpatrick                             Triple::wasm64
447*097a140dSpatrick                         ? wasm::WASM_TYPE_I64
448*097a140dSpatrick                         : wasm::WASM_TYPE_I32),
449*097a140dSpatrick             true});
450*097a140dSpatrick         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
451*097a140dSpatrick         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_WASM_location);
452*097a140dSpatrick         addSInt(*Loc, dwarf::DW_FORM_sdata, FrameBase.Location.WasmLoc.Kind);
453*097a140dSpatrick         addLabel(*Loc, dwarf::DW_FORM_udata, SPSym);
454*097a140dSpatrick         DD->addArangeLabel(SymbolCU(this, SPSym));
455*097a140dSpatrick         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
456*097a140dSpatrick         addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
45709467b48Spatrick       } else {
458*097a140dSpatrick         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
459*097a140dSpatrick         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
460*097a140dSpatrick         DIExpressionCursor Cursor({});
461*097a140dSpatrick         DwarfExpr.addWasmLocation(FrameBase.Location.WasmLoc.Kind,
462*097a140dSpatrick             FrameBase.Location.WasmLoc.Index);
463*097a140dSpatrick         DwarfExpr.addExpression(std::move(Cursor));
464*097a140dSpatrick         addBlock(*SPDie, dwarf::DW_AT_frame_base, DwarfExpr.finalize());
465*097a140dSpatrick       }
466*097a140dSpatrick       break;
467*097a140dSpatrick     }
46809467b48Spatrick     }
46909467b48Spatrick   }
47009467b48Spatrick 
47109467b48Spatrick   // Add name to the name table, we do this here because we're guaranteed
47209467b48Spatrick   // to have concrete versions of our DW_TAG_subprogram nodes.
47309467b48Spatrick   DD->addSubprogramNames(*CUNode, SP, *SPDie);
47409467b48Spatrick 
47509467b48Spatrick   return *SPDie;
47609467b48Spatrick }
47709467b48Spatrick 
47809467b48Spatrick // Construct a DIE for this scope.
47909467b48Spatrick void DwarfCompileUnit::constructScopeDIE(
48009467b48Spatrick     LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
48109467b48Spatrick   if (!Scope || !Scope->getScopeNode())
48209467b48Spatrick     return;
48309467b48Spatrick 
48409467b48Spatrick   auto *DS = Scope->getScopeNode();
48509467b48Spatrick 
48609467b48Spatrick   assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
48709467b48Spatrick          "Only handle inlined subprograms here, use "
48809467b48Spatrick          "constructSubprogramScopeDIE for non-inlined "
48909467b48Spatrick          "subprograms");
49009467b48Spatrick 
49109467b48Spatrick   SmallVector<DIE *, 8> Children;
49209467b48Spatrick 
49309467b48Spatrick   // We try to create the scope DIE first, then the children DIEs. This will
49409467b48Spatrick   // avoid creating un-used children then removing them later when we find out
49509467b48Spatrick   // the scope DIE is null.
49609467b48Spatrick   DIE *ScopeDIE;
49709467b48Spatrick   if (Scope->getParent() && isa<DISubprogram>(DS)) {
49809467b48Spatrick     ScopeDIE = constructInlinedScopeDIE(Scope);
49909467b48Spatrick     if (!ScopeDIE)
50009467b48Spatrick       return;
50109467b48Spatrick     // We create children when the scope DIE is not null.
50209467b48Spatrick     createScopeChildrenDIE(Scope, Children);
50309467b48Spatrick   } else {
50409467b48Spatrick     // Early exit when we know the scope DIE is going to be null.
50509467b48Spatrick     if (DD->isLexicalScopeDIENull(Scope))
50609467b48Spatrick       return;
50709467b48Spatrick 
50809467b48Spatrick     bool HasNonScopeChildren = false;
50909467b48Spatrick 
51009467b48Spatrick     // We create children here when we know the scope DIE is not going to be
51109467b48Spatrick     // null and the children will be added to the scope DIE.
51209467b48Spatrick     createScopeChildrenDIE(Scope, Children, &HasNonScopeChildren);
51309467b48Spatrick 
51409467b48Spatrick     // If there are only other scopes as children, put them directly in the
51509467b48Spatrick     // parent instead, as this scope would serve no purpose.
51609467b48Spatrick     if (!HasNonScopeChildren) {
51709467b48Spatrick       FinalChildren.insert(FinalChildren.end(),
51809467b48Spatrick                            std::make_move_iterator(Children.begin()),
51909467b48Spatrick                            std::make_move_iterator(Children.end()));
52009467b48Spatrick       return;
52109467b48Spatrick     }
52209467b48Spatrick     ScopeDIE = constructLexicalScopeDIE(Scope);
52309467b48Spatrick     assert(ScopeDIE && "Scope DIE should not be null.");
52409467b48Spatrick   }
52509467b48Spatrick 
52609467b48Spatrick   // Add children
52709467b48Spatrick   for (auto &I : Children)
52809467b48Spatrick     ScopeDIE->addChild(std::move(I));
52909467b48Spatrick 
53009467b48Spatrick   FinalChildren.push_back(std::move(ScopeDIE));
53109467b48Spatrick }
53209467b48Spatrick 
53309467b48Spatrick void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
53409467b48Spatrick                                          SmallVector<RangeSpan, 2> Range) {
53509467b48Spatrick 
53609467b48Spatrick   HasRangeLists = true;
53709467b48Spatrick 
53809467b48Spatrick   // Add the range list to the set of ranges to be emitted.
53909467b48Spatrick   auto IndexAndList =
54009467b48Spatrick       (DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU)
54109467b48Spatrick           ->addRange(*(Skeleton ? Skeleton : this), std::move(Range));
54209467b48Spatrick 
54309467b48Spatrick   uint32_t Index = IndexAndList.first;
54409467b48Spatrick   auto &List = *IndexAndList.second;
54509467b48Spatrick 
54609467b48Spatrick   // Under fission, ranges are specified by constant offsets relative to the
54709467b48Spatrick   // CU's DW_AT_GNU_ranges_base.
54809467b48Spatrick   // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
54909467b48Spatrick   // fission until we support the forms using the .debug_addr section
55009467b48Spatrick   // (DW_RLE_startx_endx etc.).
55109467b48Spatrick   if (DD->getDwarfVersion() >= 5)
55209467b48Spatrick     addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_rnglistx, Index);
55309467b48Spatrick   else {
55409467b48Spatrick     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
55509467b48Spatrick     const MCSymbol *RangeSectionSym =
55609467b48Spatrick         TLOF.getDwarfRangesSection()->getBeginSymbol();
55709467b48Spatrick     if (isDwoUnit())
55809467b48Spatrick       addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
55909467b48Spatrick                       RangeSectionSym);
56009467b48Spatrick     else
56109467b48Spatrick       addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
56209467b48Spatrick                       RangeSectionSym);
56309467b48Spatrick   }
56409467b48Spatrick }
56509467b48Spatrick 
56609467b48Spatrick void DwarfCompileUnit::attachRangesOrLowHighPC(
56709467b48Spatrick     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
56809467b48Spatrick   if (Ranges.size() == 1 || !DD->useRangesSection()) {
56909467b48Spatrick     const RangeSpan &Front = Ranges.front();
57009467b48Spatrick     const RangeSpan &Back = Ranges.back();
57109467b48Spatrick     attachLowHighPC(Die, Front.Begin, Back.End);
57209467b48Spatrick   } else
57309467b48Spatrick     addScopeRangeList(Die, std::move(Ranges));
57409467b48Spatrick }
57509467b48Spatrick 
57609467b48Spatrick void DwarfCompileUnit::attachRangesOrLowHighPC(
57709467b48Spatrick     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
57809467b48Spatrick   SmallVector<RangeSpan, 2> List;
57909467b48Spatrick   List.reserve(Ranges.size());
580*097a140dSpatrick   for (const InsnRange &R : Ranges) {
581*097a140dSpatrick     auto *BeginLabel = DD->getLabelBeforeInsn(R.first);
582*097a140dSpatrick     auto *EndLabel = DD->getLabelAfterInsn(R.second);
583*097a140dSpatrick 
584*097a140dSpatrick     const auto *BeginMBB = R.first->getParent();
585*097a140dSpatrick     const auto *EndMBB = R.second->getParent();
586*097a140dSpatrick 
587*097a140dSpatrick     const auto *MBB = BeginMBB;
588*097a140dSpatrick     // Basic block sections allows basic block subsets to be placed in unique
589*097a140dSpatrick     // sections. For each section, the begin and end label must be added to the
590*097a140dSpatrick     // list. If there is more than one range, debug ranges must be used.
591*097a140dSpatrick     // Otherwise, low/high PC can be used.
592*097a140dSpatrick     // FIXME: Debug Info Emission depends on block order and this assumes that
593*097a140dSpatrick     // the order of blocks will be frozen beyond this point.
594*097a140dSpatrick     do {
595*097a140dSpatrick       if (MBB->sameSection(EndMBB) || MBB->isEndSection()) {
596*097a140dSpatrick         auto MBBSectionRange = Asm->MBBSectionRanges[MBB->getSectionIDNum()];
59709467b48Spatrick         List.push_back(
598*097a140dSpatrick             {MBB->sameSection(BeginMBB) ? BeginLabel
599*097a140dSpatrick                                         : MBBSectionRange.BeginLabel,
600*097a140dSpatrick              MBB->sameSection(EndMBB) ? EndLabel : MBBSectionRange.EndLabel});
601*097a140dSpatrick       }
602*097a140dSpatrick       if (MBB->sameSection(EndMBB))
603*097a140dSpatrick         break;
604*097a140dSpatrick       MBB = MBB->getNextNode();
605*097a140dSpatrick     } while (true);
606*097a140dSpatrick   }
60709467b48Spatrick   attachRangesOrLowHighPC(Die, std::move(List));
60809467b48Spatrick }
60909467b48Spatrick 
61009467b48Spatrick // This scope represents inlined body of a function. Construct DIE to
61109467b48Spatrick // represent this concrete inlined copy of the function.
61209467b48Spatrick DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
61309467b48Spatrick   assert(Scope->getScopeNode());
61409467b48Spatrick   auto *DS = Scope->getScopeNode();
61509467b48Spatrick   auto *InlinedSP = getDISubprogram(DS);
61609467b48Spatrick   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
61709467b48Spatrick   // was inlined from another compile unit.
61809467b48Spatrick   DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
61909467b48Spatrick   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
62009467b48Spatrick 
62109467b48Spatrick   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
62209467b48Spatrick   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
62309467b48Spatrick 
62409467b48Spatrick   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
62509467b48Spatrick 
62609467b48Spatrick   // Add the call site information to the DIE.
62709467b48Spatrick   const DILocation *IA = Scope->getInlinedAt();
62809467b48Spatrick   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
62909467b48Spatrick           getOrCreateSourceID(IA->getFile()));
63009467b48Spatrick   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
63109467b48Spatrick   if (IA->getColumn())
63209467b48Spatrick     addUInt(*ScopeDIE, dwarf::DW_AT_call_column, None, IA->getColumn());
63309467b48Spatrick   if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
63409467b48Spatrick     addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
63509467b48Spatrick             IA->getDiscriminator());
63609467b48Spatrick 
63709467b48Spatrick   // Add name to the name table, we do this here because we're guaranteed
63809467b48Spatrick   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
63909467b48Spatrick   DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
64009467b48Spatrick 
64109467b48Spatrick   return ScopeDIE;
64209467b48Spatrick }
64309467b48Spatrick 
64409467b48Spatrick // Construct new DW_TAG_lexical_block for this scope and attach
64509467b48Spatrick // DW_AT_low_pc/DW_AT_high_pc labels.
64609467b48Spatrick DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
64709467b48Spatrick   if (DD->isLexicalScopeDIENull(Scope))
64809467b48Spatrick     return nullptr;
64909467b48Spatrick 
65009467b48Spatrick   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
65109467b48Spatrick   if (Scope->isAbstractScope())
65209467b48Spatrick     return ScopeDIE;
65309467b48Spatrick 
65409467b48Spatrick   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
65509467b48Spatrick 
65609467b48Spatrick   return ScopeDIE;
65709467b48Spatrick }
65809467b48Spatrick 
65909467b48Spatrick /// constructVariableDIE - Construct a DIE for the given DbgVariable.
66009467b48Spatrick DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
66109467b48Spatrick   auto D = constructVariableDIEImpl(DV, Abstract);
66209467b48Spatrick   DV.setDIE(*D);
66309467b48Spatrick   return D;
66409467b48Spatrick }
66509467b48Spatrick 
66609467b48Spatrick DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
66709467b48Spatrick                                          const LexicalScope &Scope) {
66809467b48Spatrick   auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
66909467b48Spatrick   insertDIE(DL.getLabel(), LabelDie);
67009467b48Spatrick   DL.setDIE(*LabelDie);
67109467b48Spatrick 
67209467b48Spatrick   if (Scope.isAbstractScope())
67309467b48Spatrick     applyLabelAttributes(DL, *LabelDie);
67409467b48Spatrick 
67509467b48Spatrick   return LabelDie;
67609467b48Spatrick }
67709467b48Spatrick 
67809467b48Spatrick DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
67909467b48Spatrick                                                 bool Abstract) {
68009467b48Spatrick   // Define variable debug information entry.
68109467b48Spatrick   auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
68209467b48Spatrick   insertDIE(DV.getVariable(), VariableDie);
68309467b48Spatrick 
68409467b48Spatrick   if (Abstract) {
68509467b48Spatrick     applyVariableAttributes(DV, *VariableDie);
68609467b48Spatrick     return VariableDie;
68709467b48Spatrick   }
68809467b48Spatrick 
68909467b48Spatrick   // Add variable address.
69009467b48Spatrick 
69109467b48Spatrick   unsigned Offset = DV.getDebugLocListIndex();
69209467b48Spatrick   if (Offset != ~0U) {
69309467b48Spatrick     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
69409467b48Spatrick     auto TagOffset = DV.getDebugLocListTagOffset();
69509467b48Spatrick     if (TagOffset)
69609467b48Spatrick       addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
69709467b48Spatrick               *TagOffset);
69809467b48Spatrick     return VariableDie;
69909467b48Spatrick   }
70009467b48Spatrick 
70109467b48Spatrick   // Check if variable has a single location description.
70209467b48Spatrick   if (auto *DVal = DV.getValueLoc()) {
70309467b48Spatrick     if (DVal->isLocation())
70409467b48Spatrick       addVariableAddress(DV, *VariableDie, DVal->getLoc());
70509467b48Spatrick     else if (DVal->isInt()) {
70609467b48Spatrick       auto *Expr = DV.getSingleExpression();
70709467b48Spatrick       if (Expr && Expr->getNumElements()) {
70809467b48Spatrick         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
70909467b48Spatrick         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
71009467b48Spatrick         // If there is an expression, emit raw unsigned bytes.
71109467b48Spatrick         DwarfExpr.addFragmentOffset(Expr);
71209467b48Spatrick         DwarfExpr.addUnsignedConstant(DVal->getInt());
71309467b48Spatrick         DwarfExpr.addExpression(Expr);
71409467b48Spatrick         addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
71509467b48Spatrick         if (DwarfExpr.TagOffset)
71609467b48Spatrick           addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset,
71709467b48Spatrick                   dwarf::DW_FORM_data1, *DwarfExpr.TagOffset);
71809467b48Spatrick 
71909467b48Spatrick       } else
72009467b48Spatrick         addConstantValue(*VariableDie, DVal->getInt(), DV.getType());
72109467b48Spatrick     } else if (DVal->isConstantFP()) {
72209467b48Spatrick       addConstantFPValue(*VariableDie, DVal->getConstantFP());
72309467b48Spatrick     } else if (DVal->isConstantInt()) {
72409467b48Spatrick       addConstantValue(*VariableDie, DVal->getConstantInt(), DV.getType());
72509467b48Spatrick     }
72609467b48Spatrick     return VariableDie;
72709467b48Spatrick   }
72809467b48Spatrick 
72909467b48Spatrick   // .. else use frame index.
73009467b48Spatrick   if (!DV.hasFrameIndexExprs())
73109467b48Spatrick     return VariableDie;
73209467b48Spatrick 
73309467b48Spatrick   Optional<unsigned> NVPTXAddressSpace;
73409467b48Spatrick   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
73509467b48Spatrick   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
73609467b48Spatrick   for (auto &Fragment : DV.getFrameIndexExprs()) {
737*097a140dSpatrick     Register FrameReg;
73809467b48Spatrick     const DIExpression *Expr = Fragment.Expr;
73909467b48Spatrick     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
74009467b48Spatrick     int Offset = TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
74109467b48Spatrick     DwarfExpr.addFragmentOffset(Expr);
74209467b48Spatrick     SmallVector<uint64_t, 8> Ops;
74309467b48Spatrick     DIExpression::appendOffset(Ops, Offset);
74409467b48Spatrick     // According to
74509467b48Spatrick     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
74609467b48Spatrick     // cuda-gdb requires DW_AT_address_class for all variables to be able to
74709467b48Spatrick     // correctly interpret address space of the variable address.
74809467b48Spatrick     // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
74909467b48Spatrick     // sequence for the NVPTX + gdb target.
75009467b48Spatrick     unsigned LocalNVPTXAddressSpace;
75109467b48Spatrick     if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
75209467b48Spatrick       const DIExpression *NewExpr =
75309467b48Spatrick           DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
75409467b48Spatrick       if (NewExpr != Expr) {
75509467b48Spatrick         Expr = NewExpr;
75609467b48Spatrick         NVPTXAddressSpace = LocalNVPTXAddressSpace;
75709467b48Spatrick       }
75809467b48Spatrick     }
75909467b48Spatrick     if (Expr)
76009467b48Spatrick       Ops.append(Expr->elements_begin(), Expr->elements_end());
76109467b48Spatrick     DIExpressionCursor Cursor(Ops);
76209467b48Spatrick     DwarfExpr.setMemoryLocationKind();
76309467b48Spatrick     if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
76409467b48Spatrick       addOpAddress(*Loc, FrameSymbol);
76509467b48Spatrick     else
76609467b48Spatrick       DwarfExpr.addMachineRegExpression(
76709467b48Spatrick           *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
76809467b48Spatrick     DwarfExpr.addExpression(std::move(Cursor));
76909467b48Spatrick   }
77009467b48Spatrick   if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
77109467b48Spatrick     // According to
77209467b48Spatrick     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
77309467b48Spatrick     // cuda-gdb requires DW_AT_address_class for all variables to be able to
77409467b48Spatrick     // correctly interpret address space of the variable address.
77509467b48Spatrick     const unsigned NVPTX_ADDR_local_space = 6;
77609467b48Spatrick     addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
77709467b48Spatrick             NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space);
77809467b48Spatrick   }
77909467b48Spatrick   addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
78009467b48Spatrick   if (DwarfExpr.TagOffset)
78109467b48Spatrick     addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
78209467b48Spatrick             *DwarfExpr.TagOffset);
78309467b48Spatrick 
78409467b48Spatrick   return VariableDie;
78509467b48Spatrick }
78609467b48Spatrick 
78709467b48Spatrick DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
78809467b48Spatrick                                             const LexicalScope &Scope,
78909467b48Spatrick                                             DIE *&ObjectPointer) {
79009467b48Spatrick   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
79109467b48Spatrick   if (DV.isObjectPointer())
79209467b48Spatrick     ObjectPointer = Var;
79309467b48Spatrick   return Var;
79409467b48Spatrick }
79509467b48Spatrick 
79609467b48Spatrick /// Return all DIVariables that appear in count: expressions.
79709467b48Spatrick static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
79809467b48Spatrick   SmallVector<const DIVariable *, 2> Result;
79909467b48Spatrick   auto *Array = dyn_cast<DICompositeType>(Var->getType());
80009467b48Spatrick   if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
80109467b48Spatrick     return Result;
802*097a140dSpatrick   if (auto *DLVar = Array->getDataLocation())
803*097a140dSpatrick     Result.push_back(DLVar);
80409467b48Spatrick   for (auto *El : Array->getElements()) {
80509467b48Spatrick     if (auto *Subrange = dyn_cast<DISubrange>(El)) {
806*097a140dSpatrick       if (auto Count = Subrange->getCount())
80709467b48Spatrick         if (auto *Dependency = Count.dyn_cast<DIVariable *>())
80809467b48Spatrick           Result.push_back(Dependency);
809*097a140dSpatrick       if (auto LB = Subrange->getLowerBound())
810*097a140dSpatrick         if (auto *Dependency = LB.dyn_cast<DIVariable *>())
811*097a140dSpatrick           Result.push_back(Dependency);
812*097a140dSpatrick       if (auto UB = Subrange->getUpperBound())
813*097a140dSpatrick         if (auto *Dependency = UB.dyn_cast<DIVariable *>())
814*097a140dSpatrick           Result.push_back(Dependency);
815*097a140dSpatrick       if (auto ST = Subrange->getStride())
816*097a140dSpatrick         if (auto *Dependency = ST.dyn_cast<DIVariable *>())
817*097a140dSpatrick           Result.push_back(Dependency);
81809467b48Spatrick     }
81909467b48Spatrick   }
82009467b48Spatrick   return Result;
82109467b48Spatrick }
82209467b48Spatrick 
82309467b48Spatrick /// Sort local variables so that variables appearing inside of helper
82409467b48Spatrick /// expressions come first.
82509467b48Spatrick static SmallVector<DbgVariable *, 8>
82609467b48Spatrick sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
82709467b48Spatrick   SmallVector<DbgVariable *, 8> Result;
82809467b48Spatrick   SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
82909467b48Spatrick   // Map back from a DIVariable to its containing DbgVariable.
83009467b48Spatrick   SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
83109467b48Spatrick   // Set of DbgVariables in Result.
83209467b48Spatrick   SmallDenseSet<DbgVariable *, 8> Visited;
83309467b48Spatrick   // For cycle detection.
83409467b48Spatrick   SmallDenseSet<DbgVariable *, 8> Visiting;
83509467b48Spatrick 
83609467b48Spatrick   // Initialize the worklist and the DIVariable lookup table.
83709467b48Spatrick   for (auto Var : reverse(Input)) {
83809467b48Spatrick     DbgVar.insert({Var->getVariable(), Var});
83909467b48Spatrick     WorkList.push_back({Var, 0});
84009467b48Spatrick   }
84109467b48Spatrick 
84209467b48Spatrick   // Perform a stable topological sort by doing a DFS.
84309467b48Spatrick   while (!WorkList.empty()) {
84409467b48Spatrick     auto Item = WorkList.back();
84509467b48Spatrick     DbgVariable *Var = Item.getPointer();
84609467b48Spatrick     bool visitedAllDependencies = Item.getInt();
84709467b48Spatrick     WorkList.pop_back();
84809467b48Spatrick 
84909467b48Spatrick     // Dependency is in a different lexical scope or a global.
85009467b48Spatrick     if (!Var)
85109467b48Spatrick       continue;
85209467b48Spatrick 
85309467b48Spatrick     // Already handled.
85409467b48Spatrick     if (Visited.count(Var))
85509467b48Spatrick       continue;
85609467b48Spatrick 
85709467b48Spatrick     // Add to Result if all dependencies are visited.
85809467b48Spatrick     if (visitedAllDependencies) {
85909467b48Spatrick       Visited.insert(Var);
86009467b48Spatrick       Result.push_back(Var);
86109467b48Spatrick       continue;
86209467b48Spatrick     }
86309467b48Spatrick 
86409467b48Spatrick     // Detect cycles.
86509467b48Spatrick     auto Res = Visiting.insert(Var);
86609467b48Spatrick     if (!Res.second) {
86709467b48Spatrick       assert(false && "dependency cycle in local variables");
86809467b48Spatrick       return Result;
86909467b48Spatrick     }
87009467b48Spatrick 
87109467b48Spatrick     // Push dependencies and this node onto the worklist, so that this node is
87209467b48Spatrick     // visited again after all of its dependencies are handled.
87309467b48Spatrick     WorkList.push_back({Var, 1});
87409467b48Spatrick     for (auto *Dependency : dependencies(Var)) {
87509467b48Spatrick       auto Dep = dyn_cast_or_null<const DILocalVariable>(Dependency);
87609467b48Spatrick       WorkList.push_back({DbgVar[Dep], 0});
87709467b48Spatrick     }
87809467b48Spatrick   }
87909467b48Spatrick   return Result;
88009467b48Spatrick }
88109467b48Spatrick 
88209467b48Spatrick DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
88309467b48Spatrick                                               SmallVectorImpl<DIE *> &Children,
88409467b48Spatrick                                               bool *HasNonScopeChildren) {
88509467b48Spatrick   assert(Children.empty());
88609467b48Spatrick   DIE *ObjectPointer = nullptr;
88709467b48Spatrick 
88809467b48Spatrick   // Emit function arguments (order is significant).
88909467b48Spatrick   auto Vars = DU->getScopeVariables().lookup(Scope);
89009467b48Spatrick   for (auto &DV : Vars.Args)
89109467b48Spatrick     Children.push_back(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
89209467b48Spatrick 
89309467b48Spatrick   // Emit local variables.
89409467b48Spatrick   auto Locals = sortLocalVars(Vars.Locals);
89509467b48Spatrick   for (DbgVariable *DV : Locals)
89609467b48Spatrick     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
89709467b48Spatrick 
89809467b48Spatrick   // Skip imported directives in gmlt-like data.
89909467b48Spatrick   if (!includeMinimalInlineScopes()) {
90009467b48Spatrick     // There is no need to emit empty lexical block DIE.
90109467b48Spatrick     for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
90209467b48Spatrick       Children.push_back(
90309467b48Spatrick           constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
90409467b48Spatrick   }
90509467b48Spatrick 
90609467b48Spatrick   if (HasNonScopeChildren)
90709467b48Spatrick     *HasNonScopeChildren = !Children.empty();
90809467b48Spatrick 
90909467b48Spatrick   for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
91009467b48Spatrick     Children.push_back(constructLabelDIE(*DL, *Scope));
91109467b48Spatrick 
91209467b48Spatrick   for (LexicalScope *LS : Scope->getChildren())
91309467b48Spatrick     constructScopeDIE(LS, Children);
91409467b48Spatrick 
91509467b48Spatrick   return ObjectPointer;
91609467b48Spatrick }
91709467b48Spatrick 
91809467b48Spatrick DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub,
91909467b48Spatrick                                                    LexicalScope *Scope) {
92009467b48Spatrick   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
92109467b48Spatrick 
92209467b48Spatrick   if (Scope) {
92309467b48Spatrick     assert(!Scope->getInlinedAt());
92409467b48Spatrick     assert(!Scope->isAbstractScope());
92509467b48Spatrick     // Collect lexical scope children first.
92609467b48Spatrick     // ObjectPointer might be a local (non-argument) local variable if it's a
92709467b48Spatrick     // block's synthetic this pointer.
92809467b48Spatrick     if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
92909467b48Spatrick       addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
93009467b48Spatrick   }
93109467b48Spatrick 
93209467b48Spatrick   // If this is a variadic function, add an unspecified parameter.
93309467b48Spatrick   DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
93409467b48Spatrick 
93509467b48Spatrick   // If we have a single element of null, it is a function that returns void.
93609467b48Spatrick   // If we have more than one elements and the last one is null, it is a
93709467b48Spatrick   // variadic function.
93809467b48Spatrick   if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
93909467b48Spatrick       !includeMinimalInlineScopes())
94009467b48Spatrick     ScopeDIE.addChild(
94109467b48Spatrick         DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
94209467b48Spatrick 
94309467b48Spatrick   return ScopeDIE;
94409467b48Spatrick }
94509467b48Spatrick 
94609467b48Spatrick DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
94709467b48Spatrick                                                  DIE &ScopeDIE) {
94809467b48Spatrick   // We create children when the scope DIE is not null.
94909467b48Spatrick   SmallVector<DIE *, 8> Children;
95009467b48Spatrick   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
95109467b48Spatrick 
95209467b48Spatrick   // Add children
95309467b48Spatrick   for (auto &I : Children)
95409467b48Spatrick     ScopeDIE.addChild(std::move(I));
95509467b48Spatrick 
95609467b48Spatrick   return ObjectPointer;
95709467b48Spatrick }
95809467b48Spatrick 
95909467b48Spatrick void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
96009467b48Spatrick     LexicalScope *Scope) {
96109467b48Spatrick   DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
96209467b48Spatrick   if (AbsDef)
96309467b48Spatrick     return;
96409467b48Spatrick 
96509467b48Spatrick   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
96609467b48Spatrick 
96709467b48Spatrick   DIE *ContextDIE;
96809467b48Spatrick   DwarfCompileUnit *ContextCU = this;
96909467b48Spatrick 
97009467b48Spatrick   if (includeMinimalInlineScopes())
97109467b48Spatrick     ContextDIE = &getUnitDie();
97209467b48Spatrick   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
97309467b48Spatrick   // the important distinction that the debug node is not associated with the
97409467b48Spatrick   // DIE (since the debug node will be associated with the concrete DIE, if
97509467b48Spatrick   // any). It could be refactored to some common utility function.
97609467b48Spatrick   else if (auto *SPDecl = SP->getDeclaration()) {
97709467b48Spatrick     ContextDIE = &getUnitDie();
97809467b48Spatrick     getOrCreateSubprogramDIE(SPDecl);
97909467b48Spatrick   } else {
98009467b48Spatrick     ContextDIE = getOrCreateContextDIE(SP->getScope());
98109467b48Spatrick     // The scope may be shared with a subprogram that has already been
98209467b48Spatrick     // constructed in another CU, in which case we need to construct this
98309467b48Spatrick     // subprogram in the same CU.
98409467b48Spatrick     ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
98509467b48Spatrick   }
98609467b48Spatrick 
98709467b48Spatrick   // Passing null as the associated node because the abstract definition
98809467b48Spatrick   // shouldn't be found by lookup.
98909467b48Spatrick   AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
99009467b48Spatrick   ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
99109467b48Spatrick 
99209467b48Spatrick   if (!ContextCU->includeMinimalInlineScopes())
99309467b48Spatrick     ContextCU->addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
99409467b48Spatrick   if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
99509467b48Spatrick     ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
99609467b48Spatrick }
99709467b48Spatrick 
998*097a140dSpatrick bool DwarfCompileUnit::useGNUAnalogForDwarf5Feature() const {
99909467b48Spatrick   return DD->getDwarfVersion() == 4 && DD->tuneForGDB();
100009467b48Spatrick }
100109467b48Spatrick 
100209467b48Spatrick dwarf::Tag DwarfCompileUnit::getDwarf5OrGNUTag(dwarf::Tag Tag) const {
1003*097a140dSpatrick   if (!useGNUAnalogForDwarf5Feature())
100409467b48Spatrick     return Tag;
100509467b48Spatrick   switch (Tag) {
100609467b48Spatrick   case dwarf::DW_TAG_call_site:
100709467b48Spatrick     return dwarf::DW_TAG_GNU_call_site;
100809467b48Spatrick   case dwarf::DW_TAG_call_site_parameter:
100909467b48Spatrick     return dwarf::DW_TAG_GNU_call_site_parameter;
101009467b48Spatrick   default:
101109467b48Spatrick     llvm_unreachable("DWARF5 tag with no GNU analog");
101209467b48Spatrick   }
101309467b48Spatrick }
101409467b48Spatrick 
101509467b48Spatrick dwarf::Attribute
101609467b48Spatrick DwarfCompileUnit::getDwarf5OrGNUAttr(dwarf::Attribute Attr) const {
1017*097a140dSpatrick   if (!useGNUAnalogForDwarf5Feature())
101809467b48Spatrick     return Attr;
101909467b48Spatrick   switch (Attr) {
102009467b48Spatrick   case dwarf::DW_AT_call_all_calls:
102109467b48Spatrick     return dwarf::DW_AT_GNU_all_call_sites;
102209467b48Spatrick   case dwarf::DW_AT_call_target:
102309467b48Spatrick     return dwarf::DW_AT_GNU_call_site_target;
102409467b48Spatrick   case dwarf::DW_AT_call_origin:
102509467b48Spatrick     return dwarf::DW_AT_abstract_origin;
1026*097a140dSpatrick   case dwarf::DW_AT_call_return_pc:
102709467b48Spatrick     return dwarf::DW_AT_low_pc;
102809467b48Spatrick   case dwarf::DW_AT_call_value:
102909467b48Spatrick     return dwarf::DW_AT_GNU_call_site_value;
103009467b48Spatrick   case dwarf::DW_AT_call_tail_call:
103109467b48Spatrick     return dwarf::DW_AT_GNU_tail_call;
103209467b48Spatrick   default:
103309467b48Spatrick     llvm_unreachable("DWARF5 attribute with no GNU analog");
103409467b48Spatrick   }
103509467b48Spatrick }
103609467b48Spatrick 
103709467b48Spatrick dwarf::LocationAtom
103809467b48Spatrick DwarfCompileUnit::getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const {
1039*097a140dSpatrick   if (!useGNUAnalogForDwarf5Feature())
104009467b48Spatrick     return Loc;
104109467b48Spatrick   switch (Loc) {
104209467b48Spatrick   case dwarf::DW_OP_entry_value:
104309467b48Spatrick     return dwarf::DW_OP_GNU_entry_value;
104409467b48Spatrick   default:
104509467b48Spatrick     llvm_unreachable("DWARF5 location atom with no GNU analog");
104609467b48Spatrick   }
104709467b48Spatrick }
104809467b48Spatrick 
1049*097a140dSpatrick DIE &DwarfCompileUnit::constructCallSiteEntryDIE(DIE &ScopeDIE,
1050*097a140dSpatrick                                                  DIE *CalleeDIE,
1051*097a140dSpatrick                                                  bool IsTail,
1052*097a140dSpatrick                                                  const MCSymbol *PCAddr,
1053*097a140dSpatrick                                                  const MCSymbol *CallAddr,
1054*097a140dSpatrick                                                  unsigned CallReg) {
105509467b48Spatrick   // Insert a call site entry DIE within ScopeDIE.
105609467b48Spatrick   DIE &CallSiteDIE = createAndAddDIE(getDwarf5OrGNUTag(dwarf::DW_TAG_call_site),
105709467b48Spatrick                                      ScopeDIE, nullptr);
105809467b48Spatrick 
105909467b48Spatrick   if (CallReg) {
106009467b48Spatrick     // Indirect call.
106109467b48Spatrick     addAddress(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_target),
106209467b48Spatrick                MachineLocation(CallReg));
106309467b48Spatrick   } else {
1064*097a140dSpatrick     assert(CalleeDIE && "No DIE for call site entry origin");
106509467b48Spatrick     addDIEEntry(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_origin),
106609467b48Spatrick                 *CalleeDIE);
106709467b48Spatrick   }
106809467b48Spatrick 
1069*097a140dSpatrick   if (IsTail) {
107009467b48Spatrick     // Attach DW_AT_call_tail_call to tail calls for standards compliance.
107109467b48Spatrick     addFlag(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_tail_call));
107209467b48Spatrick 
1073*097a140dSpatrick     // Attach the address of the branch instruction to allow the debugger to
1074*097a140dSpatrick     // show where the tail call occurred. This attribute has no GNU analog.
1075*097a140dSpatrick     //
1076*097a140dSpatrick     // GDB works backwards from non-standard usage of DW_AT_low_pc (in DWARF4
1077*097a140dSpatrick     // mode -- equivalently, in DWARF5 mode, DW_AT_call_return_pc) at tail-call
1078*097a140dSpatrick     // site entries to figure out the PC of tail-calling branch instructions.
1079*097a140dSpatrick     // This means it doesn't need the compiler to emit DW_AT_call_pc, so we
1080*097a140dSpatrick     // don't emit it here.
1081*097a140dSpatrick     //
1082*097a140dSpatrick     // There's no need to tie non-GDB debuggers to this non-standardness, as it
1083*097a140dSpatrick     // adds unnecessary complexity to the debugger. For non-GDB debuggers, emit
1084*097a140dSpatrick     // the standard DW_AT_call_pc info.
1085*097a140dSpatrick     if (!useGNUAnalogForDwarf5Feature())
1086*097a140dSpatrick       addLabelAddress(CallSiteDIE, dwarf::DW_AT_call_pc, CallAddr);
1087*097a140dSpatrick   }
1088*097a140dSpatrick 
108909467b48Spatrick   // Attach the return PC to allow the debugger to disambiguate call paths
109009467b48Spatrick   // from one function to another.
1091*097a140dSpatrick   //
1092*097a140dSpatrick   // The return PC is only really needed when the call /isn't/ a tail call, but
1093*097a140dSpatrick   // GDB expects it in DWARF4 mode, even for tail calls (see the comment above
1094*097a140dSpatrick   // the DW_AT_call_pc emission logic for an explanation).
1095*097a140dSpatrick   if (!IsTail || useGNUAnalogForDwarf5Feature()) {
1096*097a140dSpatrick     assert(PCAddr && "Missing return PC information for a call");
1097*097a140dSpatrick     addLabelAddress(CallSiteDIE,
1098*097a140dSpatrick                     getDwarf5OrGNUAttr(dwarf::DW_AT_call_return_pc), PCAddr);
109909467b48Spatrick   }
110009467b48Spatrick 
110109467b48Spatrick   return CallSiteDIE;
110209467b48Spatrick }
110309467b48Spatrick 
110409467b48Spatrick void DwarfCompileUnit::constructCallSiteParmEntryDIEs(
110509467b48Spatrick     DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) {
110609467b48Spatrick   for (const auto &Param : Params) {
110709467b48Spatrick     unsigned Register = Param.getRegister();
110809467b48Spatrick     auto CallSiteDieParam =
110909467b48Spatrick         DIE::get(DIEValueAllocator,
111009467b48Spatrick                  getDwarf5OrGNUTag(dwarf::DW_TAG_call_site_parameter));
111109467b48Spatrick     insertDIE(CallSiteDieParam);
111209467b48Spatrick     addAddress(*CallSiteDieParam, dwarf::DW_AT_location,
111309467b48Spatrick                MachineLocation(Register));
111409467b48Spatrick 
111509467b48Spatrick     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
111609467b48Spatrick     DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
111709467b48Spatrick     DwarfExpr.setCallSiteParamValueFlag();
111809467b48Spatrick 
111909467b48Spatrick     DwarfDebug::emitDebugLocValue(*Asm, nullptr, Param.getValue(), DwarfExpr);
112009467b48Spatrick 
112109467b48Spatrick     addBlock(*CallSiteDieParam, getDwarf5OrGNUAttr(dwarf::DW_AT_call_value),
112209467b48Spatrick              DwarfExpr.finalize());
112309467b48Spatrick 
112409467b48Spatrick     CallSiteDIE.addChild(CallSiteDieParam);
112509467b48Spatrick   }
112609467b48Spatrick }
112709467b48Spatrick 
112809467b48Spatrick DIE *DwarfCompileUnit::constructImportedEntityDIE(
112909467b48Spatrick     const DIImportedEntity *Module) {
113009467b48Spatrick   DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
113109467b48Spatrick   insertDIE(Module, IMDie);
113209467b48Spatrick   DIE *EntityDie;
113309467b48Spatrick   auto *Entity = Module->getEntity();
113409467b48Spatrick   if (auto *NS = dyn_cast<DINamespace>(Entity))
113509467b48Spatrick     EntityDie = getOrCreateNameSpace(NS);
113609467b48Spatrick   else if (auto *M = dyn_cast<DIModule>(Entity))
113709467b48Spatrick     EntityDie = getOrCreateModule(M);
113809467b48Spatrick   else if (auto *SP = dyn_cast<DISubprogram>(Entity))
113909467b48Spatrick     EntityDie = getOrCreateSubprogramDIE(SP);
114009467b48Spatrick   else if (auto *T = dyn_cast<DIType>(Entity))
114109467b48Spatrick     EntityDie = getOrCreateTypeDIE(T);
114209467b48Spatrick   else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
114309467b48Spatrick     EntityDie = getOrCreateGlobalVariableDIE(GV, {});
114409467b48Spatrick   else
114509467b48Spatrick     EntityDie = getDIE(Entity);
114609467b48Spatrick   assert(EntityDie);
114709467b48Spatrick   addSourceLine(*IMDie, Module->getLine(), Module->getFile());
114809467b48Spatrick   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
114909467b48Spatrick   StringRef Name = Module->getName();
115009467b48Spatrick   if (!Name.empty())
115109467b48Spatrick     addString(*IMDie, dwarf::DW_AT_name, Name);
115209467b48Spatrick 
115309467b48Spatrick   return IMDie;
115409467b48Spatrick }
115509467b48Spatrick 
115609467b48Spatrick void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
115709467b48Spatrick   DIE *D = getDIE(SP);
115809467b48Spatrick   if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
115909467b48Spatrick     if (D)
116009467b48Spatrick       // If this subprogram has an abstract definition, reference that
116109467b48Spatrick       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
116209467b48Spatrick   } else {
116309467b48Spatrick     assert(D || includeMinimalInlineScopes());
116409467b48Spatrick     if (D)
116509467b48Spatrick       // And attach the attributes
116609467b48Spatrick       applySubprogramAttributesToDefinition(SP, *D);
116709467b48Spatrick   }
116809467b48Spatrick }
116909467b48Spatrick 
117009467b48Spatrick void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
117109467b48Spatrick   DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
117209467b48Spatrick 
117309467b48Spatrick   auto *Die = Entity->getDIE();
117409467b48Spatrick   /// Label may be used to generate DW_AT_low_pc, so put it outside
117509467b48Spatrick   /// if/else block.
117609467b48Spatrick   const DbgLabel *Label = nullptr;
117709467b48Spatrick   if (AbsEntity && AbsEntity->getDIE()) {
117809467b48Spatrick     addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
117909467b48Spatrick     Label = dyn_cast<const DbgLabel>(Entity);
118009467b48Spatrick   } else {
118109467b48Spatrick     if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
118209467b48Spatrick       applyVariableAttributes(*Var, *Die);
118309467b48Spatrick     else if ((Label = dyn_cast<const DbgLabel>(Entity)))
118409467b48Spatrick       applyLabelAttributes(*Label, *Die);
118509467b48Spatrick     else
118609467b48Spatrick       llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
118709467b48Spatrick   }
118809467b48Spatrick 
118909467b48Spatrick   if (Label)
119009467b48Spatrick     if (const auto *Sym = Label->getSymbol())
119109467b48Spatrick       addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
119209467b48Spatrick }
119309467b48Spatrick 
119409467b48Spatrick DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
119509467b48Spatrick   auto &AbstractEntities = getAbstractEntities();
119609467b48Spatrick   auto I = AbstractEntities.find(Node);
119709467b48Spatrick   if (I != AbstractEntities.end())
119809467b48Spatrick     return I->second.get();
119909467b48Spatrick   return nullptr;
120009467b48Spatrick }
120109467b48Spatrick 
120209467b48Spatrick void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
120309467b48Spatrick                                             LexicalScope *Scope) {
120409467b48Spatrick   assert(Scope && Scope->isAbstractScope());
120509467b48Spatrick   auto &Entity = getAbstractEntities()[Node];
120609467b48Spatrick   if (isa<const DILocalVariable>(Node)) {
120709467b48Spatrick     Entity = std::make_unique<DbgVariable>(
120809467b48Spatrick                         cast<const DILocalVariable>(Node), nullptr /* IA */);;
120909467b48Spatrick     DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
121009467b48Spatrick   } else if (isa<const DILabel>(Node)) {
121109467b48Spatrick     Entity = std::make_unique<DbgLabel>(
121209467b48Spatrick                         cast<const DILabel>(Node), nullptr /* IA */);
121309467b48Spatrick     DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
121409467b48Spatrick   }
121509467b48Spatrick }
121609467b48Spatrick 
121709467b48Spatrick void DwarfCompileUnit::emitHeader(bool UseOffsets) {
121809467b48Spatrick   // Don't bother labeling the .dwo unit, as its offset isn't used.
121909467b48Spatrick   if (!Skeleton && !DD->useSectionsAsReferences()) {
122009467b48Spatrick     LabelBegin = Asm->createTempSymbol("cu_begin");
1221*097a140dSpatrick     Asm->OutStreamer->emitLabel(LabelBegin);
122209467b48Spatrick   }
122309467b48Spatrick 
122409467b48Spatrick   dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
122509467b48Spatrick                                 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
122609467b48Spatrick                                                       : dwarf::DW_UT_compile;
122709467b48Spatrick   DwarfUnit::emitCommonHeader(UseOffsets, UT);
122809467b48Spatrick   if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
122909467b48Spatrick     Asm->emitInt64(getDWOId());
123009467b48Spatrick }
123109467b48Spatrick 
123209467b48Spatrick bool DwarfCompileUnit::hasDwarfPubSections() const {
123309467b48Spatrick   switch (CUNode->getNameTableKind()) {
123409467b48Spatrick   case DICompileUnit::DebugNameTableKind::None:
123509467b48Spatrick     return false;
123609467b48Spatrick     // Opting in to GNU Pubnames/types overrides the default to ensure these are
123709467b48Spatrick     // generated for things like Gold's gdb_index generation.
123809467b48Spatrick   case DICompileUnit::DebugNameTableKind::GNU:
123909467b48Spatrick     return true;
124009467b48Spatrick   case DICompileUnit::DebugNameTableKind::Default:
124109467b48Spatrick     return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
124209467b48Spatrick            !CUNode->isDebugDirectivesOnly() &&
124309467b48Spatrick            DD->getAccelTableKind() != AccelTableKind::Apple &&
124409467b48Spatrick            DD->getDwarfVersion() < 5;
124509467b48Spatrick   }
124609467b48Spatrick   llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
124709467b48Spatrick }
124809467b48Spatrick 
124909467b48Spatrick /// addGlobalName - Add a new global name to the compile unit.
125009467b48Spatrick void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
125109467b48Spatrick                                      const DIScope *Context) {
125209467b48Spatrick   if (!hasDwarfPubSections())
125309467b48Spatrick     return;
125409467b48Spatrick   std::string FullName = getParentContextString(Context) + Name.str();
125509467b48Spatrick   GlobalNames[FullName] = &Die;
125609467b48Spatrick }
125709467b48Spatrick 
125809467b48Spatrick void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
125909467b48Spatrick                                                 const DIScope *Context) {
126009467b48Spatrick   if (!hasDwarfPubSections())
126109467b48Spatrick     return;
126209467b48Spatrick   std::string FullName = getParentContextString(Context) + Name.str();
126309467b48Spatrick   // Insert, allowing the entry to remain as-is if it's already present
126409467b48Spatrick   // This way the CU-level type DIE is preferred over the "can't describe this
126509467b48Spatrick   // type as a unit offset because it's not really in the CU at all, it's only
126609467b48Spatrick   // in a type unit"
126709467b48Spatrick   GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
126809467b48Spatrick }
126909467b48Spatrick 
127009467b48Spatrick /// Add a new global type to the unit.
127109467b48Spatrick void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
127209467b48Spatrick                                      const DIScope *Context) {
127309467b48Spatrick   if (!hasDwarfPubSections())
127409467b48Spatrick     return;
127509467b48Spatrick   std::string FullName = getParentContextString(Context) + Ty->getName().str();
127609467b48Spatrick   GlobalTypes[FullName] = &Die;
127709467b48Spatrick }
127809467b48Spatrick 
127909467b48Spatrick void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
128009467b48Spatrick                                              const DIScope *Context) {
128109467b48Spatrick   if (!hasDwarfPubSections())
128209467b48Spatrick     return;
128309467b48Spatrick   std::string FullName = getParentContextString(Context) + Ty->getName().str();
128409467b48Spatrick   // Insert, allowing the entry to remain as-is if it's already present
128509467b48Spatrick   // This way the CU-level type DIE is preferred over the "can't describe this
128609467b48Spatrick   // type as a unit offset because it's not really in the CU at all, it's only
128709467b48Spatrick   // in a type unit"
128809467b48Spatrick   GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
128909467b48Spatrick }
129009467b48Spatrick 
129109467b48Spatrick void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
129209467b48Spatrick                                           MachineLocation Location) {
129309467b48Spatrick   if (DV.hasComplexAddress())
129409467b48Spatrick     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
129509467b48Spatrick   else
129609467b48Spatrick     addAddress(Die, dwarf::DW_AT_location, Location);
129709467b48Spatrick }
129809467b48Spatrick 
129909467b48Spatrick /// Add an address attribute to a die based on the location provided.
130009467b48Spatrick void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
130109467b48Spatrick                                   const MachineLocation &Location) {
130209467b48Spatrick   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
130309467b48Spatrick   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
130409467b48Spatrick   if (Location.isIndirect())
130509467b48Spatrick     DwarfExpr.setMemoryLocationKind();
130609467b48Spatrick 
130709467b48Spatrick   DIExpressionCursor Cursor({});
130809467b48Spatrick   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
130909467b48Spatrick   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
131009467b48Spatrick     return;
131109467b48Spatrick   DwarfExpr.addExpression(std::move(Cursor));
131209467b48Spatrick 
131309467b48Spatrick   // Now attach the location information to the DIE.
131409467b48Spatrick   addBlock(Die, Attribute, DwarfExpr.finalize());
131509467b48Spatrick 
131609467b48Spatrick   if (DwarfExpr.TagOffset)
131709467b48Spatrick     addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
131809467b48Spatrick             *DwarfExpr.TagOffset);
131909467b48Spatrick }
132009467b48Spatrick 
132109467b48Spatrick /// Start with the address based on the location provided, and generate the
132209467b48Spatrick /// DWARF information necessary to find the actual variable given the extra
132309467b48Spatrick /// address information encoded in the DbgVariable, starting from the starting
132409467b48Spatrick /// location.  Add the DWARF information to the die.
132509467b48Spatrick void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
132609467b48Spatrick                                          dwarf::Attribute Attribute,
132709467b48Spatrick                                          const MachineLocation &Location) {
132809467b48Spatrick   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
132909467b48Spatrick   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
133009467b48Spatrick   const DIExpression *DIExpr = DV.getSingleExpression();
133109467b48Spatrick   DwarfExpr.addFragmentOffset(DIExpr);
1332*097a140dSpatrick   DwarfExpr.setLocation(Location, DIExpr);
133309467b48Spatrick 
133409467b48Spatrick   DIExpressionCursor Cursor(DIExpr);
133509467b48Spatrick 
1336*097a140dSpatrick   if (DIExpr->isEntryValue())
133709467b48Spatrick     DwarfExpr.beginEntryValueExpression(Cursor);
133809467b48Spatrick 
133909467b48Spatrick   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
134009467b48Spatrick   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
134109467b48Spatrick     return;
134209467b48Spatrick   DwarfExpr.addExpression(std::move(Cursor));
134309467b48Spatrick 
134409467b48Spatrick   // Now attach the location information to the DIE.
134509467b48Spatrick   addBlock(Die, Attribute, DwarfExpr.finalize());
134609467b48Spatrick 
134709467b48Spatrick   if (DwarfExpr.TagOffset)
134809467b48Spatrick     addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
134909467b48Spatrick             *DwarfExpr.TagOffset);
135009467b48Spatrick }
135109467b48Spatrick 
135209467b48Spatrick /// Add a Dwarf loclistptr attribute data and value.
135309467b48Spatrick void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
135409467b48Spatrick                                        unsigned Index) {
135509467b48Spatrick   dwarf::Form Form = dwarf::DW_FORM_data4;
135609467b48Spatrick   if (DD->getDwarfVersion() == 4)
135709467b48Spatrick     Form =dwarf::DW_FORM_sec_offset;
135809467b48Spatrick   if (DD->getDwarfVersion() >= 5)
135909467b48Spatrick     Form =dwarf::DW_FORM_loclistx;
136009467b48Spatrick   Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
136109467b48Spatrick }
136209467b48Spatrick 
136309467b48Spatrick void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
136409467b48Spatrick                                                DIE &VariableDie) {
136509467b48Spatrick   StringRef Name = Var.getName();
136609467b48Spatrick   if (!Name.empty())
136709467b48Spatrick     addString(VariableDie, dwarf::DW_AT_name, Name);
136809467b48Spatrick   const auto *DIVar = Var.getVariable();
136909467b48Spatrick   if (DIVar)
137009467b48Spatrick     if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
137109467b48Spatrick       addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
137209467b48Spatrick               AlignInBytes);
137309467b48Spatrick 
137409467b48Spatrick   addSourceLine(VariableDie, DIVar);
137509467b48Spatrick   addType(VariableDie, Var.getType());
137609467b48Spatrick   if (Var.isArtificial())
137709467b48Spatrick     addFlag(VariableDie, dwarf::DW_AT_artificial);
137809467b48Spatrick }
137909467b48Spatrick 
138009467b48Spatrick void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
138109467b48Spatrick                                             DIE &LabelDie) {
138209467b48Spatrick   StringRef Name = Label.getName();
138309467b48Spatrick   if (!Name.empty())
138409467b48Spatrick     addString(LabelDie, dwarf::DW_AT_name, Name);
138509467b48Spatrick   const auto *DILabel = Label.getLabel();
138609467b48Spatrick   addSourceLine(LabelDie, DILabel);
138709467b48Spatrick }
138809467b48Spatrick 
138909467b48Spatrick /// Add a Dwarf expression attribute data and value.
139009467b48Spatrick void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
139109467b48Spatrick                                const MCExpr *Expr) {
139209467b48Spatrick   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
139309467b48Spatrick }
139409467b48Spatrick 
139509467b48Spatrick void DwarfCompileUnit::applySubprogramAttributesToDefinition(
139609467b48Spatrick     const DISubprogram *SP, DIE &SPDie) {
139709467b48Spatrick   auto *SPDecl = SP->getDeclaration();
139809467b48Spatrick   auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope();
139909467b48Spatrick   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
140009467b48Spatrick   addGlobalName(SP->getName(), SPDie, Context);
140109467b48Spatrick }
140209467b48Spatrick 
140309467b48Spatrick bool DwarfCompileUnit::isDwoUnit() const {
140409467b48Spatrick   return DD->useSplitDwarf() && Skeleton;
140509467b48Spatrick }
140609467b48Spatrick 
140709467b48Spatrick void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
140809467b48Spatrick   constructTypeDIE(D, CTy);
140909467b48Spatrick }
141009467b48Spatrick 
141109467b48Spatrick bool DwarfCompileUnit::includeMinimalInlineScopes() const {
141209467b48Spatrick   return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
141309467b48Spatrick          (DD->useSplitDwarf() && !Skeleton);
141409467b48Spatrick }
141509467b48Spatrick 
141609467b48Spatrick void DwarfCompileUnit::addAddrTableBase() {
141709467b48Spatrick   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
141809467b48Spatrick   MCSymbol *Label = DD->getAddressPool().getLabel();
141909467b48Spatrick   addSectionLabel(getUnitDie(),
142009467b48Spatrick                   getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
142109467b48Spatrick                                          : dwarf::DW_AT_GNU_addr_base,
142209467b48Spatrick                   Label, TLOF.getDwarfAddrSection()->getBeginSymbol());
142309467b48Spatrick }
142409467b48Spatrick 
142509467b48Spatrick void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) {
142609467b48Spatrick   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, dwarf::DW_FORM_udata,
142709467b48Spatrick                new (DIEValueAllocator) DIEBaseTypeRef(this, Idx));
142809467b48Spatrick }
142909467b48Spatrick 
143009467b48Spatrick void DwarfCompileUnit::createBaseTypeDIEs() {
143109467b48Spatrick   // Insert the base_type DIEs directly after the CU so that their offsets will
143209467b48Spatrick   // fit in the fixed size ULEB128 used inside the location expressions.
143309467b48Spatrick   // Maintain order by iterating backwards and inserting to the front of CU
143409467b48Spatrick   // child list.
143509467b48Spatrick   for (auto &Btr : reverse(ExprRefedBaseTypes)) {
143609467b48Spatrick     DIE &Die = getUnitDie().addChildFront(
143709467b48Spatrick       DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type));
143809467b48Spatrick     SmallString<32> Str;
143909467b48Spatrick     addString(Die, dwarf::DW_AT_name,
144009467b48Spatrick               Twine(dwarf::AttributeEncodingString(Btr.Encoding) +
144109467b48Spatrick                     "_" + Twine(Btr.BitSize)).toStringRef(Str));
144209467b48Spatrick     addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding);
144309467b48Spatrick     addUInt(Die, dwarf::DW_AT_byte_size, None, Btr.BitSize / 8);
144409467b48Spatrick 
144509467b48Spatrick     Btr.Die = &Die;
144609467b48Spatrick   }
144709467b48Spatrick }
1448