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