13443575cSPaul Robinson //===-- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Units -----------===//
23443575cSPaul Robinson //
33443575cSPaul Robinson //                     The LLVM Compiler Infrastructure
43443575cSPaul Robinson //
53443575cSPaul Robinson // This file is distributed under the University of Illinois Open Source
63443575cSPaul Robinson // License. See LICENSE.TXT for details.
73443575cSPaul Robinson //
83443575cSPaul Robinson //===----------------------------------------------------------------------===//
93443575cSPaul Robinson //
103443575cSPaul Robinson // This file contains support for constructing a dwarf compile unit.
113443575cSPaul Robinson //
123443575cSPaul Robinson //===----------------------------------------------------------------------===//
133443575cSPaul Robinson 
1437c52310SDavid Blaikie #include "DwarfCompileUnit.h"
157813d9c9SAdrian Prantl #include "DwarfExpression.h"
16cda2aa82SDavid Blaikie #include "llvm/CodeGen/MachineFunction.h"
17364a3005SDuncan P. N. Exon Smith #include "llvm/IR/Constants.h"
1837c52310SDavid Blaikie #include "llvm/IR/DataLayout.h"
1937c52310SDavid Blaikie #include "llvm/IR/GlobalValue.h"
2037c52310SDavid Blaikie #include "llvm/IR/GlobalVariable.h"
2137c52310SDavid Blaikie #include "llvm/IR/Instruction.h"
2237c52310SDavid Blaikie #include "llvm/MC/MCAsmInfo.h"
2337c52310SDavid Blaikie #include "llvm/MC/MCStreamer.h"
24ee7df553SDavid Blaikie #include "llvm/Target/TargetFrameLowering.h"
2537c52310SDavid Blaikie #include "llvm/Target/TargetLoweringObjectFile.h"
26cda2aa82SDavid Blaikie #include "llvm/Target/TargetMachine.h"
27cda2aa82SDavid Blaikie #include "llvm/Target/TargetRegisterInfo.h"
28d9903888SChandler Carruth #include "llvm/Target/TargetSubtargetInfo.h"
2937c52310SDavid Blaikie 
3037c52310SDavid Blaikie namespace llvm {
3137c52310SDavid Blaikie 
32a9308c49SDuncan P. N. Exon Smith DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
3337c52310SDavid Blaikie                                    AsmPrinter *A, DwarfDebug *DW,
3437c52310SDavid Blaikie                                    DwarfFile *DWU)
357c384cceSPeter Collingbourne     : DwarfUnit(dwarf::DW_TAG_compile_unit, Node, A, DW, DWU), UniqueID(UID),
36063d725fSRafael Espindola       Skeleton(nullptr), BaseAddress(nullptr) {
3737c52310SDavid Blaikie   insertDIE(Node, &getUnitDie());
388bbce8adSAmjad Aboud   MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
3937c52310SDavid Blaikie }
4037c52310SDavid Blaikie 
4137c52310SDavid Blaikie /// addLabelAddress - Add a dwarf label attribute data and value using
4237c52310SDavid Blaikie /// DW_FORM_addr or DW_FORM_GNU_addr_index.
4337c52310SDavid Blaikie ///
4437c52310SDavid Blaikie void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
4537c52310SDavid Blaikie                                        const MCSymbol *Label) {
4637c52310SDavid Blaikie 
4737c52310SDavid Blaikie   // Don't use the address pool in non-fission or in the skeleton unit itself.
4837c52310SDavid Blaikie   // FIXME: Once GDB supports this, it's probably worthwhile using the address
4937c52310SDavid Blaikie   // pool from the skeleton - maybe even in non-fission (possibly fewer
5037c52310SDavid Blaikie   // relocations by sharing them in the pool, but we have other ideas about how
5137c52310SDavid Blaikie   // to reduce the number of relocations as well/instead).
5237c52310SDavid Blaikie   if (!DD->useSplitDwarf() || !Skeleton)
5337c52310SDavid Blaikie     return addLocalLabelAddress(Die, Attribute, Label);
5437c52310SDavid Blaikie 
5537c52310SDavid Blaikie   if (Label)
5637c52310SDavid Blaikie     DD->addArangeLabel(SymbolCU(this, Label));
5737c52310SDavid Blaikie 
5837c52310SDavid Blaikie   unsigned idx = DD->getAddressPool().getIndex(Label);
594fb1f9cdSDuncan P. N. Exon Smith   Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_GNU_addr_index,
604fb1f9cdSDuncan P. N. Exon Smith                DIEInteger(idx));
6137c52310SDavid Blaikie }
6237c52310SDavid Blaikie 
6337c52310SDavid Blaikie void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
6437c52310SDavid Blaikie                                             dwarf::Attribute Attribute,
6537c52310SDavid Blaikie                                             const MCSymbol *Label) {
6637c52310SDavid Blaikie   if (Label)
6737c52310SDavid Blaikie     DD->addArangeLabel(SymbolCU(this, Label));
6837c52310SDavid Blaikie 
69815a6eb5SDuncan P. N. Exon Smith   if (Label)
704fb1f9cdSDuncan P. N. Exon Smith     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
714fb1f9cdSDuncan P. N. Exon Smith                  DIELabel(Label));
72815a6eb5SDuncan P. N. Exon Smith   else
734fb1f9cdSDuncan P. N. Exon Smith     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
744fb1f9cdSDuncan P. N. Exon Smith                  DIEInteger(0));
7537c52310SDavid Blaikie }
7637c52310SDavid Blaikie 
778945219dSDavid Blaikie unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName,
788945219dSDavid Blaikie                                                StringRef DirName) {
7937c52310SDavid Blaikie   // If we print assembly, we can't separate .file entries according to
8037c52310SDavid Blaikie   // compile units. Thus all files will belong to the default compile unit.
8137c52310SDavid Blaikie 
8237c52310SDavid Blaikie   // FIXME: add a better feature test than hasRawTextSupport. Even better,
8337c52310SDavid Blaikie   // extend .file to support this.
849ff69c8fSLang Hames   return Asm->OutStreamer->EmitDwarfFileDirective(
8537c52310SDavid Blaikie       0, DirName, FileName,
869ff69c8fSLang Hames       Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID());
8737c52310SDavid Blaikie }
8837c52310SDavid Blaikie 
8960635e39SDuncan P. N. Exon Smith DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
90bceaaa96SAdrian Prantl     const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
9137c52310SDavid Blaikie   // Check for pre-existence.
9237c52310SDavid Blaikie   if (DIE *Die = getDIE(GV))
9337c52310SDavid Blaikie     return Die;
9437c52310SDavid Blaikie 
95e686f159SDuncan P. N. Exon Smith   assert(GV);
9637c52310SDavid Blaikie 
97be9e4fe7SDuncan P. N. Exon Smith   auto *GVContext = GV->getScope();
98be9e4fe7SDuncan P. N. Exon Smith   auto *GTy = DD->resolve(GV->getType());
9937c52310SDavid Blaikie 
10037c52310SDavid Blaikie   // Construct the context before querying for the existence of the DIE in
10137c52310SDavid Blaikie   // case such construction creates the DIE.
10272da9391SAmjad Aboud   DIE *ContextDIE = getOrCreateContextDIE(GVContext);
10337c52310SDavid Blaikie 
10472da9391SAmjad Aboud   // Add to map.
10572da9391SAmjad Aboud   DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
106a9308c49SDuncan P. N. Exon Smith   DIScope *DeclContext;
107b1055640SDuncan P. N. Exon Smith   if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
108b1055640SDuncan P. N. Exon Smith     DeclContext = resolve(SDMDecl->getScope());
109b1055640SDuncan P. N. Exon Smith     assert(SDMDecl->isStaticMember() && "Expected static member decl");
1107348ddaaSDuncan P. N. Exon Smith     assert(GV->isDefinition());
11149cfc8caSDavid Blaikie     // We need the declaration DIE that is in the static member's class.
11249cfc8caSDavid Blaikie     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
11349cfc8caSDavid Blaikie     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
1143502f208SAdrian Prantl     // If the global variable's type is different from the one in the class
1153502f208SAdrian Prantl     // member type, assume that it's more specific and also emit it.
1163502f208SAdrian Prantl     if (GTy != DD->resolve(SDMDecl->getBaseType()))
1173502f208SAdrian Prantl       addType(*VariableDIE, GTy);
11849cfc8caSDavid Blaikie   } else {
1197348ddaaSDuncan P. N. Exon Smith     DeclContext = GV->getScope();
12037c52310SDavid Blaikie     // Add name and type.
1217348ddaaSDuncan P. N. Exon Smith     addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
12237c52310SDavid Blaikie     addType(*VariableDIE, GTy);
12337c52310SDavid Blaikie 
12437c52310SDavid Blaikie     // Add scoping info.
1257348ddaaSDuncan P. N. Exon Smith     if (!GV->isLocalToUnit())
12637c52310SDavid Blaikie       addFlag(*VariableDIE, dwarf::DW_AT_external);
12737c52310SDavid Blaikie 
12837c52310SDavid Blaikie     // Add line number info.
12937c52310SDavid Blaikie     addSourceLine(*VariableDIE, GV);
13037c52310SDavid Blaikie   }
13137c52310SDavid Blaikie 
1327348ddaaSDuncan P. N. Exon Smith   if (!GV->isDefinition())
13349cfc8caSDavid Blaikie     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
134877354a2SDavid Blaikie   else
135877354a2SDavid Blaikie     addGlobalName(GV->getName(), *VariableDIE, DeclContext);
13649cfc8caSDavid Blaikie 
1373c989984SVictor Leschuk   if (uint32_t AlignInBytes = GV->getAlignInBytes())
1383c989984SVictor Leschuk     addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1393c989984SVictor Leschuk             AlignInBytes);
1403c989984SVictor Leschuk 
14137c52310SDavid Blaikie   // Add location.
14237c52310SDavid Blaikie   bool addToAccelTable = false;
143bceaaa96SAdrian Prantl   DIELoc *Loc = nullptr;
144bceaaa96SAdrian Prantl   std::unique_ptr<DIEDwarfExpression> DwarfExpr;
145bceaaa96SAdrian Prantl   for (const auto &GE : GlobalExprs) {
146bceaaa96SAdrian Prantl     const GlobalVariable *Global = GE.Var;
147bceaaa96SAdrian Prantl     const DIExpression *Expr = GE.Expr;
148b216e3e9SAdrian Prantl 
149d4135bbcSPeter Collingbourne     // For compatibility with DWARF 3 and earlier,
150d4135bbcSPeter Collingbourne     // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) becomes
151d4135bbcSPeter Collingbourne     // DW_AT_const_value(X).
152bceaaa96SAdrian Prantl     if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
153b216e3e9SAdrian Prantl       addToAccelTable = true;
154d4135bbcSPeter Collingbourne       addConstantValue(*VariableDIE, /*Unsigned=*/true, Expr->getElement(1));
155b216e3e9SAdrian Prantl       break;
156b216e3e9SAdrian Prantl     }
157b216e3e9SAdrian Prantl 
158bceaaa96SAdrian Prantl     // We cannot describe the location of dllimport'd variables: the
159bceaaa96SAdrian Prantl     // computation of their address requires loads from the IAT.
160b216e3e9SAdrian Prantl     if (Global && Global->hasDLLImportStorageClass())
161b216e3e9SAdrian Prantl       continue;
162b216e3e9SAdrian Prantl 
163b216e3e9SAdrian Prantl     // Nothing to describe without address or constant.
164b216e3e9SAdrian Prantl     if (!Global && (!Expr || !Expr->isConstant()))
165b216e3e9SAdrian Prantl       continue;
166b216e3e9SAdrian Prantl 
167bceaaa96SAdrian Prantl     if (!Loc) {
168b216e3e9SAdrian Prantl       addToAccelTable = true;
169bceaaa96SAdrian Prantl       Loc = new (DIEValueAllocator) DIELoc;
170bceaaa96SAdrian Prantl       DwarfExpr = llvm::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
171bceaaa96SAdrian Prantl     }
172b216e3e9SAdrian Prantl 
173bceaaa96SAdrian Prantl     if (Global) {
174cca5f68eSDuncan P. N. Exon Smith       const MCSymbol *Sym = Asm->getSymbol(Global);
175cca5f68eSDuncan P. N. Exon Smith       if (Global->isThreadLocal()) {
1761e859582SChih-Hung Hsieh         if (Asm->TM.Options.EmulatedTLS) {
1771e859582SChih-Hung Hsieh           // TODO: add debug info for emulated thread local mode.
1781e859582SChih-Hung Hsieh         } else {
17937c52310SDavid Blaikie           // FIXME: Make this work with -gsplit-dwarf.
18037c52310SDavid Blaikie           unsigned PointerSize = Asm->getDataLayout().getPointerSize();
18137c52310SDavid Blaikie           assert((PointerSize == 4 || PointerSize == 8) &&
18237c52310SDavid Blaikie                  "Add support for other sizes if necessary");
18337c52310SDavid Blaikie           // Based on GCC's support for TLS:
18437c52310SDavid Blaikie           if (!DD->useSplitDwarf()) {
18537c52310SDavid Blaikie             // 1) Start with a constNu of the appropriate pointer size
186bceaaa96SAdrian Prantl             addUInt(*Loc, dwarf::DW_FORM_data1,
187bceaaa96SAdrian Prantl                     PointerSize == 4 ? dwarf::DW_OP_const4u
18854511353SDehao Chen                                      : dwarf::DW_OP_const8u);
18937c52310SDavid Blaikie             // 2) containing the (relocated) offset of the TLS variable
19037c52310SDavid Blaikie             //    within the module's TLS block.
19137c52310SDavid Blaikie             addExpr(*Loc, dwarf::DW_FORM_udata,
19237c52310SDavid Blaikie                     Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
19337c52310SDavid Blaikie           } else {
19437c52310SDavid Blaikie             addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
19537c52310SDavid Blaikie             addUInt(*Loc, dwarf::DW_FORM_udata,
19637c52310SDavid Blaikie                     DD->getAddressPool().getIndex(Sym, /* TLS */ true));
19737c52310SDavid Blaikie           }
19878cc0821SPaul Robinson           // 3) followed by an OP to make the debugger do a TLS lookup.
19978cc0821SPaul Robinson           addUInt(*Loc, dwarf::DW_FORM_data1,
20078cc0821SPaul Robinson                   DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
20178cc0821SPaul Robinson                                         : dwarf::DW_OP_form_tls_address);
2021e859582SChih-Hung Hsieh         }
20337c52310SDavid Blaikie       } else {
20437c52310SDavid Blaikie         DD->addArangeLabel(SymbolCU(this, Sym));
20537c52310SDavid Blaikie         addOpAddress(*Loc, Sym);
20637c52310SDavid Blaikie       }
207bceaaa96SAdrian Prantl     }
208d4135bbcSPeter Collingbourne     if (Expr) {
209bceaaa96SAdrian Prantl       DwarfExpr->addFragmentOffset(Expr);
210a63b8e82SAdrian Prantl       DwarfExpr->addExpression(Expr);
211d4135bbcSPeter Collingbourne     }
212d4135bbcSPeter Collingbourne   }
213bceaaa96SAdrian Prantl   if (Loc)
214bceaaa96SAdrian Prantl     addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
215d4135bbcSPeter Collingbourne 
21643d1e453SPaul Robinson   if (DD->useAllLinkageNames())
2177348ddaaSDuncan P. N. Exon Smith     addLinkageName(*VariableDIE, GV->getLinkageName());
21837c52310SDavid Blaikie 
21937c52310SDavid Blaikie   if (addToAccelTable) {
2207348ddaaSDuncan P. N. Exon Smith     DD->addAccelName(GV->getName(), *VariableDIE);
22137c52310SDavid Blaikie 
22237c52310SDavid Blaikie     // If the linkage name is different than the name, go ahead and output
22337c52310SDavid Blaikie     // that as well into the name table.
2247348ddaaSDuncan P. N. Exon Smith     if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName())
2257348ddaaSDuncan P. N. Exon Smith       DD->addAccelName(GV->getLinkageName(), *VariableDIE);
22637c52310SDavid Blaikie   }
22737c52310SDavid Blaikie 
22849cfc8caSDavid Blaikie   return VariableDIE;
22937c52310SDavid Blaikie }
23037c52310SDavid Blaikie 
23137c52310SDavid Blaikie void DwarfCompileUnit::addRange(RangeSpan Range) {
23237c52310SDavid Blaikie   bool SameAsPrevCU = this == DD->getPrevCU();
23337c52310SDavid Blaikie   DD->setPrevCU(this);
23437c52310SDavid Blaikie   // If we have no current ranges just add the range and return, otherwise,
23537c52310SDavid Blaikie   // check the current section and CU against the previous section and CU we
23637c52310SDavid Blaikie   // emitted into and the subprogram was contained within. If these are the
23737c52310SDavid Blaikie   // same then extend our current range, otherwise add this as a new range.
23837c52310SDavid Blaikie   if (CURanges.empty() || !SameAsPrevCU ||
23937c52310SDavid Blaikie       (&CURanges.back().getEnd()->getSection() !=
24037c52310SDavid Blaikie        &Range.getEnd()->getSection())) {
24137c52310SDavid Blaikie     CURanges.push_back(Range);
24237c52310SDavid Blaikie     return;
24337c52310SDavid Blaikie   }
24437c52310SDavid Blaikie 
24537c52310SDavid Blaikie   CURanges.back().setEnd(Range.getEnd());
24637c52310SDavid Blaikie }
24737c52310SDavid Blaikie 
248063d725fSRafael Espindola void DwarfCompileUnit::initStmtList() {
24937c52310SDavid Blaikie   // Define start line table label for each Compile Unit.
25037c52310SDavid Blaikie   MCSymbol *LineTableStartSym =
2519ff69c8fSLang Hames       Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
25237c52310SDavid Blaikie 
25337c52310SDavid Blaikie   // DW_AT_stmt_list is a offset of line number information for this
25437c52310SDavid Blaikie   // compile unit in debug_line section. For split dwarf this is
25537c52310SDavid Blaikie   // left in the skeleton CU and so not included.
25637c52310SDavid Blaikie   // The line table entries are not always emitted in assembly, so it
25737c52310SDavid Blaikie   // is not okay to use line_table_start here.
258063d725fSRafael Espindola   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2594fb1f9cdSDuncan P. N. Exon Smith   StmtListValue =
26035630c33SGreg Clayton       addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
261063d725fSRafael Espindola                       TLOF.getDwarfLineSection()->getBeginSymbol());
26237c52310SDavid Blaikie }
26337c52310SDavid Blaikie 
26437c52310SDavid Blaikie void DwarfCompileUnit::applyStmtList(DIE &D) {
2654fb1f9cdSDuncan P. N. Exon Smith   D.addValue(DIEValueAllocator, *StmtListValue);
26637c52310SDavid Blaikie }
26737c52310SDavid Blaikie 
26814499a7dSDavid Blaikie void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
26914499a7dSDavid Blaikie                                        const MCSymbol *End) {
27014499a7dSDavid Blaikie   assert(Begin && "Begin label should not be null!");
27114499a7dSDavid Blaikie   assert(End && "End label should not be null!");
27214499a7dSDavid Blaikie   assert(Begin->isDefined() && "Invalid starting label");
27314499a7dSDavid Blaikie   assert(End->isDefined() && "Invalid end label");
27414499a7dSDavid Blaikie 
27514499a7dSDavid Blaikie   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
27614499a7dSDavid Blaikie   if (DD->getDwarfVersion() < 4)
27714499a7dSDavid Blaikie     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
27814499a7dSDavid Blaikie   else
27914499a7dSDavid Blaikie     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
28014499a7dSDavid Blaikie }
28114499a7dSDavid Blaikie 
282cda2aa82SDavid Blaikie // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
283cda2aa82SDavid Blaikie // and DW_AT_high_pc attributes. If there are global variables in this
284cda2aa82SDavid Blaikie // scope then create and insert DIEs for these variables.
285a9308c49SDuncan P. N. Exon Smith DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
2863a443c29SDavid Blaikie   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
287cda2aa82SDavid Blaikie 
28807c03d31SRafael Espindola   attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd());
289c53e18d9SDavid Blaikie   if (DD->useAppleExtensionAttributes() &&
290c53e18d9SDavid Blaikie       !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
291cda2aa82SDavid Blaikie           *DD->getCurrentFunction()))
292cda2aa82SDavid Blaikie     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
293cda2aa82SDavid Blaikie 
294cda2aa82SDavid Blaikie   // Only include DW_AT_frame_base in full debug info
2953a443c29SDavid Blaikie   if (!includeMinimalInlineScopes()) {
296d4e723f2SEric Christopher     const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo();
297cda2aa82SDavid Blaikie     MachineLocation Location(RI->getFrameRegister(*Asm->MF));
2988efadbf8SAdrian Prantl     if (RI->isPhysicalRegister(Location.getReg()))
299cda2aa82SDavid Blaikie       addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
300cda2aa82SDavid Blaikie   }
301cda2aa82SDavid Blaikie 
302cda2aa82SDavid Blaikie   // Add name to the name table, we do this here because we're guaranteed
303cda2aa82SDavid Blaikie   // to have concrete versions of our DW_TAG_subprogram nodes.
304cda2aa82SDavid Blaikie   DD->addSubprogramNames(SP, *SPDie);
305cda2aa82SDavid Blaikie 
306cda2aa82SDavid Blaikie   return *SPDie;
307cda2aa82SDavid Blaikie }
308cda2aa82SDavid Blaikie 
3099c65b135SDavid Blaikie // Construct a DIE for this scope.
3109c65b135SDavid Blaikie void DwarfCompileUnit::constructScopeDIE(
311827200c8SDuncan P. N. Exon Smith     LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
3129c65b135SDavid Blaikie   if (!Scope || !Scope->getScopeNode())
3139c65b135SDavid Blaikie     return;
3149c65b135SDavid Blaikie 
315be9e4fe7SDuncan P. N. Exon Smith   auto *DS = Scope->getScopeNode();
3169c65b135SDavid Blaikie 
317a9308c49SDuncan P. N. Exon Smith   assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
3189c65b135SDavid Blaikie          "Only handle inlined subprograms here, use "
3199c65b135SDavid Blaikie          "constructSubprogramScopeDIE for non-inlined "
3209c65b135SDavid Blaikie          "subprograms");
3219c65b135SDavid Blaikie 
322827200c8SDuncan P. N. Exon Smith   SmallVector<DIE *, 8> Children;
3239c65b135SDavid Blaikie 
3249c65b135SDavid Blaikie   // We try to create the scope DIE first, then the children DIEs. This will
3259c65b135SDavid Blaikie   // avoid creating un-used children then removing them later when we find out
3269c65b135SDavid Blaikie   // the scope DIE is null.
327827200c8SDuncan P. N. Exon Smith   DIE *ScopeDIE;
328a9308c49SDuncan P. N. Exon Smith   if (Scope->getParent() && isa<DISubprogram>(DS)) {
32901b48a84SDavid Blaikie     ScopeDIE = constructInlinedScopeDIE(Scope);
3309c65b135SDavid Blaikie     if (!ScopeDIE)
3319c65b135SDavid Blaikie       return;
3329c65b135SDavid Blaikie     // We create children when the scope DIE is not null.
3338b2fdb83SDavid Blaikie     createScopeChildrenDIE(Scope, Children);
3349c65b135SDavid Blaikie   } else {
3359c65b135SDavid Blaikie     // Early exit when we know the scope DIE is going to be null.
3369c65b135SDavid Blaikie     if (DD->isLexicalScopeDIENull(Scope))
3379c65b135SDavid Blaikie       return;
3389c65b135SDavid Blaikie 
339*2195e136SDavid Blaikie     bool HasNonScopeChildren = false;
3409c65b135SDavid Blaikie 
3419c65b135SDavid Blaikie     // We create children here when we know the scope DIE is not going to be
3429c65b135SDavid Blaikie     // null and the children will be added to the scope DIE.
343*2195e136SDavid Blaikie     createScopeChildrenDIE(Scope, Children, &HasNonScopeChildren);
3443a443c29SDavid Blaikie 
3459c65b135SDavid Blaikie     // If there are only other scopes as children, put them directly in the
3469c65b135SDavid Blaikie     // parent instead, as this scope would serve no purpose.
347*2195e136SDavid Blaikie     if (!HasNonScopeChildren) {
3489c65b135SDavid Blaikie       FinalChildren.insert(FinalChildren.end(),
3499c65b135SDavid Blaikie                            std::make_move_iterator(Children.begin()),
3509c65b135SDavid Blaikie                            std::make_move_iterator(Children.end()));
3519c65b135SDavid Blaikie       return;
3529c65b135SDavid Blaikie     }
3530fbf8bdbSDavid Blaikie     ScopeDIE = constructLexicalScopeDIE(Scope);
3549c65b135SDavid Blaikie     assert(ScopeDIE && "Scope DIE should not be null.");
3559c65b135SDavid Blaikie   }
3569c65b135SDavid Blaikie 
3579c65b135SDavid Blaikie   // Add children
3589c65b135SDavid Blaikie   for (auto &I : Children)
3599c65b135SDavid Blaikie     ScopeDIE->addChild(std::move(I));
3609c65b135SDavid Blaikie 
3619c65b135SDavid Blaikie   FinalChildren.push_back(std::move(ScopeDIE));
3629c65b135SDavid Blaikie }
3639c65b135SDavid Blaikie 
3645b02a19fSDavid Blaikie void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
3655b02a19fSDavid Blaikie                                          SmallVector<RangeSpan, 2> Range) {
366063d725fSRafael Espindola   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
367063d725fSRafael Espindola 
36852400200SDavid Blaikie   // Emit offset in .debug_range as a relocatable label. emitDIE will handle
36952400200SDavid Blaikie   // emitting it appropriately.
370063d725fSRafael Espindola   const MCSymbol *RangeSectionSym =
371063d725fSRafael Espindola       TLOF.getDwarfRangesSection()->getBeginSymbol();
37252400200SDavid Blaikie 
3739ab09237SRafael Espindola   RangeSpanList List(Asm->createTempSymbol("debug_ranges"), std::move(Range));
3745b02a19fSDavid Blaikie 
37552400200SDavid Blaikie   // Under fission, ranges are specified by constant offsets relative to the
37652400200SDavid Blaikie   // CU's DW_AT_GNU_ranges_base.
3775b02a19fSDavid Blaikie   if (isDwoUnit())
3785b02a19fSDavid Blaikie     addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
3795b02a19fSDavid Blaikie                     RangeSectionSym);
38052400200SDavid Blaikie   else
3815b02a19fSDavid Blaikie     addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
3825b02a19fSDavid Blaikie                     RangeSectionSym);
38352400200SDavid Blaikie 
38452400200SDavid Blaikie   // Add the range list to the set of ranges to be emitted.
385542616d4SDavid Blaikie   (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
38652400200SDavid Blaikie }
38752400200SDavid Blaikie 
388de12375cSDavid Blaikie void DwarfCompileUnit::attachRangesOrLowHighPC(
3895b02a19fSDavid Blaikie     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
3905b02a19fSDavid Blaikie   if (Ranges.size() == 1) {
3915b02a19fSDavid Blaikie     const auto &single = Ranges.front();
3925b02a19fSDavid Blaikie     attachLowHighPC(Die, single.getStart(), single.getEnd());
3935b02a19fSDavid Blaikie   } else
3945b02a19fSDavid Blaikie     addScopeRangeList(Die, std::move(Ranges));
3955b02a19fSDavid Blaikie }
3965b02a19fSDavid Blaikie 
3975b02a19fSDavid Blaikie void DwarfCompileUnit::attachRangesOrLowHighPC(
398de12375cSDavid Blaikie     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
3995b02a19fSDavid Blaikie   SmallVector<RangeSpan, 2> List;
4005b02a19fSDavid Blaikie   List.reserve(Ranges.size());
4015b02a19fSDavid Blaikie   for (const InsnRange &R : Ranges)
4025b02a19fSDavid Blaikie     List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
4035b02a19fSDavid Blaikie                              DD->getLabelAfterInsn(R.second)));
4045b02a19fSDavid Blaikie   attachRangesOrLowHighPC(Die, std::move(List));
405de12375cSDavid Blaikie }
406de12375cSDavid Blaikie 
40701b48a84SDavid Blaikie // This scope represents inlined body of a function. Construct DIE to
40801b48a84SDavid Blaikie // represent this concrete inlined copy of the function.
409827200c8SDuncan P. N. Exon Smith DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
41001b48a84SDavid Blaikie   assert(Scope->getScopeNode());
411be9e4fe7SDuncan P. N. Exon Smith   auto *DS = Scope->getScopeNode();
412be9e4fe7SDuncan P. N. Exon Smith   auto *InlinedSP = getDISubprogram(DS);
41301b48a84SDavid Blaikie   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
41401b48a84SDavid Blaikie   // was inlined from another compile unit.
415488393f8SDavid Blaikie   DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
41601b48a84SDavid Blaikie   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
41701b48a84SDavid Blaikie 
418827200c8SDuncan P. N. Exon Smith   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
41901b48a84SDavid Blaikie   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
42001b48a84SDavid Blaikie 
42101b48a84SDavid Blaikie   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
42201b48a84SDavid Blaikie 
42301b48a84SDavid Blaikie   // Add the call site information to the DIE.
424a9308c49SDuncan P. N. Exon Smith   const DILocation *IA = Scope->getInlinedAt();
42501b48a84SDavid Blaikie   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
426b7e221baSDuncan P. N. Exon Smith           getOrCreateSourceID(IA->getFilename(), IA->getDirectory()));
427b7e221baSDuncan P. N. Exon Smith   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
4286e0c8446SDehao Chen   if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
42954511353SDehao Chen     addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
43054511353SDehao Chen             IA->getDiscriminator());
43101b48a84SDavid Blaikie 
43201b48a84SDavid Blaikie   // Add name to the name table, we do this here because we're guaranteed
43301b48a84SDavid Blaikie   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
43401b48a84SDavid Blaikie   DD->addSubprogramNames(InlinedSP, *ScopeDIE);
43501b48a84SDavid Blaikie 
43601b48a84SDavid Blaikie   return ScopeDIE;
43701b48a84SDavid Blaikie }
43801b48a84SDavid Blaikie 
4390fbf8bdbSDavid Blaikie // Construct new DW_TAG_lexical_block for this scope and attach
4400fbf8bdbSDavid Blaikie // DW_AT_low_pc/DW_AT_high_pc labels.
441827200c8SDuncan P. N. Exon Smith DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
4420fbf8bdbSDavid Blaikie   if (DD->isLexicalScopeDIENull(Scope))
4430fbf8bdbSDavid Blaikie     return nullptr;
4440fbf8bdbSDavid Blaikie 
445827200c8SDuncan P. N. Exon Smith   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
4460fbf8bdbSDavid Blaikie   if (Scope->isAbstractScope())
4470fbf8bdbSDavid Blaikie     return ScopeDIE;
4480fbf8bdbSDavid Blaikie 
4490fbf8bdbSDavid Blaikie   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
4500fbf8bdbSDavid Blaikie 
4510fbf8bdbSDavid Blaikie   return ScopeDIE;
4520fbf8bdbSDavid Blaikie }
4530fbf8bdbSDavid Blaikie 
454ee7df553SDavid Blaikie /// constructVariableDIE - Construct a DIE for the given DbgVariable.
455827200c8SDuncan P. N. Exon Smith DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
456ee7df553SDavid Blaikie   auto D = constructVariableDIEImpl(DV, Abstract);
457ee7df553SDavid Blaikie   DV.setDIE(*D);
458ee7df553SDavid Blaikie   return D;
459ee7df553SDavid Blaikie }
460ee7df553SDavid Blaikie 
461827200c8SDuncan P. N. Exon Smith DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
462ee7df553SDavid Blaikie                                                 bool Abstract) {
463ee7df553SDavid Blaikie   // Define variable debug information entry.
464827200c8SDuncan P. N. Exon Smith   auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
465ee7df553SDavid Blaikie 
466ee7df553SDavid Blaikie   if (Abstract) {
467ee7df553SDavid Blaikie     applyVariableAttributes(DV, *VariableDie);
468ee7df553SDavid Blaikie     return VariableDie;
469ee7df553SDavid Blaikie   }
470ee7df553SDavid Blaikie 
471ee7df553SDavid Blaikie   // Add variable address.
472ee7df553SDavid Blaikie 
473364a3005SDuncan P. N. Exon Smith   unsigned Offset = DV.getDebugLocListIndex();
474ee7df553SDavid Blaikie   if (Offset != ~0U) {
475ee7df553SDavid Blaikie     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
476ee7df553SDavid Blaikie     return VariableDie;
477ee7df553SDavid Blaikie   }
478ee7df553SDavid Blaikie 
479ee7df553SDavid Blaikie   // Check if variable is described by a DBG_VALUE instruction.
480ee7df553SDavid Blaikie   if (const MachineInstr *DVInsn = DV.getMInsn()) {
481ee7df553SDavid Blaikie     assert(DVInsn->getNumOperands() == 4);
482ee7df553SDavid Blaikie     if (DVInsn->getOperand(0).isReg()) {
483ee7df553SDavid Blaikie       const MachineOperand RegOp = DVInsn->getOperand(0);
484ee7df553SDavid Blaikie       // If the second operand is an immediate, this is an indirect value.
485ee7df553SDavid Blaikie       if (DVInsn->getOperand(1).isImm()) {
486ee7df553SDavid Blaikie         MachineLocation Location(RegOp.getReg(),
487ee7df553SDavid Blaikie                                  DVInsn->getOperand(1).getImm());
488ee7df553SDavid Blaikie         addVariableAddress(DV, *VariableDie, Location);
489ee7df553SDavid Blaikie       } else if (RegOp.getReg())
490ee7df553SDavid Blaikie         addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
4913b89e663SAdrian Prantl     } else if (DVInsn->getOperand(0).isImm()) {
4923b89e663SAdrian Prantl       // This variable is described by a single constant.
4933b89e663SAdrian Prantl       // Check whether it has a DIExpression.
4943b89e663SAdrian Prantl       auto *Expr = DV.getSingleExpression();
4953b89e663SAdrian Prantl       if (Expr && Expr->getNumElements()) {
4963b89e663SAdrian Prantl         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
4973b89e663SAdrian Prantl         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
4983b89e663SAdrian Prantl         // If there is an expression, emit raw unsigned bytes.
4998fafb8d3SAdrian Prantl         DwarfExpr.addFragmentOffset(Expr);
500a63b8e82SAdrian Prantl         DwarfExpr.addUnsignedConstant(DVInsn->getOperand(0).getImm());
501a63b8e82SAdrian Prantl         DwarfExpr.addExpression(Expr);
502bceaaa96SAdrian Prantl         addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
5033b89e663SAdrian Prantl       } else
504ee7df553SDavid Blaikie         addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
5053b89e663SAdrian Prantl     } else if (DVInsn->getOperand(0).isFPImm())
506ee7df553SDavid Blaikie       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
507ee7df553SDavid Blaikie     else if (DVInsn->getOperand(0).isCImm())
508ee7df553SDavid Blaikie       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
509ee7df553SDavid Blaikie                        DV.getType());
510ee7df553SDavid Blaikie 
511ee7df553SDavid Blaikie     return VariableDie;
512ee7df553SDavid Blaikie   }
513ee7df553SDavid Blaikie 
514ee7df553SDavid Blaikie   // .. else use frame index.
51567c24422SAdrian Prantl   if (!DV.hasFrameIndexExprs())
516ca7e4702SAdrian Prantl     return VariableDie;
517ca7e4702SAdrian Prantl 
518e7e1d0c7SDuncan P. N. Exon Smith   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
519ca7e4702SAdrian Prantl   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
52067c24422SAdrian Prantl   for (auto &Fragment : DV.getFrameIndexExprs()) {
521ee7df553SDavid Blaikie     unsigned FrameReg = 0;
5226825fb64SAdrian Prantl     const DIExpression *Expr = Fragment.Expr;
523d4e723f2SEric Christopher     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
52467c24422SAdrian Prantl     int Offset = TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
5256825fb64SAdrian Prantl     DwarfExpr.addFragmentOffset(Expr);
526956484b7SAdrian Prantl     SmallVector<uint64_t, 8> Ops;
527ffc498dfSFlorian Hahn     Ops.push_back(dwarf::DW_OP_plus_uconst);
528956484b7SAdrian Prantl     Ops.push_back(Offset);
5296825fb64SAdrian Prantl     Ops.append(Expr->elements_begin(), Expr->elements_end());
5306825fb64SAdrian Prantl     DIExpressionCursor Cursor(Ops);
531c12cee36SAdrian Prantl     DwarfExpr.setMemoryLocationKind();
532c12cee36SAdrian Prantl     DwarfExpr.addMachineRegExpression(
533c12cee36SAdrian Prantl         *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
5346825fb64SAdrian Prantl     DwarfExpr.addExpression(std::move(Cursor));
535ee7df553SDavid Blaikie   }
536bceaaa96SAdrian Prantl   addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
537ee7df553SDavid Blaikie 
538ee7df553SDavid Blaikie   return VariableDie;
539ee7df553SDavid Blaikie }
540ee7df553SDavid Blaikie 
541827200c8SDuncan P. N. Exon Smith DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
542827200c8SDuncan P. N. Exon Smith                                             const LexicalScope &Scope,
543827200c8SDuncan P. N. Exon Smith                                             DIE *&ObjectPointer) {
5444a1a44e3SDavid Blaikie   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
5454a1a44e3SDavid Blaikie   if (DV.isObjectPointer())
546827200c8SDuncan P. N. Exon Smith     ObjectPointer = Var;
5474a1a44e3SDavid Blaikie   return Var;
5484a1a44e3SDavid Blaikie }
5494a1a44e3SDavid Blaikie 
550827200c8SDuncan P. N. Exon Smith DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
551827200c8SDuncan P. N. Exon Smith                                               SmallVectorImpl<DIE *> &Children,
552*2195e136SDavid Blaikie                                               bool *HasNonScopeChildren) {
553*2195e136SDavid Blaikie   assert(Children.empty());
5548b2fdb83SDavid Blaikie   DIE *ObjectPointer = nullptr;
5558b2fdb83SDavid Blaikie 
55680e5b1ebSDavid Blaikie   for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope))
5578b2fdb83SDavid Blaikie     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
5588b2fdb83SDavid Blaikie 
559*2195e136SDavid Blaikie   // Skip imported directives in gmlt-like data.
560*2195e136SDavid Blaikie   if (!includeMinimalInlineScopes()) {
561*2195e136SDavid Blaikie     // There is no need to emit empty lexical block DIE.
562*2195e136SDavid Blaikie     for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
563*2195e136SDavid Blaikie       Children.push_back(
564*2195e136SDavid Blaikie           constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
565*2195e136SDavid Blaikie   }
566*2195e136SDavid Blaikie 
567*2195e136SDavid Blaikie   if (HasNonScopeChildren)
568*2195e136SDavid Blaikie     *HasNonScopeChildren = !Children.empty();
5698b2fdb83SDavid Blaikie 
5708b2fdb83SDavid Blaikie   for (LexicalScope *LS : Scope->getChildren())
5718b2fdb83SDavid Blaikie     constructScopeDIE(LS, Children);
5728b2fdb83SDavid Blaikie 
5738b2fdb83SDavid Blaikie   return ObjectPointer;
5748b2fdb83SDavid Blaikie }
5758b2fdb83SDavid Blaikie 
5763e3eb33eSDavid Blaikie void DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub, LexicalScope *Scope) {
5771d072348SDavid Blaikie   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
5781d072348SDavid Blaikie 
5793e3eb33eSDavid Blaikie   if (Scope) {
5803e3eb33eSDavid Blaikie     assert(!Scope->getInlinedAt());
5813e3eb33eSDavid Blaikie     assert(!Scope->isAbstractScope());
5821dd573dbSDavid Blaikie     // Collect lexical scope children first.
5831dd573dbSDavid Blaikie     // ObjectPointer might be a local (non-argument) local variable if it's a
5841dd573dbSDavid Blaikie     // block's synthetic this pointer.
5851dd573dbSDavid Blaikie     if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
5861dd573dbSDavid Blaikie       addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
5873e3eb33eSDavid Blaikie   }
5883e3eb33eSDavid Blaikie 
5893e3eb33eSDavid Blaikie   // If this is a variadic function, add an unspecified parameter.
5903e3eb33eSDavid Blaikie   DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
5911dd573dbSDavid Blaikie 
5921d072348SDavid Blaikie   // If we have a single element of null, it is a function that returns void.
5931d072348SDavid Blaikie   // If we have more than one elements and the last one is null, it is a
5941d072348SDavid Blaikie   // variadic function.
595000fa2c6SDuncan P. N. Exon Smith   if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
5963a443c29SDavid Blaikie       !includeMinimalInlineScopes())
597827200c8SDuncan P. N. Exon Smith     ScopeDIE.addChild(
598827200c8SDuncan P. N. Exon Smith         DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
5991d072348SDavid Blaikie }
6001d072348SDavid Blaikie 
60178b65b6fSDavid Blaikie DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
60278b65b6fSDavid Blaikie                                                  DIE &ScopeDIE) {
60378b65b6fSDavid Blaikie   // We create children when the scope DIE is not null.
604827200c8SDuncan P. N. Exon Smith   SmallVector<DIE *, 8> Children;
60578b65b6fSDavid Blaikie   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
60678b65b6fSDavid Blaikie 
60778b65b6fSDavid Blaikie   // Add children
60878b65b6fSDavid Blaikie   for (auto &I : Children)
60978b65b6fSDavid Blaikie     ScopeDIE.addChild(std::move(I));
61078b65b6fSDavid Blaikie 
61178b65b6fSDavid Blaikie   return ObjectPointer;
61278b65b6fSDavid Blaikie }
61378b65b6fSDavid Blaikie 
61454511353SDehao Chen void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
61554511353SDehao Chen     LexicalScope *Scope) {
616488393f8SDavid Blaikie   DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
61749be5b35SDavid Blaikie   if (AbsDef)
61849be5b35SDavid Blaikie     return;
61949be5b35SDavid Blaikie 
620a9308c49SDuncan P. N. Exon Smith   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
62158410f24SDavid Blaikie 
62258410f24SDavid Blaikie   DIE *ContextDIE;
62358410f24SDavid Blaikie 
6243a443c29SDavid Blaikie   if (includeMinimalInlineScopes())
6253a443c29SDavid Blaikie     ContextDIE = &getUnitDie();
62658410f24SDavid Blaikie   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
6277c60f20eSDuncan P. N. Exon Smith   // the important distinction that the debug node is not associated with the
6287c60f20eSDuncan P. N. Exon Smith   // DIE (since the debug node will be associated with the concrete DIE, if
62958410f24SDavid Blaikie   // any). It could be refactored to some common utility function.
630537b4a81SDuncan P. N. Exon Smith   else if (auto *SPDecl = SP->getDeclaration()) {
63158410f24SDavid Blaikie     ContextDIE = &getUnitDie();
63258410f24SDavid Blaikie     getOrCreateSubprogramDIE(SPDecl);
63358410f24SDavid Blaikie   } else
634537b4a81SDuncan P. N. Exon Smith     ContextDIE = getOrCreateContextDIE(resolve(SP->getScope()));
63558410f24SDavid Blaikie 
6367c60f20eSDuncan P. N. Exon Smith   // Passing null as the associated node because the abstract definition
63758410f24SDavid Blaikie   // shouldn't be found by lookup.
6387c60f20eSDuncan P. N. Exon Smith   AbsDef = &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
63949be5b35SDavid Blaikie   applySubprogramAttributesToDefinition(SP, *AbsDef);
64058410f24SDavid Blaikie 
6413a443c29SDavid Blaikie   if (!includeMinimalInlineScopes())
64249be5b35SDavid Blaikie     addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
64349be5b35SDavid Blaikie   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef))
64449be5b35SDavid Blaikie     addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
64558410f24SDavid Blaikie }
64658410f24SDavid Blaikie 
647827200c8SDuncan P. N. Exon Smith DIE *DwarfCompileUnit::constructImportedEntityDIE(
648827200c8SDuncan P. N. Exon Smith     const DIImportedEntity *Module) {
64972da9391SAmjad Aboud   DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
65072da9391SAmjad Aboud   insertDIE(Module, IMDie);
651987fe227SFrederic Riss   DIE *EntityDie;
652de8e4273SDuncan P. N. Exon Smith   auto *Entity = resolve(Module->getEntity());
653a9308c49SDuncan P. N. Exon Smith   if (auto *NS = dyn_cast<DINamespace>(Entity))
654e686f159SDuncan P. N. Exon Smith     EntityDie = getOrCreateNameSpace(NS);
65508a388baSAdrian Prantl   else if (auto *M = dyn_cast<DIModule>(Entity))
65608a388baSAdrian Prantl     EntityDie = getOrCreateModule(M);
657a9308c49SDuncan P. N. Exon Smith   else if (auto *SP = dyn_cast<DISubprogram>(Entity))
658e686f159SDuncan P. N. Exon Smith     EntityDie = getOrCreateSubprogramDIE(SP);
659a9308c49SDuncan P. N. Exon Smith   else if (auto *T = dyn_cast<DIType>(Entity))
660e686f159SDuncan P. N. Exon Smith     EntityDie = getOrCreateTypeDIE(T);
661a9308c49SDuncan P. N. Exon Smith   else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
662bceaaa96SAdrian Prantl     EntityDie = getOrCreateGlobalVariableDIE(GV, {});
663987fe227SFrederic Riss   else
664987fe227SFrederic Riss     EntityDie = getDIE(Entity);
665987fe227SFrederic Riss   assert(EntityDie);
666d63bfd21SAdrian Prantl   auto *File = Module->getFile();
667d63bfd21SAdrian Prantl   addSourceLine(*IMDie, Module->getLine(), File ? File->getFilename() : "",
668d63bfd21SAdrian Prantl                 File ? File->getDirectory() : "");
669987fe227SFrederic Riss   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
670de8e4273SDuncan P. N. Exon Smith   StringRef Name = Module->getName();
671987fe227SFrederic Riss   if (!Name.empty())
672987fe227SFrederic Riss     addString(*IMDie, dwarf::DW_AT_name, Name);
673987fe227SFrederic Riss 
674987fe227SFrederic Riss   return IMDie;
675987fe227SFrederic Riss }
676987fe227SFrederic Riss 
677a9308c49SDuncan P. N. Exon Smith void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
67872da9391SAmjad Aboud   DIE *D = getDIE(SP);
679488393f8SDavid Blaikie   if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
68072da9391SAmjad Aboud     if (D)
6814191cbceSDavid Blaikie       // If this subprogram has an abstract definition, reference that
6824191cbceSDavid Blaikie       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
68372da9391SAmjad Aboud   } else {
6843e3eb33eSDavid Blaikie     assert(D || includeMinimalInlineScopes());
68572da9391SAmjad Aboud     if (D)
6864191cbceSDavid Blaikie       // And attach the attributes
6874191cbceSDavid Blaikie       applySubprogramAttributesToDefinition(SP, *D);
6884191cbceSDavid Blaikie   }
6894191cbceSDavid Blaikie }
6904191cbceSDavid Blaikie 
691488393f8SDavid Blaikie void DwarfCompileUnit::finishVariableDefinition(const DbgVariable &Var) {
692488393f8SDavid Blaikie   DbgVariable *AbsVar = getExistingAbstractVariable(
693488393f8SDavid Blaikie       InlinedVariable(Var.getVariable(), Var.getInlinedAt()));
694488393f8SDavid Blaikie   auto *VariableDie = Var.getDIE();
695488393f8SDavid Blaikie   if (AbsVar && AbsVar->getDIE()) {
696488393f8SDavid Blaikie     addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
697488393f8SDavid Blaikie                       *AbsVar->getDIE());
698488393f8SDavid Blaikie   } else
699488393f8SDavid Blaikie     applyVariableAttributes(Var, *VariableDie);
700488393f8SDavid Blaikie }
701488393f8SDavid Blaikie 
702488393f8SDavid Blaikie DbgVariable *DwarfCompileUnit::getExistingAbstractVariable(InlinedVariable IV) {
703488393f8SDavid Blaikie   const DILocalVariable *Cleansed;
704488393f8SDavid Blaikie   return getExistingAbstractVariable(IV, Cleansed);
705488393f8SDavid Blaikie }
706488393f8SDavid Blaikie 
707488393f8SDavid Blaikie // Find abstract variable, if any, associated with Var.
708488393f8SDavid Blaikie DbgVariable *DwarfCompileUnit::getExistingAbstractVariable(
709488393f8SDavid Blaikie     InlinedVariable IV, const DILocalVariable *&Cleansed) {
710488393f8SDavid Blaikie   // More then one inlined variable corresponds to one abstract variable.
711488393f8SDavid Blaikie   Cleansed = IV.first;
712488393f8SDavid Blaikie   auto &AbstractVariables = getAbstractVariables();
713488393f8SDavid Blaikie   auto I = AbstractVariables.find(Cleansed);
714488393f8SDavid Blaikie   if (I != AbstractVariables.end())
715488393f8SDavid Blaikie     return I->second.get();
716488393f8SDavid Blaikie   return nullptr;
717488393f8SDavid Blaikie }
718488393f8SDavid Blaikie 
719488393f8SDavid Blaikie void DwarfCompileUnit::createAbstractVariable(const DILocalVariable *Var,
720488393f8SDavid Blaikie                                         LexicalScope *Scope) {
721488393f8SDavid Blaikie   assert(Scope && Scope->isAbstractScope());
722488393f8SDavid Blaikie   auto AbsDbgVariable = make_unique<DbgVariable>(Var, /* IA */ nullptr);
723488393f8SDavid Blaikie   DU->addScopeVariable(Scope, AbsDbgVariable.get());
724488393f8SDavid Blaikie   getAbstractVariables()[Var] = std::move(AbsDbgVariable);
725488393f8SDavid Blaikie }
726488393f8SDavid Blaikie 
727063d725fSRafael Espindola void DwarfCompileUnit::emitHeader(bool UseOffsets) {
728b6726a9eSDavid Blaikie   // Don't bother labeling the .dwo unit, as its offset isn't used.
7293c311148SRafael Espindola   if (!Skeleton) {
7309ab09237SRafael Espindola     LabelBegin = Asm->createTempSymbol("cu_begin");
7319ff69c8fSLang Hames     Asm->OutStreamer->EmitLabel(LabelBegin);
7323c311148SRafael Espindola   }
733ae57e66eSDavid Blaikie 
734cddd6044SPaul Robinson   dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
735cddd6044SPaul Robinson                                 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
736cddd6044SPaul Robinson                                                       : dwarf::DW_UT_compile;
737cddd6044SPaul Robinson   DwarfUnit::emitCommonHeader(UseOffsets, UT);
738ae57e66eSDavid Blaikie }
739ae57e66eSDavid Blaikie 
740192b45c1SDavid Blaikie /// addGlobalName - Add a new global name to the compile unit.
741a0e3c751SDavid Blaikie void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
742a9308c49SDuncan P. N. Exon Smith                                      const DIScope *Context) {
743b3cee2fbSDavid Blaikie   if (!DD->hasDwarfPubSections(includeMinimalInlineScopes()))
744192b45c1SDavid Blaikie     return;
745192b45c1SDavid Blaikie   std::string FullName = getParentContextString(Context) + Name.str();
746192b45c1SDavid Blaikie   GlobalNames[FullName] = &Die;
747192b45c1SDavid Blaikie }
748192b45c1SDavid Blaikie 
749a0e3c751SDavid Blaikie void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
750a0e3c751SDavid Blaikie                                                 const DIScope *Context) {
751b3cee2fbSDavid Blaikie   if (!DD->hasDwarfPubSections(includeMinimalInlineScopes()))
752a0e3c751SDavid Blaikie     return;
753a0e3c751SDavid Blaikie   std::string FullName = getParentContextString(Context) + Name.str();
754a0e3c751SDavid Blaikie   // Insert, allowing the entry to remain as-is if it's already present
755a0e3c751SDavid Blaikie   // This way the CU-level type DIE is preferred over the "can't describe this
756a0e3c751SDavid Blaikie   // type as a unit offset because it's not really in the CU at all, it's only
757a0e3c751SDavid Blaikie   // in a type unit"
758a0e3c751SDavid Blaikie   GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
759a0e3c751SDavid Blaikie }
760a0e3c751SDavid Blaikie 
761192b45c1SDavid Blaikie /// Add a new global type to the unit.
762a9308c49SDuncan P. N. Exon Smith void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
763a9308c49SDuncan P. N. Exon Smith                                      const DIScope *Context) {
764b3cee2fbSDavid Blaikie   if (!DD->hasDwarfPubSections(includeMinimalInlineScopes()))
765192b45c1SDavid Blaikie     return;
766b1055640SDuncan P. N. Exon Smith   std::string FullName = getParentContextString(Context) + Ty->getName().str();
767192b45c1SDavid Blaikie   GlobalTypes[FullName] = &Die;
768192b45c1SDavid Blaikie }
769ae57e66eSDavid Blaikie 
770a0e3c751SDavid Blaikie void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
771a0e3c751SDavid Blaikie                                              const DIScope *Context) {
772b3cee2fbSDavid Blaikie   if (!DD->hasDwarfPubSections(includeMinimalInlineScopes()))
773a0e3c751SDavid Blaikie     return;
774a0e3c751SDavid Blaikie   std::string FullName = getParentContextString(Context) + Ty->getName().str();
775a0e3c751SDavid Blaikie   // Insert, allowing the entry to remain as-is if it's already present
776a0e3c751SDavid Blaikie   // This way the CU-level type DIE is preferred over the "can't describe this
777a0e3c751SDavid Blaikie   // type as a unit offset because it's not really in the CU at all, it's only
778a0e3c751SDavid Blaikie   // in a type unit"
779a0e3c751SDavid Blaikie   GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
780a0e3c751SDavid Blaikie }
781a0e3c751SDavid Blaikie 
7827d48be2bSDavid Blaikie /// addVariableAddress - Add DW_AT_location attribute for a
7837d48be2bSDavid Blaikie /// DbgVariable based on provided MachineLocation.
7847d48be2bSDavid Blaikie void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
7857d48be2bSDavid Blaikie                                           MachineLocation Location) {
786e6cc531bSDuncan P. N. Exon Smith   if (DV.hasComplexAddress())
7877d48be2bSDavid Blaikie     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
7887d48be2bSDavid Blaikie   else if (DV.isBlockByrefVariable())
7897d48be2bSDavid Blaikie     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
7907d48be2bSDavid Blaikie   else
7915883af3fSAdrian Prantl     addAddress(Die, dwarf::DW_AT_location, Location);
7927d48be2bSDavid Blaikie }
793f7435ee6SDavid Blaikie 
794f7435ee6SDavid Blaikie /// Add an address attribute to a die based on the location provided.
795f7435ee6SDavid Blaikie void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
7965883af3fSAdrian Prantl                                   const MachineLocation &Location) {
797e7e1d0c7SDuncan P. N. Exon Smith   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
798956484b7SAdrian Prantl   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
799c12cee36SAdrian Prantl   if (Location.isIndirect())
800c12cee36SAdrian Prantl     DwarfExpr.setMemoryLocationKind();
801f7435ee6SDavid Blaikie 
802956484b7SAdrian Prantl   SmallVector<uint64_t, 8> Ops;
8036825fb64SAdrian Prantl   if (Location.isIndirect() && Location.getOffset()) {
804ffc498dfSFlorian Hahn     Ops.push_back(dwarf::DW_OP_plus_uconst);
805956484b7SAdrian Prantl     Ops.push_back(Location.getOffset());
806956484b7SAdrian Prantl   }
807956484b7SAdrian Prantl   DIExpressionCursor Cursor(Ops);
808956484b7SAdrian Prantl   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
809c12cee36SAdrian Prantl   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
810ab255fcdSAdrian Prantl     return;
811956484b7SAdrian Prantl   DwarfExpr.addExpression(std::move(Cursor));
812ab255fcdSAdrian Prantl 
813f7435ee6SDavid Blaikie   // Now attach the location information to the DIE.
814956484b7SAdrian Prantl   addBlock(Die, Attribute, DwarfExpr.finalize());
815f7435ee6SDavid Blaikie }
81677895fb2SDavid Blaikie 
81777895fb2SDavid Blaikie /// Start with the address based on the location provided, and generate the
81877895fb2SDavid Blaikie /// DWARF information necessary to find the actual variable given the extra
81977895fb2SDavid Blaikie /// address information encoded in the DbgVariable, starting from the starting
82077895fb2SDavid Blaikie /// location.  Add the DWARF information to the die.
82177895fb2SDavid Blaikie void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
82277895fb2SDavid Blaikie                                          dwarf::Attribute Attribute,
82377895fb2SDavid Blaikie                                          const MachineLocation &Location) {
824e7e1d0c7SDuncan P. N. Exon Smith   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
8257813d9c9SAdrian Prantl   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
826956484b7SAdrian Prantl   const DIExpression *DIExpr = DV.getSingleExpression();
827956484b7SAdrian Prantl   DwarfExpr.addFragmentOffset(DIExpr);
828c12cee36SAdrian Prantl   if (Location.isIndirect())
829c12cee36SAdrian Prantl     DwarfExpr.setMemoryLocationKind();
830956484b7SAdrian Prantl 
831956484b7SAdrian Prantl   SmallVector<uint64_t, 8> Ops;
8326825fb64SAdrian Prantl   if (Location.isIndirect() && Location.getOffset()) {
833ffc498dfSFlorian Hahn     Ops.push_back(dwarf::DW_OP_plus_uconst);
834956484b7SAdrian Prantl     Ops.push_back(Location.getOffset());
835956484b7SAdrian Prantl   }
836956484b7SAdrian Prantl   Ops.append(DIExpr->elements_begin(), DIExpr->elements_end());
837956484b7SAdrian Prantl   DIExpressionCursor Cursor(Ops);
83896c9ae6aSPeter Collingbourne   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
839c12cee36SAdrian Prantl   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
84054286bdaSAdrian Prantl     return;
841956484b7SAdrian Prantl   DwarfExpr.addExpression(std::move(Cursor));
84277895fb2SDavid Blaikie 
84377895fb2SDavid Blaikie   // Now attach the location information to the DIE.
844956484b7SAdrian Prantl   addBlock(Die, Attribute, DwarfExpr.finalize());
84577895fb2SDavid Blaikie }
8464bc0881aSDavid Blaikie 
8474bc0881aSDavid Blaikie /// Add a Dwarf loclistptr attribute data and value.
8484bc0881aSDavid Blaikie void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
8494bc0881aSDavid Blaikie                                        unsigned Index) {
8504bc0881aSDavid Blaikie   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
8514bc0881aSDavid Blaikie                                                 : dwarf::DW_FORM_data4;
8524fb1f9cdSDuncan P. N. Exon Smith   Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
8534bc0881aSDavid Blaikie }
85402a6333bSDavid Blaikie 
8558c485b5dSDavid Blaikie void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
85602a6333bSDavid Blaikie                                                DIE &VariableDie) {
85702a6333bSDavid Blaikie   StringRef Name = Var.getName();
85802a6333bSDavid Blaikie   if (!Name.empty())
85902a6333bSDavid Blaikie     addString(VariableDie, dwarf::DW_AT_name, Name);
8603c989984SVictor Leschuk   const auto *DIVar = Var.getVariable();
8613c989984SVictor Leschuk   if (DIVar)
8623c989984SVictor Leschuk     if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
8633c989984SVictor Leschuk       addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
8643c989984SVictor Leschuk               AlignInBytes);
8653c989984SVictor Leschuk 
8663c989984SVictor Leschuk   addSourceLine(VariableDie, DIVar);
86702a6333bSDavid Blaikie   addType(VariableDie, Var.getType());
86802a6333bSDavid Blaikie   if (Var.isArtificial())
86902a6333bSDavid Blaikie     addFlag(VariableDie, dwarf::DW_AT_artificial);
87002a6333bSDavid Blaikie }
87197802080SDavid Blaikie 
87297802080SDavid Blaikie /// Add a Dwarf expression attribute data and value.
87397802080SDavid Blaikie void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
87497802080SDavid Blaikie                                const MCExpr *Expr) {
8754fb1f9cdSDuncan P. N. Exon Smith   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
87697802080SDavid Blaikie }
8773363a57cSDavid Blaikie 
8782fbe1354SDuncan P. N. Exon Smith void DwarfCompileUnit::applySubprogramAttributesToDefinition(
879a9308c49SDuncan P. N. Exon Smith     const DISubprogram *SP, DIE &SPDie) {
880537b4a81SDuncan P. N. Exon Smith   auto *SPDecl = SP->getDeclaration();
881be9e4fe7SDuncan P. N. Exon Smith   auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope());
8823a443c29SDavid Blaikie   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
883537b4a81SDuncan P. N. Exon Smith   addGlobalName(SP->getName(), SPDie, Context);
8843363a57cSDavid Blaikie }
885cafd962dSDavid Blaikie 
886cafd962dSDavid Blaikie bool DwarfCompileUnit::isDwoUnit() const {
887cafd962dSDavid Blaikie   return DD->useSplitDwarf() && Skeleton;
888cafd962dSDavid Blaikie }
8893a443c29SDavid Blaikie 
8903a443c29SDavid Blaikie bool DwarfCompileUnit::includeMinimalInlineScopes() const {
891b939a257SAdrian Prantl   return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
8923a443c29SDavid Blaikie          (DD->useSplitDwarf() && !Skeleton);
8933a443c29SDavid Blaikie }
894f00654e3SAlexander Kornienko } // end llvm namespace
895