[DWARF] Fix debug info generation for function static variables, typedefs, and records
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfCompileUnit.cpp
1 #include "DwarfCompileUnit.h"
2 #include "DwarfExpression.h"
3 #include "llvm/CodeGen/MachineFunction.h"
4 #include "llvm/IR/Constants.h"
5 #include "llvm/IR/DataLayout.h"
6 #include "llvm/IR/GlobalValue.h"
7 #include "llvm/IR/GlobalVariable.h"
8 #include "llvm/IR/Instruction.h"
9 #include "llvm/MC/MCAsmInfo.h"
10 #include "llvm/MC/MCStreamer.h"
11 #include "llvm/Target/TargetFrameLowering.h"
12 #include "llvm/Target/TargetLoweringObjectFile.h"
13 #include "llvm/Target/TargetMachine.h"
14 #include "llvm/Target/TargetRegisterInfo.h"
15 #include "llvm/Target/TargetSubtargetInfo.h"
16
17 namespace llvm {
18
19 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
20                                    AsmPrinter *A, DwarfDebug *DW,
21                                    DwarfFile *DWU)
22     : DwarfUnit(UID, dwarf::DW_TAG_compile_unit, Node, A, DW, DWU),
23       Skeleton(nullptr), BaseAddress(nullptr) {
24   insertDIE(Node, &getUnitDie());
25 }
26
27 /// addLabelAddress - Add a dwarf label attribute data and value using
28 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
29 ///
30 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
31                                        const MCSymbol *Label) {
32
33   // Don't use the address pool in non-fission or in the skeleton unit itself.
34   // FIXME: Once GDB supports this, it's probably worthwhile using the address
35   // pool from the skeleton - maybe even in non-fission (possibly fewer
36   // relocations by sharing them in the pool, but we have other ideas about how
37   // to reduce the number of relocations as well/instead).
38   if (!DD->useSplitDwarf() || !Skeleton)
39     return addLocalLabelAddress(Die, Attribute, Label);
40
41   if (Label)
42     DD->addArangeLabel(SymbolCU(this, Label));
43
44   unsigned idx = DD->getAddressPool().getIndex(Label);
45   Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_GNU_addr_index,
46                DIEInteger(idx));
47 }
48
49 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
50                                             dwarf::Attribute Attribute,
51                                             const MCSymbol *Label) {
52   if (Label)
53     DD->addArangeLabel(SymbolCU(this, Label));
54
55   if (Label)
56     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
57                  DIELabel(Label));
58   else
59     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
60                  DIEInteger(0));
61 }
62
63 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName,
64                                                StringRef DirName) {
65   // If we print assembly, we can't separate .file entries according to
66   // compile units. Thus all files will belong to the default compile unit.
67
68   // FIXME: add a better feature test than hasRawTextSupport. Even better,
69   // extend .file to support this.
70   return Asm->OutStreamer->EmitDwarfFileDirective(
71       0, DirName, FileName,
72       Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID());
73 }
74
75 // Return const expression if value is a GEP to access merged global
76 // constant. e.g.
77 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
78 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
79   const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
80   if (!CE || CE->getNumOperands() != 3 ||
81       CE->getOpcode() != Instruction::GetElementPtr)
82     return nullptr;
83
84   // First operand points to a global struct.
85   Value *Ptr = CE->getOperand(0);
86   if (!isa<GlobalValue>(Ptr) ||
87       !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
88     return nullptr;
89
90   // Second operand is zero.
91   const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
92   if (!CI || !CI->isZero())
93     return nullptr;
94
95   // Third operand is offset.
96   if (!isa<ConstantInt>(CE->getOperand(2)))
97     return nullptr;
98
99   return CE;
100 }
101
102 /// getOrCreateGlobalVariableDIE - get or create global variable DIE.
103 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
104   const DIGlobalVariable *GV, DIE *ContextDIE) {
105   // Check for pre-existence.
106   if (DIE *Die = getDIE(GV))
107     return Die;
108
109   assert(GV);
110
111   auto *GVContext = GV->getScope();
112   auto *GTy = DD->resolve(GV->getType());
113
114   // Construct the context before querying for the existence of the DIE in
115   // case such construction creates the DIE.
116   if (ContextDIE == nullptr)
117     ContextDIE = getOrCreateContextDIE(GVContext);
118
119   // Add to map.
120   DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
121   DIScope *DeclContext;
122   if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
123     DeclContext = resolve(SDMDecl->getScope());
124     assert(SDMDecl->isStaticMember() && "Expected static member decl");
125     assert(GV->isDefinition());
126     // We need the declaration DIE that is in the static member's class.
127     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
128     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
129   } else {
130     DeclContext = GV->getScope();
131     // Add name and type.
132     addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
133     addType(*VariableDIE, GTy);
134
135     // Add scoping info.
136     if (!GV->isLocalToUnit())
137       addFlag(*VariableDIE, dwarf::DW_AT_external);
138
139     // Add line number info.
140     addSourceLine(*VariableDIE, GV);
141   }
142
143   if (!GV->isDefinition())
144     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
145   else
146     addGlobalName(GV->getName(), *VariableDIE, DeclContext);
147
148   // Add location.
149   bool addToAccelTable = false;
150   if (auto *Global = dyn_cast_or_null<GlobalVariable>(GV->getVariable())) {
151     addToAccelTable = true;
152     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
153     const MCSymbol *Sym = Asm->getSymbol(Global);
154     if (Global->isThreadLocal()) {
155       // FIXME: Make this work with -gsplit-dwarf.
156       unsigned PointerSize = Asm->getDataLayout().getPointerSize();
157       assert((PointerSize == 4 || PointerSize == 8) &&
158              "Add support for other sizes if necessary");
159       // Based on GCC's support for TLS:
160       if (!DD->useSplitDwarf()) {
161         // 1) Start with a constNu of the appropriate pointer size
162         addUInt(*Loc, dwarf::DW_FORM_data1,
163                 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
164         // 2) containing the (relocated) offset of the TLS variable
165         //    within the module's TLS block.
166         addExpr(*Loc, dwarf::DW_FORM_udata,
167                 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
168       } else {
169         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
170         addUInt(*Loc, dwarf::DW_FORM_udata,
171                 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
172       }
173       // 3) followed by an OP to make the debugger do a TLS lookup.
174       addUInt(*Loc, dwarf::DW_FORM_data1,
175               DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
176                                     : dwarf::DW_OP_form_tls_address);
177     } else {
178       DD->addArangeLabel(SymbolCU(this, Sym));
179       addOpAddress(*Loc, Sym);
180     }
181
182     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
183     addLinkageName(*VariableDIE, GV->getLinkageName());
184   } else if (const ConstantInt *CI =
185                  dyn_cast_or_null<ConstantInt>(GV->getVariable())) {
186     addConstantValue(*VariableDIE, CI, GTy);
187   } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getVariable())) {
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   }
202
203   if (addToAccelTable) {
204     DD->addAccelName(GV->getName(), *VariableDIE);
205
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   }
211
212   return VariableDIE;
213 }
214
215 void DwarfCompileUnit::addRange(RangeSpan Range) {
216   bool SameAsPrevCU = this == DD->getPrevCU();
217   DD->setPrevCU(this);
218   // If we have no current ranges just add the range and return, otherwise,
219   // check the current section and CU against the previous section and CU we
220   // emitted into and the subprogram was contained within. If these are the
221   // same then extend our current range, otherwise add this as a new range.
222   if (CURanges.empty() || !SameAsPrevCU ||
223       (&CURanges.back().getEnd()->getSection() !=
224        &Range.getEnd()->getSection())) {
225     CURanges.push_back(Range);
226     return;
227   }
228
229   CURanges.back().setEnd(Range.getEnd());
230 }
231
232 DIE::value_iterator
233 DwarfCompileUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
234                                   const MCSymbol *Label, const MCSymbol *Sec) {
235   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
236     return addLabel(Die, Attribute,
237                     DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
238                                                : dwarf::DW_FORM_data4,
239                     Label);
240   return addSectionDelta(Die, Attribute, Label, Sec);
241 }
242
243 void DwarfCompileUnit::initStmtList() {
244   // Define start line table label for each Compile Unit.
245   MCSymbol *LineTableStartSym =
246       Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
247
248   // DW_AT_stmt_list is a offset of line number information for this
249   // compile unit in debug_line section. For split dwarf this is
250   // left in the skeleton CU and so not included.
251   // The line table entries are not always emitted in assembly, so it
252   // is not okay to use line_table_start here.
253   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
254   StmtListValue =
255       addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
256                       TLOF.getDwarfLineSection()->getBeginSymbol());
257 }
258
259 void DwarfCompileUnit::applyStmtList(DIE &D) {
260   D.addValue(DIEValueAllocator, *StmtListValue);
261 }
262
263 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
264                                        const MCSymbol *End) {
265   assert(Begin && "Begin label should not be null!");
266   assert(End && "End label should not be null!");
267   assert(Begin->isDefined() && "Invalid starting label");
268   assert(End->isDefined() && "Invalid end label");
269
270   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
271   if (DD->getDwarfVersion() < 4)
272     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
273   else
274     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
275 }
276
277 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
278 // and DW_AT_high_pc attributes. If there are global variables in this
279 // scope then create and insert DIEs for these variables.
280 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
281   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
282
283   attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd());
284   if (!DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
285           *DD->getCurrentFunction()))
286     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
287
288   // Only include DW_AT_frame_base in full debug info
289   if (!includeMinimalInlineScopes()) {
290     const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo();
291     MachineLocation Location(RI->getFrameRegister(*Asm->MF));
292     if (RI->isPhysicalRegister(Location.getReg()))
293       addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
294   }
295
296   // Add name to the name table, we do this here because we're guaranteed
297   // to have concrete versions of our DW_TAG_subprogram nodes.
298   DD->addSubprogramNames(SP, *SPDie);
299
300   return *SPDie;
301 }
302
303 // Construct a DIE for this scope.
304 void DwarfCompileUnit::constructScopeDIE(
305     LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
306   if (!Scope || !Scope->getScopeNode())
307     return;
308
309   auto *DS = Scope->getScopeNode();
310
311   assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
312          "Only handle inlined subprograms here, use "
313          "constructSubprogramScopeDIE for non-inlined "
314          "subprograms");
315
316   SmallVector<DIE *, 8> Children;
317
318   // We try to create the scope DIE first, then the children DIEs. This will
319   // avoid creating un-used children then removing them later when we find out
320   // the scope DIE is null.
321   DIE *ScopeDIE;
322   if (Scope->getParent() && isa<DISubprogram>(DS)) {
323     ScopeDIE = constructInlinedScopeDIE(Scope);
324     if (!ScopeDIE)
325       return;
326     // We create children when the scope DIE is not null.
327     createScopeChildrenDIE(Scope, Children);
328   } else {
329     // Early exit when we know the scope DIE is going to be null.
330     if (DD->isLexicalScopeDIENull(Scope))
331       return;
332
333     unsigned ChildScopeCount;
334
335     // We create children here when we know the scope DIE is not going to be
336     // null and the children will be added to the scope DIE.
337     createScopeChildrenDIE(Scope, Children, &ChildScopeCount);
338
339
340     DwarfDebug::LocalDeclMapRange LocalDeclNodeRangeForScope(nullptr, nullptr);
341     // Skip local decls in gmlt-like data.
342     if (!includeMinimalInlineScopes())
343       LocalDeclNodeRangeForScope = DD->findLocalDeclNodesForScope(DS);
344
345     // If there are only other scopes as children, put them directly in the
346     // parent instead, as this scope would serve no purpose.
347     if (Children.size() == ChildScopeCount &&
348         empty(LocalDeclNodeRangeForScope)) {
349       FinalChildren.insert(FinalChildren.end(),
350                            std::make_move_iterator(Children.begin()),
351                            std::make_move_iterator(Children.end()));
352       return;
353     }
354     ScopeDIE = constructLexicalScopeDIE(Scope);
355     assert(ScopeDIE && "Scope DIE should not be null.");
356
357     for (const auto &DI : LocalDeclNodeRangeForScope) {
358       if (auto *IE = dyn_cast<DIImportedEntity>(DI.second))
359         Children.push_back(constructImportedEntityDIE(IE));
360       else if (auto *GV = dyn_cast<DIGlobalVariable>(DI.second))
361         getOrCreateGlobalVariableDIE(GV, ScopeDIE);
362       else if (auto *RT = dyn_cast<DIType>(DI.second))
363         getOrCreateTypeDIE(RT, ScopeDIE);
364     }
365   }
366
367   // Add children
368   for (auto &I : Children)
369     ScopeDIE->addChild(std::move(I));
370
371   FinalChildren.push_back(std::move(ScopeDIE));
372 }
373
374 DIE::value_iterator
375 DwarfCompileUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
376                                   const MCSymbol *Hi, const MCSymbol *Lo) {
377   return Die.addValue(DIEValueAllocator, Attribute,
378                       DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
379                                                  : dwarf::DW_FORM_data4,
380                       new (DIEValueAllocator) DIEDelta(Hi, Lo));
381 }
382
383 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
384                                          SmallVector<RangeSpan, 2> Range) {
385   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
386
387   // Emit offset in .debug_range as a relocatable label. emitDIE will handle
388   // emitting it appropriately.
389   const MCSymbol *RangeSectionSym =
390       TLOF.getDwarfRangesSection()->getBeginSymbol();
391
392   RangeSpanList List(Asm->createTempSymbol("debug_ranges"), std::move(Range));
393
394   // Under fission, ranges are specified by constant offsets relative to the
395   // CU's DW_AT_GNU_ranges_base.
396   if (isDwoUnit())
397     addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
398                     RangeSectionSym);
399   else
400     addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
401                     RangeSectionSym);
402
403   // Add the range list to the set of ranges to be emitted.
404   (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
405 }
406
407 void DwarfCompileUnit::attachRangesOrLowHighPC(
408     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
409   if (Ranges.size() == 1) {
410     const auto &single = Ranges.front();
411     attachLowHighPC(Die, single.getStart(), single.getEnd());
412   } else
413     addScopeRangeList(Die, std::move(Ranges));
414 }
415
416 void DwarfCompileUnit::attachRangesOrLowHighPC(
417     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
418   SmallVector<RangeSpan, 2> List;
419   List.reserve(Ranges.size());
420   for (const InsnRange &R : Ranges)
421     List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
422                              DD->getLabelAfterInsn(R.second)));
423   attachRangesOrLowHighPC(Die, std::move(List));
424 }
425
426 // This scope represents inlined body of a function. Construct DIE to
427 // represent this concrete inlined copy of the function.
428 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
429   assert(Scope->getScopeNode());
430   auto *DS = Scope->getScopeNode();
431   auto *InlinedSP = getDISubprogram(DS);
432   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
433   // was inlined from another compile unit.
434   DIE *OriginDIE = DU->getAbstractSPDies()[InlinedSP];
435   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
436
437   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
438   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
439
440   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
441
442   // Add the call site information to the DIE.
443   const DILocation *IA = Scope->getInlinedAt();
444   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
445           getOrCreateSourceID(IA->getFilename(), IA->getDirectory()));
446   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
447
448   // Add name to the name table, we do this here because we're guaranteed
449   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
450   DD->addSubprogramNames(InlinedSP, *ScopeDIE);
451
452   return ScopeDIE;
453 }
454
455 // Construct new DW_TAG_lexical_block for this scope and attach
456 // DW_AT_low_pc/DW_AT_high_pc labels.
457 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
458   if (DD->isLexicalScopeDIENull(Scope))
459     return nullptr;
460
461   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
462   if (Scope->isAbstractScope())
463     return ScopeDIE;
464
465   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
466
467   return ScopeDIE;
468 }
469
470 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
471 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
472   auto D = constructVariableDIEImpl(DV, Abstract);
473   DV.setDIE(*D);
474   return D;
475 }
476
477 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
478                                                 bool Abstract) {
479   // Define variable debug information entry.
480   auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
481
482   if (Abstract) {
483     applyVariableAttributes(DV, *VariableDie);
484     return VariableDie;
485   }
486
487   // Add variable address.
488
489   unsigned Offset = DV.getDebugLocListIndex();
490   if (Offset != ~0U) {
491     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
492     return VariableDie;
493   }
494
495   // Check if variable is described by a DBG_VALUE instruction.
496   if (const MachineInstr *DVInsn = DV.getMInsn()) {
497     assert(DVInsn->getNumOperands() == 4);
498     if (DVInsn->getOperand(0).isReg()) {
499       const MachineOperand RegOp = DVInsn->getOperand(0);
500       // If the second operand is an immediate, this is an indirect value.
501       if (DVInsn->getOperand(1).isImm()) {
502         MachineLocation Location(RegOp.getReg(),
503                                  DVInsn->getOperand(1).getImm());
504         addVariableAddress(DV, *VariableDie, Location);
505       } else if (RegOp.getReg())
506         addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
507     } else if (DVInsn->getOperand(0).isImm())
508       addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
509     else if (DVInsn->getOperand(0).isFPImm())
510       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
511     else if (DVInsn->getOperand(0).isCImm())
512       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
513                        DV.getType());
514
515     return VariableDie;
516   }
517
518   // .. else use frame index.
519   if (DV.getFrameIndex().empty())
520     return VariableDie;
521
522   auto Expr = DV.getExpression().begin();
523   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
524   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
525   for (auto FI : DV.getFrameIndex()) {
526     unsigned FrameReg = 0;
527     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
528     int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
529     assert(Expr != DV.getExpression().end() &&
530            "Wrong number of expressions");
531     DwarfExpr.AddMachineRegIndirect(FrameReg, Offset);
532     DwarfExpr.AddExpression((*Expr)->expr_op_begin(), (*Expr)->expr_op_end());
533     ++Expr;
534   }
535   addBlock(*VariableDie, dwarf::DW_AT_location, Loc);
536
537   return VariableDie;
538 }
539
540 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
541                                             const LexicalScope &Scope,
542                                             DIE *&ObjectPointer) {
543   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
544   if (DV.isObjectPointer())
545     ObjectPointer = Var;
546   return Var;
547 }
548
549 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
550                                               SmallVectorImpl<DIE *> &Children,
551                                               unsigned *ChildScopeCount) {
552   DIE *ObjectPointer = nullptr;
553
554   for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope))
555     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
556
557   unsigned ChildCountWithoutScopes = Children.size();
558
559   for (LexicalScope *LS : Scope->getChildren())
560     constructScopeDIE(LS, Children);
561
562   if (ChildScopeCount)
563     *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
564
565   return ObjectPointer;
566 }
567
568 void DwarfCompileUnit::constructSubprogramScopeDIE(LexicalScope *Scope) {
569   assert(Scope && Scope->getScopeNode());
570   assert(!Scope->getInlinedAt());
571   assert(!Scope->isAbstractScope());
572   auto *Sub = cast<DISubprogram>(Scope->getScopeNode());
573
574   DD->getProcessedSPNodes().insert(Sub);
575
576   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
577
578   // If this is a variadic function, add an unspecified parameter.
579   DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
580
581   // Collect lexical scope children first.
582   // ObjectPointer might be a local (non-argument) local variable if it's a
583   // block's synthetic this pointer.
584   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
585     addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
586
587   // If we have a single element of null, it is a function that returns void.
588   // If we have more than one elements and the last one is null, it is a
589   // variadic function.
590   if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
591       !includeMinimalInlineScopes())
592     ScopeDIE.addChild(
593         DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
594 }
595
596 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
597                                                  DIE &ScopeDIE) {
598   // We create children when the scope DIE is not null.
599   SmallVector<DIE *, 8> Children;
600   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
601
602   // Add children
603   for (auto &I : Children)
604     ScopeDIE.addChild(std::move(I));
605
606   return ObjectPointer;
607 }
608
609 void
610 DwarfCompileUnit::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
611   DIE *&AbsDef = DU->getAbstractSPDies()[Scope->getScopeNode()];
612   if (AbsDef)
613     return;
614
615   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
616
617   DIE *ContextDIE;
618
619   if (includeMinimalInlineScopes())
620     ContextDIE = &getUnitDie();
621   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
622   // the important distinction that the debug node is not associated with the
623   // DIE (since the debug node will be associated with the concrete DIE, if
624   // any). It could be refactored to some common utility function.
625   else if (auto *SPDecl = SP->getDeclaration()) {
626     ContextDIE = &getUnitDie();
627     getOrCreateSubprogramDIE(SPDecl);
628   } else
629     ContextDIE = getOrCreateContextDIE(resolve(SP->getScope()));
630
631   // Passing null as the associated node because the abstract definition
632   // shouldn't be found by lookup.
633   AbsDef = &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
634   applySubprogramAttributesToDefinition(SP, *AbsDef);
635
636   if (!includeMinimalInlineScopes())
637     addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
638   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef))
639     addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
640 }
641
642 DIE *DwarfCompileUnit::constructImportedEntityDIE(
643     const DIImportedEntity *Module) {
644   DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
645   insertDIE(Module, IMDie);
646   DIE *EntityDie;
647   auto *Entity = resolve(Module->getEntity());
648   if (auto *NS = dyn_cast<DINamespace>(Entity))
649     EntityDie = getOrCreateNameSpace(NS);
650   else if (auto *M = dyn_cast<DIModule>(Entity))
651     EntityDie = getOrCreateModule(M);
652   else if (auto *SP = dyn_cast<DISubprogram>(Entity))
653     EntityDie = getOrCreateSubprogramDIE(SP);
654   else if (auto *T = dyn_cast<DIType>(Entity))
655     EntityDie = getOrCreateTypeDIE(T);
656   else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
657     EntityDie = getOrCreateGlobalVariableDIE(GV);
658   else
659     EntityDie = getDIE(Entity);
660   assert(EntityDie);
661   addSourceLine(*IMDie, Module->getLine(), Module->getScope()->getFilename(),
662                 Module->getScope()->getDirectory());
663   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
664   StringRef Name = Module->getName();
665   if (!Name.empty())
666     addString(*IMDie, dwarf::DW_AT_name, Name);
667
668   return IMDie;
669 }
670
671 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
672   DIE *D = getDIE(SP);
673   if (DIE *AbsSPDIE = DU->getAbstractSPDies().lookup(SP)) {
674     if (D)
675       // If this subprogram has an abstract definition, reference that
676       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
677   } else {
678     if (!D && !includeMinimalInlineScopes())
679       // Lazily construct the subprogram if we didn't see either concrete or
680       // inlined versions during codegen. (except in -gmlt ^ where we want
681       // to omit these entirely)
682       D = getOrCreateSubprogramDIE(SP);
683     if (D)
684       // And attach the attributes
685       applySubprogramAttributesToDefinition(SP, *D);
686   }
687 }
688 void DwarfCompileUnit::collectDeadVariables(const DISubprogram *SP) {
689   assert(SP && "CU's subprogram list contains a non-subprogram");
690   assert(SP->isDefinition() &&
691          "CU's subprogram list contains a subprogram declaration");
692   auto Variables = SP->getVariables();
693   if (Variables.size() == 0)
694     return;
695
696   DIE *SPDIE = DU->getAbstractSPDies().lookup(SP);
697   if (!SPDIE)
698     SPDIE = getDIE(SP);
699   assert(SPDIE);
700   for (const DILocalVariable *DV : Variables) {
701     DbgVariable NewVar(DV, /* IA */ nullptr, DD);
702     auto VariableDie = constructVariableDIE(NewVar);
703     applyVariableAttributes(NewVar, *VariableDie);
704     SPDIE->addChild(std::move(VariableDie));
705   }
706 }
707
708 void DwarfCompileUnit::emitHeader(bool UseOffsets) {
709   // Don't bother labeling the .dwo unit, as its offset isn't used.
710   if (!Skeleton) {
711     LabelBegin = Asm->createTempSymbol("cu_begin");
712     Asm->OutStreamer->EmitLabel(LabelBegin);
713   }
714
715   DwarfUnit::emitHeader(UseOffsets);
716 }
717
718 /// addGlobalName - Add a new global name to the compile unit.
719 void DwarfCompileUnit::addGlobalName(StringRef Name, DIE &Die,
720                                      const DIScope *Context) {
721   if (includeMinimalInlineScopes())
722     return;
723   std::string FullName = getParentContextString(Context) + Name.str();
724   GlobalNames[FullName] = &Die;
725 }
726
727 /// Add a new global type to the unit.
728 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
729                                      const DIScope *Context) {
730   if (includeMinimalInlineScopes())
731     return;
732   std::string FullName = getParentContextString(Context) + Ty->getName().str();
733   GlobalTypes[FullName] = &Die;
734 }
735
736 /// addVariableAddress - Add DW_AT_location attribute for a
737 /// DbgVariable based on provided MachineLocation.
738 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
739                                           MachineLocation Location) {
740   if (DV.hasComplexAddress())
741     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
742   else if (DV.isBlockByrefVariable())
743     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
744   else
745     addAddress(Die, dwarf::DW_AT_location, Location);
746 }
747
748 /// Add an address attribute to a die based on the location provided.
749 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
750                                   const MachineLocation &Location) {
751   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
752
753   bool validReg;
754   if (Location.isReg())
755     validReg = addRegisterOpPiece(*Loc, Location.getReg());
756   else
757     validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
758
759   if (!validReg)
760     return;
761
762   // Now attach the location information to the DIE.
763   addBlock(Die, Attribute, Loc);
764 }
765
766 /// Start with the address based on the location provided, and generate the
767 /// DWARF information necessary to find the actual variable given the extra
768 /// address information encoded in the DbgVariable, starting from the starting
769 /// location.  Add the DWARF information to the die.
770 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
771                                          dwarf::Attribute Attribute,
772                                          const MachineLocation &Location) {
773   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
774   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
775   assert(DV.getExpression().size() == 1);
776   const DIExpression *Expr = DV.getExpression().back();
777   bool ValidReg;
778   if (Location.getOffset()) {
779     ValidReg = DwarfExpr.AddMachineRegIndirect(Location.getReg(),
780                                                Location.getOffset());
781     if (ValidReg)
782       DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end());
783   } else
784     ValidReg = DwarfExpr.AddMachineRegExpression(Expr, Location.getReg());
785
786   // Now attach the location information to the DIE.
787   if (ValidReg)
788     addBlock(Die, Attribute, Loc);
789 }
790
791 /// Add a Dwarf loclistptr attribute data and value.
792 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
793                                        unsigned Index) {
794   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
795                                                 : dwarf::DW_FORM_data4;
796   Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
797 }
798
799 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
800                                                DIE &VariableDie) {
801   StringRef Name = Var.getName();
802   if (!Name.empty())
803     addString(VariableDie, dwarf::DW_AT_name, Name);
804   addSourceLine(VariableDie, Var.getVariable());
805   addType(VariableDie, Var.getType());
806   if (Var.isArtificial())
807     addFlag(VariableDie, dwarf::DW_AT_artificial);
808 }
809
810 /// Add a Dwarf expression attribute data and value.
811 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
812                                const MCExpr *Expr) {
813   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
814 }
815
816 void DwarfCompileUnit::applySubprogramAttributesToDefinition(
817     const DISubprogram *SP, DIE &SPDie) {
818   auto *SPDecl = SP->getDeclaration();
819   auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope());
820   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
821   addGlobalName(SP->getName(), SPDie, Context);
822 }
823
824 bool DwarfCompileUnit::isDwoUnit() const {
825   return DD->useSplitDwarf() && Skeleton;
826 }
827
828 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
829   return getCUNode()->getEmissionKind() == DIBuilder::LineTablesOnly ||
830          (DD->useSplitDwarf() && !Skeleton);
831 }
832 } // end llvm namespace