]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp
Sink most of DwarfDebug::constructAbstractSubprogramScopeDIE into DwarfCompileUnit
[opencl/llvm.git] / lib / CodeGen / AsmPrinter / DwarfCompileUnit.cpp
1 #include "DwarfCompileUnit.h"
3 #include "llvm/CodeGen/MachineFunction.h"
4 #include "llvm/IR/DataLayout.h"
5 #include "llvm/IR/GlobalValue.h"
6 #include "llvm/IR/GlobalVariable.h"
7 #include "llvm/IR/Instruction.h"
8 #include "llvm/MC/MCAsmInfo.h"
9 #include "llvm/MC/MCStreamer.h"
10 #include "llvm/Target/TargetFrameLowering.h"
11 #include "llvm/Target/TargetLoweringObjectFile.h"
12 #include "llvm/Target/TargetMachine.h"
13 #include "llvm/Target/TargetSubtargetInfo.h"
14 #include "llvm/Target/TargetRegisterInfo.h"
16 namespace llvm {
18 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DICompileUnit Node,
19                                    AsmPrinter *A, DwarfDebug *DW,
20                                    DwarfFile *DWU)
21     : DwarfUnit(UID, dwarf::DW_TAG_compile_unit, Node, A, DW, DWU) {
22   insertDIE(Node, &getUnitDie());
23 }
25 /// addLabelAddress - Add a dwarf label attribute data and value using
26 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
27 ///
28 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
29                                        const MCSymbol *Label) {
31   // Don't use the address pool in non-fission or in the skeleton unit itself.
32   // FIXME: Once GDB supports this, it's probably worthwhile using the address
33   // pool from the skeleton - maybe even in non-fission (possibly fewer
34   // relocations by sharing them in the pool, but we have other ideas about how
35   // to reduce the number of relocations as well/instead).
36   if (!DD->useSplitDwarf() || !Skeleton)
37     return addLocalLabelAddress(Die, Attribute, Label);
39   if (Label)
40     DD->addArangeLabel(SymbolCU(this, Label));
42   unsigned idx = DD->getAddressPool().getIndex(Label);
43   DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
44   Die.addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
45 }
47 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
48                                             dwarf::Attribute Attribute,
49                                             const MCSymbol *Label) {
50   if (Label)
51     DD->addArangeLabel(SymbolCU(this, Label));
53   Die.addValue(Attribute, dwarf::DW_FORM_addr,
54                Label ? (DIEValue *)new (DIEValueAllocator) DIELabel(Label)
55                      : new (DIEValueAllocator) DIEInteger(0));
56 }
58 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName,
59                                                StringRef DirName) {
60   // If we print assembly, we can't separate .file entries according to
61   // compile units. Thus all files will belong to the default compile unit.
63   // FIXME: add a better feature test than hasRawTextSupport. Even better,
64   // extend .file to support this.
65   return Asm->OutStreamer.EmitDwarfFileDirective(
66       0, DirName, FileName,
67       Asm->OutStreamer.hasRawTextSupport() ? 0 : getUniqueID());
68 }
70 // Return const expression if value is a GEP to access merged global
71 // constant. e.g.
72 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
73 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
74   const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
75   if (!CE || CE->getNumOperands() != 3 ||
76       CE->getOpcode() != Instruction::GetElementPtr)
77     return nullptr;
79   // First operand points to a global struct.
80   Value *Ptr = CE->getOperand(0);
81   if (!isa<GlobalValue>(Ptr) ||
82       !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
83     return nullptr;
85   // Second operand is zero.
86   const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
87   if (!CI || !CI->isZero())
88     return nullptr;
90   // Third operand is offset.
91   if (!isa<ConstantInt>(CE->getOperand(2)))
92     return nullptr;
94   return CE;
95 }
97 /// getOrCreateGlobalVariableDIE - get or create global variable DIE.
98 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(DIGlobalVariable GV) {
99   // Check for pre-existence.
100   if (DIE *Die = getDIE(GV))
101     return Die;
103   assert(GV.isGlobalVariable());
105   DIScope GVContext = GV.getContext();
106   DIType GTy = DD->resolve(GV.getType());
108   // Construct the context before querying for the existence of the DIE in
109   // case such construction creates the DIE.
110   DIE *ContextDIE = getOrCreateContextDIE(GVContext);
112   // Add to map.
113   DIE *VariableDIE = &createAndAddDIE(GV.getTag(), *ContextDIE, GV);
114   DIScope DeclContext;
116   if (DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration()) {
117     DeclContext = resolve(SDMDecl.getContext());
118     assert(SDMDecl.isStaticMember() && "Expected static member decl");
119     assert(GV.isDefinition());
120     // We need the declaration DIE that is in the static member's class.
121     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
122     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
123   } else {
124     DeclContext = GV.getContext();
125     // Add name and type.
126     addString(*VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
127     addType(*VariableDIE, GTy);
129     // Add scoping info.
130     if (!GV.isLocalToUnit())
131       addFlag(*VariableDIE, dwarf::DW_AT_external);
133     // Add line number info.
134     addSourceLine(*VariableDIE, GV);
135   }
137   if (!GV.isDefinition())
138     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
140   // Add location.
141   bool addToAccelTable = false;
142   bool isGlobalVariable = GV.getGlobal() != nullptr;
143   if (isGlobalVariable) {
144     addToAccelTable = true;
145     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
146     const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
147     if (GV.getGlobal()->isThreadLocal()) {
148       // FIXME: Make this work with -gsplit-dwarf.
149       unsigned PointerSize = Asm->getDataLayout().getPointerSize();
150       assert((PointerSize == 4 || PointerSize == 8) &&
151              "Add support for other sizes if necessary");
152       // Based on GCC's support for TLS:
153       if (!DD->useSplitDwarf()) {
154         // 1) Start with a constNu of the appropriate pointer size
155         addUInt(*Loc, dwarf::DW_FORM_data1,
156                 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
157         // 2) containing the (relocated) offset of the TLS variable
158         //    within the module's TLS block.
159         addExpr(*Loc, dwarf::DW_FORM_udata,
160                 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
161       } else {
162         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
163         addUInt(*Loc, dwarf::DW_FORM_udata,
164                 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
165       }
166       // 3) followed by a custom OP to make the debugger do a TLS lookup.
167       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
168     } else {
169       DD->addArangeLabel(SymbolCU(this, Sym));
170       addOpAddress(*Loc, Sym);
171     }
173     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
174     // Add the linkage name.
175     StringRef LinkageName = GV.getLinkageName();
176     if (!LinkageName.empty())
177       // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
178       // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
179       // TAG_variable.
180       addString(*VariableDIE,
181                 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
182                                            : dwarf::DW_AT_MIPS_linkage_name,
183                 GlobalValue::getRealLinkageName(LinkageName));
184   } else if (const ConstantInt *CI =
185                  dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
186     addConstantValue(*VariableDIE, CI, GTy);
187   } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV.getConstant())) {
188     addToAccelTable = true;
189     // GV is a merged global.
190     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
191     Value *Ptr = CE->getOperand(0);
192     MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
193     DD->addArangeLabel(SymbolCU(this, Sym));
194     addOpAddress(*Loc, Sym);
195     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
196     SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
197     addUInt(*Loc, dwarf::DW_FORM_udata,
198             Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
199     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
200     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
201   }
203   if (addToAccelTable) {
204     DD->addAccelName(GV.getName(), *VariableDIE);
206     // If the linkage name is different than the name, go ahead and output
207     // that as well into the name table.
208     if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
209       DD->addAccelName(GV.getLinkageName(), *VariableDIE);
210   }
212   addGlobalName(GV.getName(), *VariableDIE, DeclContext);
213   return VariableDIE;
216 void DwarfCompileUnit::addRange(RangeSpan Range) {
217   bool SameAsPrevCU = this == DD->getPrevCU();
218   DD->setPrevCU(this);
219   // If we have no current ranges just add the range and return, otherwise,
220   // check the current section and CU against the previous section and CU we
221   // emitted into and the subprogram was contained within. If these are the
222   // same then extend our current range, otherwise add this as a new range.
223   if (CURanges.empty() || !SameAsPrevCU ||
224       (&CURanges.back().getEnd()->getSection() !=
225        &Range.getEnd()->getSection())) {
226     CURanges.push_back(Range);
227     return;
228   }
230   CURanges.back().setEnd(Range.getEnd());
233 void DwarfCompileUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
234                                        const MCSymbol *Label,
235                                        const MCSymbol *Sec) {
236   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
237     addLabel(Die, Attribute,
238              DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
239                                         : dwarf::DW_FORM_data4,
240              Label);
241   else
242     addSectionDelta(Die, Attribute, Label, Sec);
245 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
246   // Define start line table label for each Compile Unit.
247   MCSymbol *LineTableStartSym =
248       Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
250   stmtListIndex = UnitDie.getValues().size();
252   // DW_AT_stmt_list is a offset of line number information for this
253   // compile unit in debug_line section. For split dwarf this is
254   // left in the skeleton CU and so not included.
255   // The line table entries are not always emitted in assembly, so it
256   // is not okay to use line_table_start here.
257   addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
258                   DwarfLineSectionSym);
261 void DwarfCompileUnit::applyStmtList(DIE &D) {
262   D.addValue(dwarf::DW_AT_stmt_list,
263              UnitDie.getAbbrev().getData()[stmtListIndex].getForm(),
264              UnitDie.getValues()[stmtListIndex]);
267 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
268                                        const MCSymbol *End) {
269   assert(Begin && "Begin label should not be null!");
270   assert(End && "End label should not be null!");
271   assert(Begin->isDefined() && "Invalid starting label");
272   assert(End->isDefined() && "Invalid end label");
274   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
275   if (DD->getDwarfVersion() < 4)
276     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
277   else
278     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
281 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
282 // and DW_AT_high_pc attributes. If there are global variables in this
283 // scope then create and insert DIEs for these variables.
284 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(DISubprogram SP) {
285   DIE *SPDie = getOrCreateSubprogramDIE(SP);
287   attachLowHighPC(*SPDie, DD->getFunctionBeginSym(), DD->getFunctionEndSym());
288   if (!DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
289           *DD->getCurrentFunction()))
290     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
292   // Only include DW_AT_frame_base in full debug info
293   if (getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly) {
294     const TargetRegisterInfo *RI =
295         Asm->TM.getSubtargetImpl()->getRegisterInfo();
296     MachineLocation Location(RI->getFrameRegister(*Asm->MF));
297     addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
298   }
300   // Add name to the name table, we do this here because we're guaranteed
301   // to have concrete versions of our DW_TAG_subprogram nodes.
302   DD->addSubprogramNames(SP, *SPDie);
304   return *SPDie;
307 // Construct a DIE for this scope.
308 void DwarfCompileUnit::constructScopeDIE(
309     LexicalScope *Scope, SmallVectorImpl<std::unique_ptr<DIE>> &FinalChildren) {
310   if (!Scope || !Scope->getScopeNode())
311     return;
313   DIScope DS(Scope->getScopeNode());
315   assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
316          "Only handle inlined subprograms here, use "
317          "constructSubprogramScopeDIE for non-inlined "
318          "subprograms");
320   SmallVector<std::unique_ptr<DIE>, 8> Children;
322   // We try to create the scope DIE first, then the children DIEs. This will
323   // avoid creating un-used children then removing them later when we find out
324   // the scope DIE is null.
325   std::unique_ptr<DIE> ScopeDIE;
326   if (Scope->getParent() && DS.isSubprogram()) {
327     ScopeDIE = constructInlinedScopeDIE(Scope);
328     if (!ScopeDIE)
329       return;
330     // We create children when the scope DIE is not null.
331     createScopeChildrenDIE(Scope, Children);
332   } else {
333     // Early exit when we know the scope DIE is going to be null.
334     if (DD->isLexicalScopeDIENull(Scope))
335       return;
337     unsigned ChildScopeCount;
339     // We create children here when we know the scope DIE is not going to be
340     // null and the children will be added to the scope DIE.
341     createScopeChildrenDIE(Scope, Children, &ChildScopeCount);
343     // There is no need to emit empty lexical block DIE.
344     for (const auto &E : DD->findImportedEntitiesForScope(DS))
345       Children.push_back(
346           constructImportedEntityDIE(DIImportedEntity(E.second)));
347     // If there are only other scopes as children, put them directly in the
348     // parent instead, as this scope would serve no purpose.
349     if (Children.size() == ChildScopeCount) {
350       FinalChildren.insert(FinalChildren.end(),
351                            std::make_move_iterator(Children.begin()),
352                            std::make_move_iterator(Children.end()));
353       return;
354     }
355     ScopeDIE = constructLexicalScopeDIE(Scope);
356     assert(ScopeDIE && "Scope DIE should not be null.");
357   }
359   // Add children
360   for (auto &I : Children)
361     ScopeDIE->addChild(std::move(I));
363   FinalChildren.push_back(std::move(ScopeDIE));
366 void DwarfCompileUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
367                                        const MCSymbol *Hi, const MCSymbol *Lo) {
368   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
369   Die.addValue(Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
370                                                      : dwarf::DW_FORM_data4,
371                Value);
374 void
375 DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
376                                     const SmallVectorImpl<InsnRange> &Range) {
377   // Emit offset in .debug_range as a relocatable label. emitDIE will handle
378   // emitting it appropriately.
379   MCSymbol *RangeSym =
380       Asm->GetTempSymbol("debug_ranges", DD->getNextRangeNumber());
382   auto *RangeSectionSym = DD->getRangeSectionSym();
384   // Under fission, ranges are specified by constant offsets relative to the
385   // CU's DW_AT_GNU_ranges_base.
386   if (DD->useSplitDwarf())
387     addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym, RangeSectionSym);
388   else
389     addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, RangeSym, RangeSectionSym);
391   RangeSpanList List(RangeSym);
392   for (const InsnRange &R : Range)
393     List.addRange(RangeSpan(DD->getLabelBeforeInsn(R.first),
394                             DD->getLabelAfterInsn(R.second)));
396   // Add the range list to the set of ranges to be emitted.
397   addRangeList(std::move(List));
400 void DwarfCompileUnit::attachRangesOrLowHighPC(
401     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
402   assert(!Ranges.empty());
403   if (Ranges.size() == 1)
404     attachLowHighPC(Die, DD->getLabelBeforeInsn(Ranges.front().first),
405                     DD->getLabelAfterInsn(Ranges.front().second));
406   else
407     addScopeRangeList(Die, Ranges);
410 // This scope represents inlined body of a function. Construct DIE to
411 // represent this concrete inlined copy of the function.
412 std::unique_ptr<DIE>
413 DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
414   assert(Scope->getScopeNode());
415   DIScope DS(Scope->getScopeNode());
416   DISubprogram InlinedSP = getDISubprogram(DS);
417   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
418   // was inlined from another compile unit.
419   DIE *OriginDIE = DD->getAbstractSPDies()[InlinedSP];
420   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
422   auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
423   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
425   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
427   // Add the call site information to the DIE.
428   DILocation DL(Scope->getInlinedAt());
429   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
430           getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
431   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
433   // Add name to the name table, we do this here because we're guaranteed
434   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
435   DD->addSubprogramNames(InlinedSP, *ScopeDIE);
437   return ScopeDIE;
440 // Construct new DW_TAG_lexical_block for this scope and attach
441 // DW_AT_low_pc/DW_AT_high_pc labels.
442 std::unique_ptr<DIE>
443 DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
444   if (DD->isLexicalScopeDIENull(Scope))
445     return nullptr;
447   auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
448   if (Scope->isAbstractScope())
449     return ScopeDIE;
451   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
453   return ScopeDIE;
456 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
457 std::unique_ptr<DIE> DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
458                                                             bool Abstract) {
459   auto D = constructVariableDIEImpl(DV, Abstract);
460   DV.setDIE(*D);
461   return D;
464 std::unique_ptr<DIE>
465 DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
466                                            bool Abstract) {
467   // Define variable debug information entry.
468   auto VariableDie = make_unique<DIE>(DV.getTag());
470   if (Abstract) {
471     applyVariableAttributes(DV, *VariableDie);
472     return VariableDie;
473   }
475   // Add variable address.
477   unsigned Offset = DV.getDotDebugLocOffset();
478   if (Offset != ~0U) {
479     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
480     return VariableDie;
481   }
483   // Check if variable is described by a DBG_VALUE instruction.
484   if (const MachineInstr *DVInsn = DV.getMInsn()) {
485     assert(DVInsn->getNumOperands() == 4);
486     if (DVInsn->getOperand(0).isReg()) {
487       const MachineOperand RegOp = DVInsn->getOperand(0);
488       // If the second operand is an immediate, this is an indirect value.
489       if (DVInsn->getOperand(1).isImm()) {
490         MachineLocation Location(RegOp.getReg(),
491                                  DVInsn->getOperand(1).getImm());
492         addVariableAddress(DV, *VariableDie, Location);
493       } else if (RegOp.getReg())
494         addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
495     } else if (DVInsn->getOperand(0).isImm())
496       addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
497     else if (DVInsn->getOperand(0).isFPImm())
498       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
499     else if (DVInsn->getOperand(0).isCImm())
500       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
501                        DV.getType());
503     return VariableDie;
504   }
506   // .. else use frame index.
507   int FI = DV.getFrameIndex();
508   if (FI != ~0) {
509     unsigned FrameReg = 0;
510     const TargetFrameLowering *TFI =
511         Asm->TM.getSubtargetImpl()->getFrameLowering();
512     int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
513     MachineLocation Location(FrameReg, Offset);
514     addVariableAddress(DV, *VariableDie, Location);
515   }
517   return VariableDie;
520 std::unique_ptr<DIE> DwarfCompileUnit::constructVariableDIE(
521     DbgVariable &DV, const LexicalScope &Scope, DIE *&ObjectPointer) {
522   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
523   if (DV.isObjectPointer())
524     ObjectPointer = Var.get();
525   return Var;
528 DIE *DwarfCompileUnit::createScopeChildrenDIE(
529     LexicalScope *Scope, SmallVectorImpl<std::unique_ptr<DIE>> &Children,
530     unsigned *ChildScopeCount) {
531   DIE *ObjectPointer = nullptr;
533   for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope))
534     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
536   unsigned ChildCountWithoutScopes = Children.size();
538   for (LexicalScope *LS : Scope->getChildren())
539     constructScopeDIE(LS, Children);
541   if (ChildScopeCount)
542     *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
544   return ObjectPointer;
547 void DwarfCompileUnit::constructSubprogramScopeDIE(LexicalScope *Scope) {
548   assert(Scope && Scope->getScopeNode());
549   assert(!Scope->getInlinedAt());
550   assert(!Scope->isAbstractScope());
551   DISubprogram Sub(Scope->getScopeNode());
553   assert(Sub.isSubprogram());
555   DD->getProcessedSPNodes().insert(Sub);
557   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
559   // If this is a variadic function, add an unspecified parameter.
560   DITypeArray FnArgs = Sub.getType().getTypeArray();
562   // Collect lexical scope children first.
563   // ObjectPointer might be a local (non-argument) local variable if it's a
564   // block's synthetic this pointer.
565   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
566     addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
568   // If we have a single element of null, it is a function that returns void.
569   // If we have more than one elements and the last one is null, it is a
570   // variadic function.
571   if (FnArgs.getNumElements() > 1 &&
572       !FnArgs.getElement(FnArgs.getNumElements() - 1))
573     ScopeDIE.addChild(make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
576 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
577                                                  DIE &ScopeDIE) {
578   // We create children when the scope DIE is not null.
579   SmallVector<std::unique_ptr<DIE>, 8> Children;
580   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
582   // Add children
583   for (auto &I : Children)
584     ScopeDIE.addChild(std::move(I));
586   return ObjectPointer;
589 void
590 DwarfCompileUnit::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
591   DIE *&AbsDef = DD->getAbstractSPDies()[Scope->getScopeNode()];
592   if (AbsDef)
593     return;
595   DISubprogram SP(Scope->getScopeNode());
597   DIE *ContextDIE;
599   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
600   // the important distinction that the DIDescriptor is not associated with the
601   // DIE (since the DIDescriptor will be associated with the concrete DIE, if
602   // any). It could be refactored to some common utility function.
603   if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
604     ContextDIE = &getUnitDie();
605     getOrCreateSubprogramDIE(SPDecl);
606   } else
607     ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
609   // Passing null as the associated DIDescriptor because the abstract definition
610   // shouldn't be found by lookup.
611   AbsDef =
612       &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, DIDescriptor());
613   applySubprogramAttributesToDefinition(SP, *AbsDef);
615   if (getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
616     addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
617   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef))
618     addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
621 std::unique_ptr<DIE>
622 DwarfCompileUnit::constructImportedEntityDIE(const DIImportedEntity &Module) {
623   assert(Module.Verify() &&
624          "Use one of the MDNode * overloads to handle invalid metadata");
625   std::unique_ptr<DIE> IMDie = make_unique<DIE>((dwarf::Tag)Module.getTag());
626   insertDIE(Module, IMDie.get());
627   DIE *EntityDie;
628   DIDescriptor Entity = resolve(Module.getEntity());
629   if (Entity.isNameSpace())
630     EntityDie = getOrCreateNameSpace(DINameSpace(Entity));
631   else if (Entity.isSubprogram())
632     EntityDie = getOrCreateSubprogramDIE(DISubprogram(Entity));
633   else if (Entity.isType())
634     EntityDie = getOrCreateTypeDIE(DIType(Entity));
635   else
636     EntityDie = getDIE(Entity);
637   assert(EntityDie);
638   addSourceLine(*IMDie, Module.getLineNumber(),
639                 Module.getContext().getFilename(),
640                 Module.getContext().getDirectory());
641   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
642   StringRef Name = Module.getName();
643   if (!Name.empty())
644     addString(*IMDie, dwarf::DW_AT_name, Name);
646   return IMDie;
649 void DwarfCompileUnit::finishSubprogramDefinition(DISubprogram SP) {
650   DIE *D = getDIE(SP);
651   if (DIE *AbsSPDIE = DD->getAbstractSPDies().lookup(SP)) {
652     if (D)
653       // If this subprogram has an abstract definition, reference that
654       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
655   } else {
656     if (!D && getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
657       // Lazily construct the subprogram if we didn't see either concrete or
658       // inlined versions during codegen. (except in -gmlt ^ where we want
659       // to omit these entirely)
660       D = getOrCreateSubprogramDIE(SP);
661     if (D)
662       // And attach the attributes
663       applySubprogramAttributesToDefinition(SP, *D);
664   }
667 } // end llvm namespace