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