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