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