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