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