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