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