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