DwarfDebug.cpp revision 1ced208be9cab0f994c5df9000da36bc313b2507
1//===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
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 writing dwarf debug info into asm files.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "dwarfdebug"
15#include "DwarfDebug.h"
16#include "DIE.h"
17#include "DwarfAccelTable.h"
18#include "DwarfCompileUnit.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/Triple.h"
23#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineModuleInfo.h"
25#include "llvm/DIBuilder.h"
26#include "llvm/DebugInfo.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Module.h"
31#include "llvm/MC/MCAsmInfo.h"
32#include "llvm/MC/MCSection.h"
33#include "llvm/MC/MCStreamer.h"
34#include "llvm/MC/MCSymbol.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/FormattedStream.h"
39#include "llvm/Support/Path.h"
40#include "llvm/Support/Timer.h"
41#include "llvm/Support/ValueHandle.h"
42#include "llvm/Target/TargetFrameLowering.h"
43#include "llvm/Target/TargetLoweringObjectFile.h"
44#include "llvm/Target/TargetMachine.h"
45#include "llvm/Target/TargetOptions.h"
46#include "llvm/Target/TargetRegisterInfo.h"
47using namespace llvm;
48
49static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
50                                              cl::Hidden,
51     cl::desc("Disable debug info printing"));
52
53static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
54     cl::desc("Make an absence of debug location information explicit."),
55     cl::init(false));
56
57namespace {
58  enum DefaultOnOff {
59    Default, Enable, Disable
60  };
61}
62
63static cl::opt<DefaultOnOff> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
64     cl::desc("Output prototype dwarf accelerator tables."),
65     cl::values(
66                clEnumVal(Default, "Default for platform"),
67                clEnumVal(Enable, "Enabled"),
68                clEnumVal(Disable, "Disabled"),
69                clEnumValEnd),
70     cl::init(Default));
71
72static cl::opt<DefaultOnOff> DarwinGDBCompat("darwin-gdb-compat", cl::Hidden,
73     cl::desc("Compatibility with Darwin gdb."),
74     cl::values(
75                clEnumVal(Default, "Default for platform"),
76                clEnumVal(Enable, "Enabled"),
77                clEnumVal(Disable, "Disabled"),
78                clEnumValEnd),
79     cl::init(Default));
80
81static cl::opt<DefaultOnOff> SplitDwarf("split-dwarf", cl::Hidden,
82     cl::desc("Output prototype dwarf split debug info."),
83     cl::values(
84                clEnumVal(Default, "Default for platform"),
85                clEnumVal(Enable, "Enabled"),
86                clEnumVal(Disable, "Disabled"),
87                clEnumValEnd),
88     cl::init(Default));
89
90namespace {
91  const char *DWARFGroupName = "DWARF Emission";
92  const char *DbgTimerName = "DWARF Debug Writer";
93} // end anonymous namespace
94
95//===----------------------------------------------------------------------===//
96
97// Configuration values for initial hash set sizes (log2).
98//
99static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
100
101namespace llvm {
102
103DIType DbgVariable::getType() const {
104  DIType Ty = Var.getType();
105  // FIXME: isBlockByrefVariable should be reformulated in terms of complex
106  // addresses instead.
107  if (Var.isBlockByrefVariable()) {
108    /* Byref variables, in Blocks, are declared by the programmer as
109       "SomeType VarName;", but the compiler creates a
110       __Block_byref_x_VarName struct, and gives the variable VarName
111       either the struct, or a pointer to the struct, as its type.  This
112       is necessary for various behind-the-scenes things the compiler
113       needs to do with by-reference variables in blocks.
114
115       However, as far as the original *programmer* is concerned, the
116       variable should still have type 'SomeType', as originally declared.
117
118       The following function dives into the __Block_byref_x_VarName
119       struct to find the original type of the variable.  This will be
120       passed back to the code generating the type for the Debug
121       Information Entry for the variable 'VarName'.  'VarName' will then
122       have the original type 'SomeType' in its debug information.
123
124       The original type 'SomeType' will be the type of the field named
125       'VarName' inside the __Block_byref_x_VarName struct.
126
127       NOTE: In order for this to not completely fail on the debugger
128       side, the Debug Information Entry for the variable VarName needs to
129       have a DW_AT_location that tells the debugger how to unwind through
130       the pointers and __Block_byref_x_VarName struct to find the actual
131       value of the variable.  The function addBlockByrefType does this.  */
132    DIType subType = Ty;
133    unsigned tag = Ty.getTag();
134
135    if (tag == dwarf::DW_TAG_pointer_type) {
136      DIDerivedType DTy = DIDerivedType(Ty);
137      subType = DTy.getTypeDerivedFrom();
138    }
139
140    DICompositeType blockStruct = DICompositeType(subType);
141    DIArray Elements = blockStruct.getTypeArray();
142
143    for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
144      DIDescriptor Element = Elements.getElement(i);
145      DIDerivedType DT = DIDerivedType(Element);
146      if (getName() == DT.getName())
147        return (DT.getTypeDerivedFrom());
148    }
149  }
150  return Ty;
151}
152
153} // end llvm namespace
154
155DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
156  : Asm(A), MMI(Asm->MMI), FirstCU(0),
157    AbbreviationsSet(InitAbbreviationsSetSize),
158    SourceIdMap(DIEValueAllocator),
159    PrevLabel(NULL), GlobalCUIndexCount(0),
160    InfoHolder(A, &AbbreviationsSet, &Abbreviations, "info_string",
161               DIEValueAllocator),
162    SkeletonCU(0),
163    SkeletonAbbrevSet(InitAbbreviationsSetSize),
164    SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, "skel_string",
165                   DIEValueAllocator) {
166
167  DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
168  DwarfStrSectionSym = TextSectionSym = 0;
169  DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
170  DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
171  FunctionBeginSym = FunctionEndSym = 0;
172
173  // Turn on accelerator tables and older gdb compatibility
174  // for Darwin.
175  bool IsDarwin = Triple(M->getTargetTriple()).isOSDarwin();
176  if (DarwinGDBCompat == Default) {
177    if (IsDarwin)
178      IsDarwinGDBCompat = true;
179    else
180      IsDarwinGDBCompat = false;
181  } else
182    IsDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
183
184  if (DwarfAccelTables == Default) {
185    if (IsDarwin)
186      HasDwarfAccelTables = true;
187    else
188      HasDwarfAccelTables = false;
189  } else
190    HasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
191
192  if (SplitDwarf == Default)
193    HasSplitDwarf = false;
194  else
195    HasSplitDwarf = SplitDwarf == Enable ? true : false;
196
197  {
198    NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
199    beginModule();
200  }
201}
202DwarfDebug::~DwarfDebug() {
203}
204
205// Switch to the specified MCSection and emit an assembler
206// temporary label to it if SymbolStem is specified.
207static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
208                                const char *SymbolStem = 0) {
209  Asm->OutStreamer.SwitchSection(Section);
210  if (!SymbolStem) return 0;
211
212  MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
213  Asm->OutStreamer.EmitLabel(TmpSym);
214  return TmpSym;
215}
216
217MCSymbol *DwarfUnits::getStringPoolSym() {
218  return Asm->GetTempSymbol(StringPref);
219}
220
221MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
222  std::pair<MCSymbol*, unsigned> &Entry =
223    StringPool.GetOrCreateValue(Str).getValue();
224  if (Entry.first) return Entry.first;
225
226  Entry.second = NextStringPoolNumber++;
227  return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
228}
229
230unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
231  std::pair<MCSymbol*, unsigned> &Entry =
232    StringPool.GetOrCreateValue(Str).getValue();
233  if (Entry.first) return Entry.second;
234
235  Entry.second = NextStringPoolNumber++;
236  Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
237  return Entry.second;
238}
239
240// Define a unique number for the abbreviation.
241//
242void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
243  // Profile the node so that we can make it unique.
244  FoldingSetNodeID ID;
245  Abbrev.Profile(ID);
246
247  // Check the set for priors.
248  DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
249
250  // If it's newly added.
251  if (InSet == &Abbrev) {
252    // Add to abbreviation list.
253    Abbreviations->push_back(&Abbrev);
254
255    // Assign the vector position + 1 as its number.
256    Abbrev.setNumber(Abbreviations->size());
257  } else {
258    // Assign existing abbreviation number.
259    Abbrev.setNumber(InSet->getNumber());
260  }
261}
262
263// If special LLVM prefix that is used to inform the asm
264// printer to not emit usual symbol prefix before the symbol name is used then
265// return linkage name after skipping this special LLVM prefix.
266static StringRef getRealLinkageName(StringRef LinkageName) {
267  char One = '\1';
268  if (LinkageName.startswith(StringRef(&One, 1)))
269    return LinkageName.substr(1);
270  return LinkageName;
271}
272
273static bool isObjCClass(StringRef Name) {
274  return Name.startswith("+") || Name.startswith("-");
275}
276
277static bool hasObjCCategory(StringRef Name) {
278  if (!isObjCClass(Name)) return false;
279
280  size_t pos = Name.find(')');
281  if (pos != std::string::npos) {
282    if (Name[pos+1] != ' ') return false;
283    return true;
284  }
285  return false;
286}
287
288static void getObjCClassCategory(StringRef In, StringRef &Class,
289                                 StringRef &Category) {
290  if (!hasObjCCategory(In)) {
291    Class = In.slice(In.find('[') + 1, In.find(' '));
292    Category = "";
293    return;
294  }
295
296  Class = In.slice(In.find('[') + 1, In.find('('));
297  Category = In.slice(In.find('[') + 1, In.find(' '));
298  return;
299}
300
301static StringRef getObjCMethodName(StringRef In) {
302  return In.slice(In.find(' ') + 1, In.find(']'));
303}
304
305// Add the various names to the Dwarf accelerator table names.
306static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
307                               DIE* Die) {
308  if (!SP.isDefinition()) return;
309
310  TheCU->addAccelName(SP.getName(), Die);
311
312  // If the linkage name is different than the name, go ahead and output
313  // that as well into the name table.
314  if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
315    TheCU->addAccelName(SP.getLinkageName(), Die);
316
317  // If this is an Objective-C selector name add it to the ObjC accelerator
318  // too.
319  if (isObjCClass(SP.getName())) {
320    StringRef Class, Category;
321    getObjCClassCategory(SP.getName(), Class, Category);
322    TheCU->addAccelObjC(Class, Die);
323    if (Category != "")
324      TheCU->addAccelObjC(Category, Die);
325    // Also add the base method name to the name table.
326    TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
327  }
328}
329
330// Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
331// and DW_AT_high_pc attributes. If there are global variables in this
332// scope then create and insert DIEs for these variables.
333DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
334                                          const MDNode *SPNode) {
335  DIE *SPDie = SPCU->getDIE(SPNode);
336
337  assert(SPDie && "Unable to find subprogram DIE!");
338  DISubprogram SP(SPNode);
339
340  // If we're updating an abstract DIE, then we will be adding the children and
341  // object pointer later on. But what we don't want to do is process the
342  // concrete DIE twice.
343  if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
344    // Pick up abstract subprogram DIE.
345    SPDie = new DIE(dwarf::DW_TAG_subprogram);
346    SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
347                      dwarf::DW_FORM_ref4, AbsSPDIE);
348    SPCU->addDie(SPDie);
349  } else {
350    DISubprogram SPDecl = SP.getFunctionDeclaration();
351    if (!SPDecl.isSubprogram()) {
352      // There is not any need to generate specification DIE for a function
353      // defined at compile unit level. If a function is defined inside another
354      // function then gdb prefers the definition at top level and but does not
355      // expect specification DIE in parent function. So avoid creating
356      // specification DIE for a function defined inside a function.
357      if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
358          !SP.getContext().isFile() &&
359          !isSubprogramContext(SP.getContext())) {
360        SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
361
362        // Add arguments.
363        DICompositeType SPTy = SP.getType();
364        DIArray Args = SPTy.getTypeArray();
365        unsigned SPTag = SPTy.getTag();
366        if (SPTag == dwarf::DW_TAG_subroutine_type)
367          for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
368            DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
369            DIType ATy = DIType(Args.getElement(i));
370            SPCU->addType(Arg, ATy);
371            if (ATy.isArtificial())
372              SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
373            if (ATy.isObjectPointer())
374              SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
375                                dwarf::DW_FORM_ref4, Arg);
376            SPDie->addChild(Arg);
377          }
378        DIE *SPDeclDie = SPDie;
379        SPDie = new DIE(dwarf::DW_TAG_subprogram);
380        SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
381                          dwarf::DW_FORM_ref4, SPDeclDie);
382        SPCU->addDie(SPDie);
383      }
384    }
385  }
386
387  SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
388                 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
389  SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
390                 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
391  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
392  MachineLocation Location(RI->getFrameRegister(*Asm->MF));
393  SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
394
395  // Add name to the name table, we do this here because we're guaranteed
396  // to have concrete versions of our DW_TAG_subprogram nodes.
397  addSubprogramNames(SPCU, SP, SPDie);
398
399  return SPDie;
400}
401
402// Construct new DW_TAG_lexical_block for this scope and attach
403// DW_AT_low_pc/DW_AT_high_pc labels.
404DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
405                                          LexicalScope *Scope) {
406  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
407  if (Scope->isAbstractScope())
408    return ScopeDIE;
409
410  const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
411  if (Ranges.empty())
412    return 0;
413
414  SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
415  if (Ranges.size() > 1) {
416    // .debug_range section has not been laid out yet. Emit offset in
417    // .debug_range as a uint, size 4, for now. emitDIE will handle
418    // DW_AT_ranges appropriately.
419    TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
420                   DebugRangeSymbols.size()
421                   * Asm->getDataLayout().getPointerSize());
422    for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
423         RE = Ranges.end(); RI != RE; ++RI) {
424      DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
425      DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
426    }
427    DebugRangeSymbols.push_back(NULL);
428    DebugRangeSymbols.push_back(NULL);
429    return ScopeDIE;
430  }
431
432  const MCSymbol *Start = getLabelBeforeInsn(RI->first);
433  const MCSymbol *End = getLabelAfterInsn(RI->second);
434
435  if (End == 0) return 0;
436
437  assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
438  assert(End->isDefined() && "Invalid end label for an inlined scope!");
439
440  TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
441  TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
442
443  return ScopeDIE;
444}
445
446// This scope represents inlined body of a function. Construct DIE to
447// represent this concrete inlined copy of the function.
448DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
449                                          LexicalScope *Scope) {
450  const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
451  assert(Ranges.empty() == false &&
452         "LexicalScope does not have instruction markers!");
453
454  if (!Scope->getScopeNode())
455    return NULL;
456  DIScope DS(Scope->getScopeNode());
457  DISubprogram InlinedSP = getDISubprogram(DS);
458  DIE *OriginDIE = TheCU->getDIE(InlinedSP);
459  if (!OriginDIE) {
460    DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
461    return NULL;
462  }
463
464  SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
465  const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
466  const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
467
468  if (StartLabel == 0 || EndLabel == 0) {
469    llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
470  }
471  assert(StartLabel->isDefined() &&
472         "Invalid starting label for an inlined scope!");
473  assert(EndLabel->isDefined() &&
474         "Invalid end label for an inlined scope!");
475
476  DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
477  TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
478                     dwarf::DW_FORM_ref4, OriginDIE);
479
480  if (Ranges.size() > 1) {
481    // .debug_range section has not been laid out yet. Emit offset in
482    // .debug_range as a uint, size 4, for now. emitDIE will handle
483    // DW_AT_ranges appropriately.
484    TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
485                   DebugRangeSymbols.size()
486                   * Asm->getDataLayout().getPointerSize());
487    for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
488         RE = Ranges.end(); RI != RE; ++RI) {
489      DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
490      DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
491    }
492    DebugRangeSymbols.push_back(NULL);
493    DebugRangeSymbols.push_back(NULL);
494  } else {
495    TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
496                    StartLabel);
497    TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
498                    EndLabel);
499  }
500
501  InlinedSubprogramDIEs.insert(OriginDIE);
502
503  // Track the start label for this inlined function.
504  //.debug_inlined section specification does not clearly state how
505  // to emit inlined scope that is split into multiple instruction ranges.
506  // For now, use first instruction range and emit low_pc/high_pc pair and
507  // corresponding .debug_inlined section entry for this pair.
508  DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
509    I = InlineInfo.find(InlinedSP);
510
511  if (I == InlineInfo.end()) {
512    InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
513    InlinedSPNodes.push_back(InlinedSP);
514  } else
515    I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
516
517  DILocation DL(Scope->getInlinedAt());
518  TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
519                 getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
520  TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
521
522  // Add name to the name table, we do this here because we're guaranteed
523  // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
524  addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
525
526  return ScopeDIE;
527}
528
529// Construct a DIE for this scope.
530DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
531  if (!Scope || !Scope->getScopeNode())
532    return NULL;
533
534  SmallVector<DIE *, 8> Children;
535  DIE *ObjectPointer = NULL;
536
537  // Collect arguments for current function.
538  if (LScopes.isCurrentFunctionScope(Scope))
539    for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
540      if (DbgVariable *ArgDV = CurrentFnArguments[i])
541        if (DIE *Arg =
542            TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
543          Children.push_back(Arg);
544          if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
545        }
546
547  // Collect lexical scope children first.
548  const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
549  for (unsigned i = 0, N = Variables.size(); i < N; ++i)
550    if (DIE *Variable =
551        TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
552      Children.push_back(Variable);
553      if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
554    }
555  const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
556  for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
557    if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
558      Children.push_back(Nested);
559  DIScope DS(Scope->getScopeNode());
560  DIE *ScopeDIE = NULL;
561  if (Scope->getInlinedAt())
562    ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
563  else if (DS.isSubprogram()) {
564    ProcessedSPNodes.insert(DS);
565    if (Scope->isAbstractScope()) {
566      ScopeDIE = TheCU->getDIE(DS);
567      // Note down abstract DIE.
568      if (ScopeDIE)
569        AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
570    }
571    else
572      ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
573  }
574  else {
575    // There is no need to emit empty lexical block DIE.
576    if (Children.empty())
577      return NULL;
578    ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
579  }
580
581  if (!ScopeDIE) return NULL;
582
583  // Add children
584  for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
585         E = Children.end(); I != E; ++I)
586    ScopeDIE->addChild(*I);
587
588  if (DS.isSubprogram() && ObjectPointer != NULL)
589    TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
590                       dwarf::DW_FORM_ref4, ObjectPointer);
591
592  if (DS.isSubprogram())
593    TheCU->addPubTypes(DISubprogram(DS));
594
595  return ScopeDIE;
596}
597
598// Look up the source id with the given directory and source file names.
599// If none currently exists, create a new id and insert it in the
600// SourceIds map. This can update DirectoryNames and SourceFileNames maps
601// as well.
602unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
603                                         StringRef DirName) {
604  // If FE did not provide a file name, then assume stdin.
605  if (FileName.empty())
606    return getOrCreateSourceID("<stdin>", StringRef());
607
608  // TODO: this might not belong here. See if we can factor this better.
609  if (DirName == CompilationDir)
610    DirName = "";
611
612  unsigned SrcId = SourceIdMap.size()+1;
613
614  // We look up the file/dir pair by concatenating them with a zero byte.
615  SmallString<128> NamePair;
616  NamePair += DirName;
617  NamePair += '\0'; // Zero bytes are not allowed in paths.
618  NamePair += FileName;
619
620  StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
621  if (Ent.getValue() != SrcId)
622    return Ent.getValue();
623
624  // Print out a .file directive to specify files for .loc directives.
625  Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName);
626
627  return SrcId;
628}
629
630// Create new CompileUnit for the given metadata node with tag
631// DW_TAG_compile_unit.
632CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
633  DICompileUnit DIUnit(N);
634  StringRef FN = DIUnit.getFilename();
635  CompilationDir = DIUnit.getDirectory();
636  // Call this to emit a .file directive if it wasn't emitted for the source
637  // file this CU comes from yet.
638  getOrCreateSourceID(FN, CompilationDir);
639
640  DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
641  CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
642                                       DIUnit.getLanguage(), Die, Asm,
643                                       this, &InfoHolder);
644  NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
645  NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
646                 DIUnit.getLanguage());
647  NewCU->addString(Die, dwarf::DW_AT_name, FN);
648  // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
649  // into an entity.
650  NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
651  // DW_AT_stmt_list is a offset of line number information for this
652  // compile unit in debug_line section.
653  if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
654    NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
655                    Asm->GetTempSymbol("section_line"));
656  else
657    NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
658
659  if (!CompilationDir.empty())
660    NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
661  if (DIUnit.isOptimized())
662    NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
663
664  StringRef Flags = DIUnit.getFlags();
665  if (!Flags.empty())
666    NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
667
668  if (unsigned RVer = DIUnit.getRunTimeVersion())
669    NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
670            dwarf::DW_FORM_data1, RVer);
671
672  if (!FirstCU)
673    FirstCU = NewCU;
674  if (useSplitDwarf() && !SkeletonCU)
675    SkeletonCU = constructSkeletonCU(N);
676
677  InfoHolder.addUnit(NewCU);
678
679  CUMap.insert(std::make_pair(N, NewCU));
680  return NewCU;
681}
682
683// Construct subprogram DIE.
684void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
685                                        const MDNode *N) {
686  CompileUnit *&CURef = SPMap[N];
687  if (CURef)
688    return;
689  CURef = TheCU;
690
691  DISubprogram SP(N);
692  if (!SP.isDefinition())
693    // This is a method declaration which will be handled while constructing
694    // class type.
695    return;
696
697  DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
698
699  // Add to map.
700  TheCU->insertDIE(N, SubprogramDie);
701
702  // Add to context owner.
703  TheCU->addToContextOwner(SubprogramDie, SP.getContext());
704
705  return;
706}
707
708// Collect debug info from named mdnodes such as llvm.dbg.enum and llvm.dbg.ty.
709void DwarfDebug::collectInfoFromNamedMDNodes(const Module *M) {
710  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
711    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
712      const MDNode *N = NMD->getOperand(i);
713      if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
714        constructSubprogramDIE(CU, N);
715    }
716
717  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
718    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
719      const MDNode *N = NMD->getOperand(i);
720      if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
721        CU->createGlobalVariableDIE(N);
722    }
723
724  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
725    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
726      DIType Ty(NMD->getOperand(i));
727      if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
728        CU->getOrCreateTypeDIE(Ty);
729    }
730
731  if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
732    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
733      DIType Ty(NMD->getOperand(i));
734      if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
735        CU->getOrCreateTypeDIE(Ty);
736    }
737}
738
739// Collect debug info using DebugInfoFinder.
740// FIXME - Remove this when dragonegg switches to DIBuilder.
741bool DwarfDebug::collectLegacyDebugInfo(const Module *M) {
742  DebugInfoFinder DbgFinder;
743  DbgFinder.processModule(*M);
744
745  bool HasDebugInfo = false;
746  // Scan all the compile-units to see if there are any marked as the main
747  // unit. If not, we do not generate debug info.
748  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
749         E = DbgFinder.compile_unit_end(); I != E; ++I) {
750    if (DICompileUnit(*I).isMain()) {
751      HasDebugInfo = true;
752      break;
753    }
754  }
755  if (!HasDebugInfo) return false;
756
757  // Create all the compile unit DIEs.
758  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
759         E = DbgFinder.compile_unit_end(); I != E; ++I)
760    constructCompileUnit(*I);
761
762  // Create DIEs for each global variable.
763  for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
764         E = DbgFinder.global_variable_end(); I != E; ++I) {
765    const MDNode *N = *I;
766    if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
767      CU->createGlobalVariableDIE(N);
768  }
769
770  // Create DIEs for each subprogram.
771  for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
772         E = DbgFinder.subprogram_end(); I != E; ++I) {
773    const MDNode *N = *I;
774    if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
775      constructSubprogramDIE(CU, N);
776  }
777
778  return HasDebugInfo;
779}
780
781// Emit all Dwarf sections that should come prior to the content. Create
782// global DIEs and emit initial debug info sections. This is invoked by
783// the target AsmPrinter.
784void DwarfDebug::beginModule() {
785  if (DisableDebugInfoPrinting)
786    return;
787
788  const Module *M = MMI->getModule();
789
790  // If module has named metadata anchors then use them, otherwise scan the
791  // module using debug info finder to collect debug info.
792  NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
793  if (CU_Nodes) {
794    for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
795      DICompileUnit CUNode(CU_Nodes->getOperand(i));
796      CompileUnit *CU = constructCompileUnit(CUNode);
797      DIArray GVs = CUNode.getGlobalVariables();
798      for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
799        CU->createGlobalVariableDIE(GVs.getElement(i));
800      DIArray SPs = CUNode.getSubprograms();
801      for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
802        constructSubprogramDIE(CU, SPs.getElement(i));
803      DIArray EnumTypes = CUNode.getEnumTypes();
804      for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
805        CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
806      DIArray RetainedTypes = CUNode.getRetainedTypes();
807      for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
808        CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
809    }
810  } else if (!collectLegacyDebugInfo(M))
811    return;
812
813  collectInfoFromNamedMDNodes(M);
814
815  // Tell MMI that we have debug info.
816  MMI->setDebugInfoAvailability(true);
817
818  // Prime section data.
819  SectionMap.insert(Asm->getObjFileLowering().getTextSection());
820}
821
822// Attach DW_AT_inline attribute with inlined subprogram DIEs.
823void DwarfDebug::computeInlinedDIEs() {
824  // Attach DW_AT_inline attribute with inlined subprogram DIEs.
825  for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
826         AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
827    DIE *ISP = *AI;
828    FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
829  }
830  for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
831         AE = AbstractSPDies.end(); AI != AE; ++AI) {
832    DIE *ISP = AI->second;
833    if (InlinedSubprogramDIEs.count(ISP))
834      continue;
835    FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
836  }
837}
838
839// Collect info for variables that were optimized out.
840void DwarfDebug::collectDeadVariables() {
841  const Module *M = MMI->getModule();
842  DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
843
844  if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
845    for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
846      DICompileUnit TheCU(CU_Nodes->getOperand(i));
847      DIArray Subprograms = TheCU.getSubprograms();
848      for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
849        DISubprogram SP(Subprograms.getElement(i));
850        if (ProcessedSPNodes.count(SP) != 0) continue;
851        if (!SP.Verify()) continue;
852        if (!SP.isDefinition()) continue;
853        DIArray Variables = SP.getVariables();
854        if (Variables.getNumElements() == 0) continue;
855
856        LexicalScope *Scope =
857          new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
858        DeadFnScopeMap[SP] = Scope;
859
860        // Construct subprogram DIE and add variables DIEs.
861        CompileUnit *SPCU = CUMap.lookup(TheCU);
862        assert(SPCU && "Unable to find Compile Unit!");
863        constructSubprogramDIE(SPCU, SP);
864        DIE *ScopeDIE = SPCU->getDIE(SP);
865        for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
866          DIVariable DV(Variables.getElement(vi));
867          if (!DV.Verify()) continue;
868          DbgVariable *NewVar = new DbgVariable(DV, NULL);
869          if (DIE *VariableDIE =
870              SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
871            ScopeDIE->addChild(VariableDIE);
872        }
873      }
874    }
875  }
876  DeleteContainerSeconds(DeadFnScopeMap);
877}
878
879void DwarfDebug::finalizeModuleInfo() {
880  // Collect info for variables that were optimized out.
881  collectDeadVariables();
882
883  // Attach DW_AT_inline attribute with inlined subprogram DIEs.
884  computeInlinedDIEs();
885
886  // Emit DW_AT_containing_type attribute to connect types with their
887  // vtable holding type.
888  for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
889         CUE = CUMap.end(); CUI != CUE; ++CUI) {
890    CompileUnit *TheCU = CUI->second;
891    TheCU->constructContainingTypeDIEs();
892  }
893
894   // Compute DIE offsets and sizes.
895  InfoHolder.computeSizeAndOffsets();
896  if (useSplitDwarf())
897    SkeletonHolder.computeSizeAndOffsets();
898}
899
900void DwarfDebug::endSections() {
901  // Standard sections final addresses.
902  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
903  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
904  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
905  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
906
907  // End text sections.
908  for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
909    Asm->OutStreamer.SwitchSection(SectionMap[I]);
910    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
911  }
912}
913
914// Emit all Dwarf sections that should come after the content.
915void DwarfDebug::endModule() {
916
917  if (!FirstCU) return;
918
919  // End any existing sections.
920  // TODO: Does this need to happen?
921  endSections();
922
923  // Finalize the debug info for the module.
924  finalizeModuleInfo();
925
926  // Emit initial sections.
927  emitSectionLabels();
928
929  if (!useSplitDwarf()) {
930    // Emit all the DIEs into a debug info section.
931    emitDebugInfo();
932
933    // Corresponding abbreviations into a abbrev section.
934    emitAbbreviations();
935
936    // Emit info into a debug loc section.
937    emitDebugLoc();
938
939    // Emit info into a debug aranges section.
940    emitDebugARanges();
941
942    // Emit info into a debug ranges section.
943    emitDebugRanges();
944
945    // Emit info into a debug macinfo section.
946    emitDebugMacInfo();
947
948    // Emit inline info.
949    // TODO: When we don't need the option anymore we
950    // can remove all of the code that this section
951    // depends upon.
952    if (useDarwinGDBCompat())
953      emitDebugInlineInfo();
954  } else {
955    // TODO: Fill this in for separated debug sections and separate
956    // out information into new sections.
957
958    // Emit the debug info section and compile units.
959    emitDebugInfo();
960    emitDebugInfoDWO();
961
962    // Corresponding abbreviations into a abbrev section.
963    emitAbbreviations();
964    emitDebugAbbrevDWO();
965
966    // Emit info into a debug loc section.
967    emitDebugLoc();
968
969    // Emit info into a debug aranges section.
970    emitDebugARanges();
971
972    // Emit info into a debug ranges section.
973    emitDebugRanges();
974
975    // Emit info into a debug macinfo section.
976    emitDebugMacInfo();
977
978    // Emit inline info.
979    // TODO: When we don't need the option anymore we
980    // can remove all of the code that this section
981    // depends upon.
982    if (useDarwinGDBCompat())
983      emitDebugInlineInfo();
984  }
985
986  // Emit info into the dwarf accelerator table sections.
987  if (useDwarfAccelTables()) {
988    emitAccelNames();
989    emitAccelObjC();
990    emitAccelNamespaces();
991    emitAccelTypes();
992  }
993
994  // Emit info into a debug pubtypes section.
995  // TODO: When we don't need the option anymore we can
996  // remove all of the code that adds to the table.
997  if (useDarwinGDBCompat())
998    emitDebugPubTypes();
999
1000  // Finally emit string information into a string table.
1001  emitDebugStr();
1002  if (useSplitDwarf())
1003    emitDebugStrDWO();
1004
1005  // clean up.
1006  SPMap.clear();
1007  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1008         E = CUMap.end(); I != E; ++I)
1009    delete I->second;
1010
1011  delete SkeletonCU;
1012
1013  // Reset these for the next Module if we have one.
1014  FirstCU = NULL;
1015  SkeletonCU = NULL;
1016}
1017
1018// Find abstract variable, if any, associated with Var.
1019DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1020                                              DebugLoc ScopeLoc) {
1021  LLVMContext &Ctx = DV->getContext();
1022  // More then one inlined variable corresponds to one abstract variable.
1023  DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1024  DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1025  if (AbsDbgVariable)
1026    return AbsDbgVariable;
1027
1028  LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1029  if (!Scope)
1030    return NULL;
1031
1032  AbsDbgVariable = new DbgVariable(Var, NULL);
1033  addScopeVariable(Scope, AbsDbgVariable);
1034  AbstractVariables[Var] = AbsDbgVariable;
1035  return AbsDbgVariable;
1036}
1037
1038// If Var is a current function argument then add it to CurrentFnArguments list.
1039bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1040                                      DbgVariable *Var, LexicalScope *Scope) {
1041  if (!LScopes.isCurrentFunctionScope(Scope))
1042    return false;
1043  DIVariable DV = Var->getVariable();
1044  if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1045    return false;
1046  unsigned ArgNo = DV.getArgNumber();
1047  if (ArgNo == 0)
1048    return false;
1049
1050  size_t Size = CurrentFnArguments.size();
1051  if (Size == 0)
1052    CurrentFnArguments.resize(MF->getFunction()->arg_size());
1053  // llvm::Function argument size is not good indicator of how many
1054  // arguments does the function have at source level.
1055  if (ArgNo > Size)
1056    CurrentFnArguments.resize(ArgNo * 2);
1057  CurrentFnArguments[ArgNo - 1] = Var;
1058  return true;
1059}
1060
1061// Collect variable information from side table maintained by MMI.
1062void
1063DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1064                                   SmallPtrSet<const MDNode *, 16> &Processed) {
1065  MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1066  for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1067         VE = VMap.end(); VI != VE; ++VI) {
1068    const MDNode *Var = VI->first;
1069    if (!Var) continue;
1070    Processed.insert(Var);
1071    DIVariable DV(Var);
1072    const std::pair<unsigned, DebugLoc> &VP = VI->second;
1073
1074    LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1075
1076    // If variable scope is not found then skip this variable.
1077    if (Scope == 0)
1078      continue;
1079
1080    DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1081    DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1082    RegVar->setFrameIndex(VP.first);
1083    if (!addCurrentFnArgument(MF, RegVar, Scope))
1084      addScopeVariable(Scope, RegVar);
1085    if (AbsDbgVariable)
1086      AbsDbgVariable->setFrameIndex(VP.first);
1087  }
1088}
1089
1090// Return true if debug value, encoded by DBG_VALUE instruction, is in a
1091// defined reg.
1092static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1093  assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1094  return MI->getNumOperands() == 3 &&
1095         MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1096         MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1097}
1098
1099// Get .debug_loc entry for the instruction range starting at MI.
1100static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1101                                         const MCSymbol *FLabel,
1102                                         const MCSymbol *SLabel,
1103                                         const MachineInstr *MI) {
1104  const MDNode *Var =  MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1105
1106  if (MI->getNumOperands() != 3) {
1107    MachineLocation MLoc = Asm->getDebugValueLocation(MI);
1108    return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1109  }
1110  if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1111    MachineLocation MLoc;
1112    MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1113    return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1114  }
1115  if (MI->getOperand(0).isImm())
1116    return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1117  if (MI->getOperand(0).isFPImm())
1118    return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1119  if (MI->getOperand(0).isCImm())
1120    return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1121
1122  llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1123}
1124
1125// Find variables for each lexical scope.
1126void
1127DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1128                                SmallPtrSet<const MDNode *, 16> &Processed) {
1129
1130  // collection info from MMI table.
1131  collectVariableInfoFromMMITable(MF, Processed);
1132
1133  for (SmallVectorImpl<const MDNode*>::const_iterator
1134         UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1135         ++UVI) {
1136    const MDNode *Var = *UVI;
1137    if (Processed.count(Var))
1138      continue;
1139
1140    // History contains relevant DBG_VALUE instructions for Var and instructions
1141    // clobbering it.
1142    SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1143    if (History.empty())
1144      continue;
1145    const MachineInstr *MInsn = History.front();
1146
1147    DIVariable DV(Var);
1148    LexicalScope *Scope = NULL;
1149    if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1150        DISubprogram(DV.getContext()).describes(MF->getFunction()))
1151      Scope = LScopes.getCurrentFunctionScope();
1152    else {
1153      if (DV.getVersion() <= LLVMDebugVersion9)
1154        Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1155      else {
1156        if (MDNode *IA = DV.getInlinedAt())
1157          Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1158        else
1159          Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1160      }
1161    }
1162    // If variable scope is not found then skip this variable.
1163    if (!Scope)
1164      continue;
1165
1166    Processed.insert(DV);
1167    assert(MInsn->isDebugValue() && "History must begin with debug value");
1168    DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1169    DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1170    if (!addCurrentFnArgument(MF, RegVar, Scope))
1171      addScopeVariable(Scope, RegVar);
1172    if (AbsVar)
1173      AbsVar->setMInsn(MInsn);
1174
1175    // Simplify ranges that are fully coalesced.
1176    if (History.size() <= 1 || (History.size() == 2 &&
1177                                MInsn->isIdenticalTo(History.back()))) {
1178      RegVar->setMInsn(MInsn);
1179      continue;
1180    }
1181
1182    // handle multiple DBG_VALUE instructions describing one variable.
1183    RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1184
1185    for (SmallVectorImpl<const MachineInstr*>::const_iterator
1186           HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1187      const MachineInstr *Begin = *HI;
1188      assert(Begin->isDebugValue() && "Invalid History entry");
1189
1190      // Check if DBG_VALUE is truncating a range.
1191      if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1192          && !Begin->getOperand(0).getReg())
1193        continue;
1194
1195      // Compute the range for a register location.
1196      const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1197      const MCSymbol *SLabel = 0;
1198
1199      if (HI + 1 == HE)
1200        // If Begin is the last instruction in History then its value is valid
1201        // until the end of the function.
1202        SLabel = FunctionEndSym;
1203      else {
1204        const MachineInstr *End = HI[1];
1205        DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1206              << "\t" << *Begin << "\t" << *End << "\n");
1207        if (End->isDebugValue())
1208          SLabel = getLabelBeforeInsn(End);
1209        else {
1210          // End is a normal instruction clobbering the range.
1211          SLabel = getLabelAfterInsn(End);
1212          assert(SLabel && "Forgot label after clobber instruction");
1213          ++HI;
1214        }
1215      }
1216
1217      // The value is valid until the next DBG_VALUE or clobber.
1218      DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1219                                                    Begin));
1220    }
1221    DotDebugLocEntries.push_back(DotDebugLocEntry());
1222  }
1223
1224  // Collect info for variables that were optimized out.
1225  LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1226  DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1227  for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1228    DIVariable DV(Variables.getElement(i));
1229    if (!DV || !DV.Verify() || !Processed.insert(DV))
1230      continue;
1231    if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1232      addScopeVariable(Scope, new DbgVariable(DV, NULL));
1233  }
1234}
1235
1236// Return Label preceding the instruction.
1237const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1238  MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1239  assert(Label && "Didn't insert label before instruction");
1240  return Label;
1241}
1242
1243// Return Label immediately following the instruction.
1244const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1245  return LabelsAfterInsn.lookup(MI);
1246}
1247
1248// Process beginning of an instruction.
1249void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1250  // Check if source location changes, but ignore DBG_VALUE locations.
1251  if (!MI->isDebugValue()) {
1252    DebugLoc DL = MI->getDebugLoc();
1253    if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1254      unsigned Flags = 0;
1255      PrevInstLoc = DL;
1256      if (DL == PrologEndLoc) {
1257        Flags |= DWARF2_FLAG_PROLOGUE_END;
1258        PrologEndLoc = DebugLoc();
1259      }
1260      if (PrologEndLoc.isUnknown())
1261        Flags |= DWARF2_FLAG_IS_STMT;
1262
1263      if (!DL.isUnknown()) {
1264        const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1265        recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1266      } else
1267        recordSourceLine(0, 0, 0, 0);
1268    }
1269  }
1270
1271  // Insert labels where requested.
1272  DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1273    LabelsBeforeInsn.find(MI);
1274
1275  // No label needed.
1276  if (I == LabelsBeforeInsn.end())
1277    return;
1278
1279  // Label already assigned.
1280  if (I->second)
1281    return;
1282
1283  if (!PrevLabel) {
1284    PrevLabel = MMI->getContext().CreateTempSymbol();
1285    Asm->OutStreamer.EmitLabel(PrevLabel);
1286  }
1287  I->second = PrevLabel;
1288}
1289
1290// Process end of an instruction.
1291void DwarfDebug::endInstruction(const MachineInstr *MI) {
1292  // Don't create a new label after DBG_VALUE instructions.
1293  // They don't generate code.
1294  if (!MI->isDebugValue())
1295    PrevLabel = 0;
1296
1297  DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1298    LabelsAfterInsn.find(MI);
1299
1300  // No label needed.
1301  if (I == LabelsAfterInsn.end())
1302    return;
1303
1304  // Label already assigned.
1305  if (I->second)
1306    return;
1307
1308  // We need a label after this instruction.
1309  if (!PrevLabel) {
1310    PrevLabel = MMI->getContext().CreateTempSymbol();
1311    Asm->OutStreamer.EmitLabel(PrevLabel);
1312  }
1313  I->second = PrevLabel;
1314}
1315
1316// Each LexicalScope has first instruction and last instruction to mark
1317// beginning and end of a scope respectively. Create an inverse map that list
1318// scopes starts (and ends) with an instruction. One instruction may start (or
1319// end) multiple scopes. Ignore scopes that are not reachable.
1320void DwarfDebug::identifyScopeMarkers() {
1321  SmallVector<LexicalScope *, 4> WorkList;
1322  WorkList.push_back(LScopes.getCurrentFunctionScope());
1323  while (!WorkList.empty()) {
1324    LexicalScope *S = WorkList.pop_back_val();
1325
1326    const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1327    if (!Children.empty())
1328      for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1329             SE = Children.end(); SI != SE; ++SI)
1330        WorkList.push_back(*SI);
1331
1332    if (S->isAbstractScope())
1333      continue;
1334
1335    const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1336    if (Ranges.empty())
1337      continue;
1338    for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1339           RE = Ranges.end(); RI != RE; ++RI) {
1340      assert(RI->first && "InsnRange does not have first instruction!");
1341      assert(RI->second && "InsnRange does not have second instruction!");
1342      requestLabelBeforeInsn(RI->first);
1343      requestLabelAfterInsn(RI->second);
1344    }
1345  }
1346}
1347
1348// Get MDNode for DebugLoc's scope.
1349static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1350  if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1351    return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1352  return DL.getScope(Ctx);
1353}
1354
1355// Walk up the scope chain of given debug loc and find line number info
1356// for the function.
1357static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1358  const MDNode *Scope = getScopeNode(DL, Ctx);
1359  DISubprogram SP = getDISubprogram(Scope);
1360  if (SP.Verify()) {
1361    // Check for number of operands since the compatibility is
1362    // cheap here.
1363    if (SP->getNumOperands() > 19)
1364      return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1365    else
1366      return DebugLoc::get(SP.getLineNumber(), 0, SP);
1367  }
1368
1369  return DebugLoc();
1370}
1371
1372// Gather pre-function debug information.  Assumes being called immediately
1373// after the function entry point has been emitted.
1374void DwarfDebug::beginFunction(const MachineFunction *MF) {
1375  if (!MMI->hasDebugInfo()) return;
1376  LScopes.initialize(*MF);
1377  if (LScopes.empty()) return;
1378  identifyScopeMarkers();
1379
1380  FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1381                                        Asm->getFunctionNumber());
1382  // Assumes in correct section after the entry point.
1383  Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1384
1385  assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1386
1387  const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1388  // LiveUserVar - Map physreg numbers to the MDNode they contain.
1389  std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1390
1391  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1392       I != E; ++I) {
1393    bool AtBlockEntry = true;
1394    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1395         II != IE; ++II) {
1396      const MachineInstr *MI = II;
1397
1398      if (MI->isDebugValue()) {
1399        assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1400
1401        // Keep track of user variables.
1402        const MDNode *Var =
1403          MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1404
1405        // Variable is in a register, we need to check for clobbers.
1406        if (isDbgValueInDefinedReg(MI))
1407          LiveUserVar[MI->getOperand(0).getReg()] = Var;
1408
1409        // Check the history of this variable.
1410        SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1411        if (History.empty()) {
1412          UserVariables.push_back(Var);
1413          // The first mention of a function argument gets the FunctionBeginSym
1414          // label, so arguments are visible when breaking at function entry.
1415          DIVariable DV(Var);
1416          if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1417              DISubprogram(getDISubprogram(DV.getContext()))
1418                .describes(MF->getFunction()))
1419            LabelsBeforeInsn[MI] = FunctionBeginSym;
1420        } else {
1421          // We have seen this variable before. Try to coalesce DBG_VALUEs.
1422          const MachineInstr *Prev = History.back();
1423          if (Prev->isDebugValue()) {
1424            // Coalesce identical entries at the end of History.
1425            if (History.size() >= 2 &&
1426                Prev->isIdenticalTo(History[History.size() - 2])) {
1427              DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1428                    << "\t" << *Prev
1429                    << "\t" << *History[History.size() - 2] << "\n");
1430              History.pop_back();
1431            }
1432
1433            // Terminate old register assignments that don't reach MI;
1434            MachineFunction::const_iterator PrevMBB = Prev->getParent();
1435            if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1436                isDbgValueInDefinedReg(Prev)) {
1437              // Previous register assignment needs to terminate at the end of
1438              // its basic block.
1439              MachineBasicBlock::const_iterator LastMI =
1440                PrevMBB->getLastNonDebugInstr();
1441              if (LastMI == PrevMBB->end()) {
1442                // Drop DBG_VALUE for empty range.
1443                DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1444                      << "\t" << *Prev << "\n");
1445                History.pop_back();
1446              }
1447              else {
1448                // Terminate after LastMI.
1449                History.push_back(LastMI);
1450              }
1451            }
1452          }
1453        }
1454        History.push_back(MI);
1455      } else {
1456        // Not a DBG_VALUE instruction.
1457        if (!MI->isLabel())
1458          AtBlockEntry = false;
1459
1460        // First known non-DBG_VALUE and non-frame setup location marks
1461        // the beginning of the function body.
1462        if (!MI->getFlag(MachineInstr::FrameSetup) &&
1463            (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1464          PrologEndLoc = MI->getDebugLoc();
1465
1466        // Check if the instruction clobbers any registers with debug vars.
1467        for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1468               MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1469          if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1470            continue;
1471          for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1472               AI.isValid(); ++AI) {
1473            unsigned Reg = *AI;
1474            const MDNode *Var = LiveUserVar[Reg];
1475            if (!Var)
1476              continue;
1477            // Reg is now clobbered.
1478            LiveUserVar[Reg] = 0;
1479
1480            // Was MD last defined by a DBG_VALUE referring to Reg?
1481            DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1482            if (HistI == DbgValues.end())
1483              continue;
1484            SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1485            if (History.empty())
1486              continue;
1487            const MachineInstr *Prev = History.back();
1488            // Sanity-check: Register assignments are terminated at the end of
1489            // their block.
1490            if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1491              continue;
1492            // Is the variable still in Reg?
1493            if (!isDbgValueInDefinedReg(Prev) ||
1494                Prev->getOperand(0).getReg() != Reg)
1495              continue;
1496            // Var is clobbered. Make sure the next instruction gets a label.
1497            History.push_back(MI);
1498          }
1499        }
1500      }
1501    }
1502  }
1503
1504  for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1505       I != E; ++I) {
1506    SmallVectorImpl<const MachineInstr*> &History = I->second;
1507    if (History.empty())
1508      continue;
1509
1510    // Make sure the final register assignments are terminated.
1511    const MachineInstr *Prev = History.back();
1512    if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1513      const MachineBasicBlock *PrevMBB = Prev->getParent();
1514      MachineBasicBlock::const_iterator LastMI =
1515        PrevMBB->getLastNonDebugInstr();
1516      if (LastMI == PrevMBB->end())
1517        // Drop DBG_VALUE for empty range.
1518        History.pop_back();
1519      else {
1520        // Terminate after LastMI.
1521        History.push_back(LastMI);
1522      }
1523    }
1524    // Request labels for the full history.
1525    for (unsigned i = 0, e = History.size(); i != e; ++i) {
1526      const MachineInstr *MI = History[i];
1527      if (MI->isDebugValue())
1528        requestLabelBeforeInsn(MI);
1529      else
1530        requestLabelAfterInsn(MI);
1531    }
1532  }
1533
1534  PrevInstLoc = DebugLoc();
1535  PrevLabel = FunctionBeginSym;
1536
1537  // Record beginning of function.
1538  if (!PrologEndLoc.isUnknown()) {
1539    DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1540                                       MF->getFunction()->getContext());
1541    recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1542                     FnStartDL.getScope(MF->getFunction()->getContext()),
1543    // We'd like to list the prologue as "not statements" but GDB behaves
1544    // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1545                     DWARF2_FLAG_IS_STMT);
1546  }
1547}
1548
1549void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1550//  SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1551  ScopeVariables[LS].push_back(Var);
1552//  Vars.push_back(Var);
1553}
1554
1555// Gather and emit post-function debug information.
1556void DwarfDebug::endFunction(const MachineFunction *MF) {
1557  if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1558
1559  // Define end label for subprogram.
1560  FunctionEndSym = Asm->GetTempSymbol("func_end",
1561                                      Asm->getFunctionNumber());
1562  // Assumes in correct section after the entry point.
1563  Asm->OutStreamer.EmitLabel(FunctionEndSym);
1564
1565  SmallPtrSet<const MDNode *, 16> ProcessedVars;
1566  collectVariableInfo(MF, ProcessedVars);
1567
1568  LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1569  CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1570  assert(TheCU && "Unable to find compile unit!");
1571
1572  // Construct abstract scopes.
1573  ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1574  for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1575    LexicalScope *AScope = AList[i];
1576    DISubprogram SP(AScope->getScopeNode());
1577    if (SP.Verify()) {
1578      // Collect info for variables that were optimized out.
1579      DIArray Variables = SP.getVariables();
1580      for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1581        DIVariable DV(Variables.getElement(i));
1582        if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1583          continue;
1584        // Check that DbgVariable for DV wasn't created earlier, when
1585        // findAbstractVariable() was called for inlined instance of DV.
1586        LLVMContext &Ctx = DV->getContext();
1587        DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1588        if (AbstractVariables.lookup(CleanDV))
1589          continue;
1590        if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1591          addScopeVariable(Scope, new DbgVariable(DV, NULL));
1592      }
1593    }
1594    if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1595      constructScopeDIE(TheCU, AScope);
1596  }
1597
1598  DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1599
1600  if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1601    TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1602
1603  DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1604                                               MMI->getFrameMoves()));
1605
1606  // Clear debug info
1607  for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1608         I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1609    DeleteContainerPointers(I->second);
1610  ScopeVariables.clear();
1611  DeleteContainerPointers(CurrentFnArguments);
1612  UserVariables.clear();
1613  DbgValues.clear();
1614  AbstractVariables.clear();
1615  LabelsBeforeInsn.clear();
1616  LabelsAfterInsn.clear();
1617  PrevLabel = NULL;
1618}
1619
1620// Register a source line with debug info. Returns the  unique label that was
1621// emitted and which provides correspondence to the source line list.
1622void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1623                                  unsigned Flags) {
1624  StringRef Fn;
1625  StringRef Dir;
1626  unsigned Src = 1;
1627  if (S) {
1628    DIDescriptor Scope(S);
1629
1630    if (Scope.isCompileUnit()) {
1631      DICompileUnit CU(S);
1632      Fn = CU.getFilename();
1633      Dir = CU.getDirectory();
1634    } else if (Scope.isFile()) {
1635      DIFile F(S);
1636      Fn = F.getFilename();
1637      Dir = F.getDirectory();
1638    } else if (Scope.isSubprogram()) {
1639      DISubprogram SP(S);
1640      Fn = SP.getFilename();
1641      Dir = SP.getDirectory();
1642    } else if (Scope.isLexicalBlockFile()) {
1643      DILexicalBlockFile DBF(S);
1644      Fn = DBF.getFilename();
1645      Dir = DBF.getDirectory();
1646    } else if (Scope.isLexicalBlock()) {
1647      DILexicalBlock DB(S);
1648      Fn = DB.getFilename();
1649      Dir = DB.getDirectory();
1650    } else
1651      llvm_unreachable("Unexpected scope info");
1652
1653    Src = getOrCreateSourceID(Fn, Dir);
1654  }
1655  Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1656}
1657
1658//===----------------------------------------------------------------------===//
1659// Emit Methods
1660//===----------------------------------------------------------------------===//
1661
1662// Compute the size and offset of a DIE.
1663unsigned
1664DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1665  // Get the children.
1666  const std::vector<DIE *> &Children = Die->getChildren();
1667
1668  // Record the abbreviation.
1669  assignAbbrevNumber(Die->getAbbrev());
1670
1671  // Get the abbreviation for this DIE.
1672  unsigned AbbrevNumber = Die->getAbbrevNumber();
1673  const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1674
1675  // Set DIE offset
1676  Die->setOffset(Offset);
1677
1678  // Start the size with the size of abbreviation code.
1679  Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1680
1681  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1682  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1683
1684  // Size the DIE attribute values.
1685  for (unsigned i = 0, N = Values.size(); i < N; ++i)
1686    // Size attribute value.
1687    Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1688
1689  // Size the DIE children if any.
1690  if (!Children.empty()) {
1691    assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1692           "Children flag not set");
1693
1694    for (unsigned j = 0, M = Children.size(); j < M; ++j)
1695      Offset = computeSizeAndOffset(Children[j], Offset);
1696
1697    // End of children marker.
1698    Offset += sizeof(int8_t);
1699  }
1700
1701  Die->setSize(Offset - Die->getOffset());
1702  return Offset;
1703}
1704
1705// Compute the size and offset of all the DIEs.
1706void DwarfUnits::computeSizeAndOffsets() {
1707  for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1708         E = CUs.end(); I != E; ++I) {
1709    unsigned Offset =
1710      sizeof(int32_t) + // Length of Compilation Unit Info
1711      sizeof(int16_t) + // DWARF version number
1712      sizeof(int32_t) + // Offset Into Abbrev. Section
1713      sizeof(int8_t);   // Pointer Size (in bytes)
1714
1715    computeSizeAndOffset((*I)->getCUDie(), Offset);
1716  }
1717}
1718
1719// Emit initial Dwarf sections with a label at the start of each one.
1720void DwarfDebug::emitSectionLabels() {
1721  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1722
1723  // Dwarf sections base addresses.
1724  DwarfInfoSectionSym =
1725    emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1726  DwarfAbbrevSectionSym =
1727    emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1728  if (useSplitDwarf())
1729    DwarfAbbrevDWOSectionSym =
1730      emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1731                     "section_abbrev_dwo");
1732  emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1733
1734  if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1735    emitSectionSym(Asm, MacroInfo);
1736
1737  emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1738  emitSectionSym(Asm, TLOF.getDwarfLocSection());
1739  emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1740  DwarfStrSectionSym =
1741    emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1742  if (useSplitDwarf())
1743    DwarfStrDWOSectionSym =
1744      emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1745  DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1746                                             "debug_range");
1747
1748  DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1749                                           "section_debug_loc");
1750
1751  TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1752  emitSectionSym(Asm, TLOF.getDataSection());
1753}
1754
1755// Recursively emits a debug information entry.
1756void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1757  // Get the abbreviation for this DIE.
1758  unsigned AbbrevNumber = Die->getAbbrevNumber();
1759  const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1760
1761  // Emit the code (index) for the abbreviation.
1762  if (Asm->isVerbose())
1763    Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1764                                Twine::utohexstr(Die->getOffset()) + ":0x" +
1765                                Twine::utohexstr(Die->getSize()) + " " +
1766                                dwarf::TagString(Abbrev->getTag()));
1767  Asm->EmitULEB128(AbbrevNumber);
1768
1769  const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1770  const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1771
1772  // Emit the DIE attribute values.
1773  for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1774    unsigned Attr = AbbrevData[i].getAttribute();
1775    unsigned Form = AbbrevData[i].getForm();
1776    assert(Form && "Too many attributes for DIE (check abbreviation)");
1777
1778    if (Asm->isVerbose())
1779      Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1780
1781    switch (Attr) {
1782    case dwarf::DW_AT_abstract_origin: {
1783      DIEEntry *E = cast<DIEEntry>(Values[i]);
1784      DIE *Origin = E->getEntry();
1785      unsigned Addr = Origin->getOffset();
1786      Asm->EmitInt32(Addr);
1787      break;
1788    }
1789    case dwarf::DW_AT_ranges: {
1790      // DW_AT_range Value encodes offset in debug_range section.
1791      DIEInteger *V = cast<DIEInteger>(Values[i]);
1792
1793      if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1794        Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1795                                 V->getValue(),
1796                                 4);
1797      } else {
1798        Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1799                                       V->getValue(),
1800                                       DwarfDebugRangeSectionSym,
1801                                       4);
1802      }
1803      break;
1804    }
1805    case dwarf::DW_AT_location: {
1806      if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1807        if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1808          Asm->EmitLabelReference(L->getValue(), 4);
1809        else
1810          Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1811      } else {
1812        Values[i]->EmitValue(Asm, Form);
1813      }
1814      break;
1815    }
1816    case dwarf::DW_AT_accessibility: {
1817      if (Asm->isVerbose()) {
1818        DIEInteger *V = cast<DIEInteger>(Values[i]);
1819        Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1820      }
1821      Values[i]->EmitValue(Asm, Form);
1822      break;
1823    }
1824    default:
1825      // Emit an attribute using the defined form.
1826      Values[i]->EmitValue(Asm, Form);
1827      break;
1828    }
1829  }
1830
1831  // Emit the DIE children if any.
1832  if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1833    const std::vector<DIE *> &Children = Die->getChildren();
1834
1835    for (unsigned j = 0, M = Children.size(); j < M; ++j)
1836      emitDIE(Children[j], Abbrevs);
1837
1838    if (Asm->isVerbose())
1839      Asm->OutStreamer.AddComment("End Of Children Mark");
1840    Asm->EmitInt8(0);
1841  }
1842}
1843
1844// Emit the various dwarf units to the unit section USection with
1845// the abbreviations going into ASection.
1846void DwarfUnits::emitUnits(DwarfDebug *DD,
1847                           const MCSection *USection,
1848                           const MCSection *ASection,
1849                           const MCSymbol *ASectionSym) {
1850  Asm->OutStreamer.SwitchSection(USection);
1851  for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1852         E = CUs.end(); I != E; ++I) {
1853    CompileUnit *TheCU = *I;
1854    DIE *Die = TheCU->getCUDie();
1855
1856    // Emit the compile units header.
1857    Asm->OutStreamer
1858      .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
1859                                    TheCU->getUniqueID()));
1860
1861    // Emit size of content not including length itself
1862    unsigned ContentSize = Die->getSize() +
1863      sizeof(int16_t) + // DWARF version number
1864      sizeof(int32_t) + // Offset Into Abbrev. Section
1865      sizeof(int8_t);   // Pointer Size (in bytes)
1866
1867    Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1868    Asm->EmitInt32(ContentSize);
1869    Asm->OutStreamer.AddComment("DWARF version number");
1870    Asm->EmitInt16(dwarf::DWARF_VERSION);
1871    Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1872    Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1873                           ASectionSym);
1874    Asm->OutStreamer.AddComment("Address Size (in bytes)");
1875    Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1876
1877    DD->emitDIE(Die, Abbreviations);
1878    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
1879                                                  TheCU->getUniqueID()));
1880  }
1881}
1882
1883// Emit the debug info section.
1884void DwarfDebug::emitDebugInfo() {
1885  DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1886
1887  Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
1888                   Asm->getObjFileLowering().getDwarfAbbrevSection(),
1889                   DwarfAbbrevSectionSym);
1890}
1891
1892// Emit the abbreviation section.
1893void DwarfDebug::emitAbbreviations() {
1894  if (!useSplitDwarf())
1895    emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
1896                &Abbreviations);
1897  else
1898    emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1899}
1900
1901void DwarfDebug::emitAbbrevs(const MCSection *Section,
1902                             std::vector<DIEAbbrev *> *Abbrevs) {
1903  // Check to see if it is worth the effort.
1904  if (!Abbrevs->empty()) {
1905    // Start the debug abbrev section.
1906    Asm->OutStreamer.SwitchSection(Section);
1907
1908    MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
1909    Asm->OutStreamer.EmitLabel(Begin);
1910
1911    // For each abbrevation.
1912    for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
1913      // Get abbreviation data
1914      const DIEAbbrev *Abbrev = Abbrevs->at(i);
1915
1916      // Emit the abbrevations code (base 1 index.)
1917      Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1918
1919      // Emit the abbreviations data.
1920      Abbrev->Emit(Asm);
1921    }
1922
1923    // Mark end of abbreviations.
1924    Asm->EmitULEB128(0, "EOM(3)");
1925
1926    MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
1927    Asm->OutStreamer.EmitLabel(End);
1928  }
1929}
1930
1931// Emit the last address of the section and the end of the line matrix.
1932void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1933  // Define last address of section.
1934  Asm->OutStreamer.AddComment("Extended Op");
1935  Asm->EmitInt8(0);
1936
1937  Asm->OutStreamer.AddComment("Op size");
1938  Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1939  Asm->OutStreamer.AddComment("DW_LNE_set_address");
1940  Asm->EmitInt8(dwarf::DW_LNE_set_address);
1941
1942  Asm->OutStreamer.AddComment("Section end label");
1943
1944  Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1945                                   Asm->getDataLayout().getPointerSize());
1946
1947  // Mark end of matrix.
1948  Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1949  Asm->EmitInt8(0);
1950  Asm->EmitInt8(1);
1951  Asm->EmitInt8(1);
1952}
1953
1954// Emit visible names into a hashed accelerator table section.
1955void DwarfDebug::emitAccelNames() {
1956  DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1957                                           dwarf::DW_FORM_data4));
1958  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1959         E = CUMap.end(); I != E; ++I) {
1960    CompileUnit *TheCU = I->second;
1961    const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
1962    for (StringMap<std::vector<DIE*> >::const_iterator
1963           GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1964      const char *Name = GI->getKeyData();
1965      const std::vector<DIE *> &Entities = GI->second;
1966      for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1967             DE = Entities.end(); DI != DE; ++DI)
1968        AT.AddName(Name, (*DI));
1969    }
1970  }
1971
1972  AT.FinalizeTable(Asm, "Names");
1973  Asm->OutStreamer.SwitchSection(
1974    Asm->getObjFileLowering().getDwarfAccelNamesSection());
1975  MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1976  Asm->OutStreamer.EmitLabel(SectionBegin);
1977
1978  // Emit the full data.
1979  AT.Emit(Asm, SectionBegin, &InfoHolder);
1980}
1981
1982// Emit objective C classes and categories into a hashed accelerator table
1983// section.
1984void DwarfDebug::emitAccelObjC() {
1985  DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1986                                           dwarf::DW_FORM_data4));
1987  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1988         E = CUMap.end(); I != E; ++I) {
1989    CompileUnit *TheCU = I->second;
1990    const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
1991    for (StringMap<std::vector<DIE*> >::const_iterator
1992           GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1993      const char *Name = GI->getKeyData();
1994      const std::vector<DIE *> &Entities = GI->second;
1995      for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1996             DE = Entities.end(); DI != DE; ++DI)
1997        AT.AddName(Name, (*DI));
1998    }
1999  }
2000
2001  AT.FinalizeTable(Asm, "ObjC");
2002  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2003                                 .getDwarfAccelObjCSection());
2004  MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2005  Asm->OutStreamer.EmitLabel(SectionBegin);
2006
2007  // Emit the full data.
2008  AT.Emit(Asm, SectionBegin, &InfoHolder);
2009}
2010
2011// Emit namespace dies into a hashed accelerator table.
2012void DwarfDebug::emitAccelNamespaces() {
2013  DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2014                                           dwarf::DW_FORM_data4));
2015  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2016         E = CUMap.end(); I != E; ++I) {
2017    CompileUnit *TheCU = I->second;
2018    const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2019    for (StringMap<std::vector<DIE*> >::const_iterator
2020           GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2021      const char *Name = GI->getKeyData();
2022      const std::vector<DIE *> &Entities = GI->second;
2023      for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2024             DE = Entities.end(); DI != DE; ++DI)
2025        AT.AddName(Name, (*DI));
2026    }
2027  }
2028
2029  AT.FinalizeTable(Asm, "namespac");
2030  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2031                                 .getDwarfAccelNamespaceSection());
2032  MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2033  Asm->OutStreamer.EmitLabel(SectionBegin);
2034
2035  // Emit the full data.
2036  AT.Emit(Asm, SectionBegin, &InfoHolder);
2037}
2038
2039// Emit type dies into a hashed accelerator table.
2040void DwarfDebug::emitAccelTypes() {
2041  std::vector<DwarfAccelTable::Atom> Atoms;
2042  Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2043                                        dwarf::DW_FORM_data4));
2044  Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2045                                        dwarf::DW_FORM_data2));
2046  Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2047                                        dwarf::DW_FORM_data1));
2048  DwarfAccelTable AT(Atoms);
2049  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2050         E = CUMap.end(); I != E; ++I) {
2051    CompileUnit *TheCU = I->second;
2052    const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2053      = TheCU->getAccelTypes();
2054    for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2055           GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2056      const char *Name = GI->getKeyData();
2057      const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2058      for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2059             = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2060        AT.AddName(Name, (*DI).first, (*DI).second);
2061    }
2062  }
2063
2064  AT.FinalizeTable(Asm, "types");
2065  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2066                                 .getDwarfAccelTypesSection());
2067  MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2068  Asm->OutStreamer.EmitLabel(SectionBegin);
2069
2070  // Emit the full data.
2071  AT.Emit(Asm, SectionBegin, &InfoHolder);
2072}
2073
2074void DwarfDebug::emitDebugPubTypes() {
2075  for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2076         E = CUMap.end(); I != E; ++I) {
2077    CompileUnit *TheCU = I->second;
2078    // Start the dwarf pubtypes section.
2079    Asm->OutStreamer.SwitchSection(
2080      Asm->getObjFileLowering().getDwarfPubTypesSection());
2081    Asm->OutStreamer.AddComment("Length of Public Types Info");
2082    Asm->EmitLabelDifference(
2083      Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2084      Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2085
2086    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2087                                                  TheCU->getUniqueID()));
2088
2089    if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2090    Asm->EmitInt16(dwarf::DWARF_VERSION);
2091
2092    Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2093    const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2094    Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2095                                              TheCU->getUniqueID()),
2096                           DwarfInfoSectionSym);
2097
2098    Asm->OutStreamer.AddComment("Compilation Unit Length");
2099    Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2100                                                TheCU->getUniqueID()),
2101                             Asm->GetTempSymbol(ISec->getLabelBeginName(),
2102                                                TheCU->getUniqueID()),
2103                             4);
2104
2105    const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2106    for (StringMap<DIE*>::const_iterator
2107           GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2108      const char *Name = GI->getKeyData();
2109      DIE *Entity = GI->second;
2110
2111      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2112      Asm->EmitInt32(Entity->getOffset());
2113
2114      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2115      // Emit the name with a terminating null byte.
2116      Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2117    }
2118
2119    Asm->OutStreamer.AddComment("End Mark");
2120    Asm->EmitInt32(0);
2121    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2122                                                  TheCU->getUniqueID()));
2123  }
2124}
2125
2126// Emit strings into a string section.
2127void DwarfUnits::emitStrings(const MCSection *StrSection,
2128                             const MCSection *OffsetSection = NULL,
2129                             const MCSymbol *StrSecSym = NULL) {
2130
2131  if (StringPool.empty()) return;
2132
2133  // Start the dwarf str section.
2134  Asm->OutStreamer.SwitchSection(StrSection);
2135
2136  // Get all of the string pool entries and put them in an array by their ID so
2137  // we can sort them.
2138  SmallVector<std::pair<unsigned,
2139                 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2140
2141  for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2142         I = StringPool.begin(), E = StringPool.end();
2143       I != E; ++I)
2144    Entries.push_back(std::make_pair(I->second.second, &*I));
2145
2146  array_pod_sort(Entries.begin(), Entries.end());
2147
2148  for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2149    // Emit a label for reference from debug information entries.
2150    Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2151
2152    // Emit the string itself with a terminating null byte.
2153    Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2154                                         Entries[i].second->getKeyLength()+1));
2155  }
2156
2157  // If we've got an offset section go ahead and emit that now as well.
2158  if (OffsetSection) {
2159    Asm->OutStreamer.SwitchSection(OffsetSection);
2160    unsigned offset = 0;
2161    unsigned size = 4;
2162    for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2163      Asm->OutStreamer.EmitIntValue(offset, size);
2164      offset += Entries[i].second->getKeyLength() + 1;
2165    }
2166  }
2167}
2168
2169// Emit visible names into a debug str section.
2170void DwarfDebug::emitDebugStr() {
2171  DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2172  Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2173}
2174
2175// Emit visible names into a debug loc section.
2176void DwarfDebug::emitDebugLoc() {
2177  if (DotDebugLocEntries.empty())
2178    return;
2179
2180  for (SmallVector<DotDebugLocEntry, 4>::iterator
2181         I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2182       I != E; ++I) {
2183    DotDebugLocEntry &Entry = *I;
2184    if (I + 1 != DotDebugLocEntries.end())
2185      Entry.Merge(I+1);
2186  }
2187
2188  // Start the dwarf loc section.
2189  Asm->OutStreamer.SwitchSection(
2190    Asm->getObjFileLowering().getDwarfLocSection());
2191  unsigned char Size = Asm->getDataLayout().getPointerSize();
2192  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2193  unsigned index = 1;
2194  for (SmallVector<DotDebugLocEntry, 4>::iterator
2195         I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2196       I != E; ++I, ++index) {
2197    DotDebugLocEntry &Entry = *I;
2198    if (Entry.isMerged()) continue;
2199    if (Entry.isEmpty()) {
2200      Asm->OutStreamer.EmitIntValue(0, Size);
2201      Asm->OutStreamer.EmitIntValue(0, Size);
2202      Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2203    } else {
2204      Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size);
2205      Asm->OutStreamer.EmitSymbolValue(Entry.End, Size);
2206      DIVariable DV(Entry.Variable);
2207      Asm->OutStreamer.AddComment("Loc expr size");
2208      MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2209      MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2210      Asm->EmitLabelDifference(end, begin, 2);
2211      Asm->OutStreamer.EmitLabel(begin);
2212      if (Entry.isInt()) {
2213        DIBasicType BTy(DV.getType());
2214        if (BTy.Verify() &&
2215            (BTy.getEncoding()  == dwarf::DW_ATE_signed
2216             || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2217          Asm->OutStreamer.AddComment("DW_OP_consts");
2218          Asm->EmitInt8(dwarf::DW_OP_consts);
2219          Asm->EmitSLEB128(Entry.getInt());
2220        } else {
2221          Asm->OutStreamer.AddComment("DW_OP_constu");
2222          Asm->EmitInt8(dwarf::DW_OP_constu);
2223          Asm->EmitULEB128(Entry.getInt());
2224        }
2225      } else if (Entry.isLocation()) {
2226        if (!DV.hasComplexAddress())
2227          // Regular entry.
2228          Asm->EmitDwarfRegOp(Entry.Loc);
2229        else {
2230          // Complex address entry.
2231          unsigned N = DV.getNumAddrElements();
2232          unsigned i = 0;
2233          if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2234            if (Entry.Loc.getOffset()) {
2235              i = 2;
2236              Asm->EmitDwarfRegOp(Entry.Loc);
2237              Asm->OutStreamer.AddComment("DW_OP_deref");
2238              Asm->EmitInt8(dwarf::DW_OP_deref);
2239              Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2240              Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2241              Asm->EmitSLEB128(DV.getAddrElement(1));
2242            } else {
2243              // If first address element is OpPlus then emit
2244              // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2245              MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2246              Asm->EmitDwarfRegOp(Loc);
2247              i = 2;
2248            }
2249          } else {
2250            Asm->EmitDwarfRegOp(Entry.Loc);
2251          }
2252
2253          // Emit remaining complex address elements.
2254          for (; i < N; ++i) {
2255            uint64_t Element = DV.getAddrElement(i);
2256            if (Element == DIBuilder::OpPlus) {
2257              Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2258              Asm->EmitULEB128(DV.getAddrElement(++i));
2259            } else if (Element == DIBuilder::OpDeref) {
2260              if (!Entry.Loc.isReg())
2261                Asm->EmitInt8(dwarf::DW_OP_deref);
2262            } else
2263              llvm_unreachable("unknown Opcode found in complex address");
2264          }
2265        }
2266      }
2267      // else ... ignore constant fp. There is not any good way to
2268      // to represent them here in dwarf.
2269      Asm->OutStreamer.EmitLabel(end);
2270    }
2271  }
2272}
2273
2274// Emit visible names into a debug aranges section.
2275void DwarfDebug::emitDebugARanges() {
2276  // Start the dwarf aranges section.
2277  Asm->OutStreamer.SwitchSection(
2278                          Asm->getObjFileLowering().getDwarfARangesSection());
2279}
2280
2281// Emit visible names into a debug ranges section.
2282void DwarfDebug::emitDebugRanges() {
2283  // Start the dwarf ranges section.
2284  Asm->OutStreamer.SwitchSection(
2285    Asm->getObjFileLowering().getDwarfRangesSection());
2286  unsigned char Size = Asm->getDataLayout().getPointerSize();
2287  for (SmallVector<const MCSymbol *, 8>::iterator
2288         I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2289       I != E; ++I) {
2290    if (*I)
2291      Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2292    else
2293      Asm->OutStreamer.EmitIntValue(0, Size);
2294  }
2295}
2296
2297// Emit visible names into a debug macinfo section.
2298void DwarfDebug::emitDebugMacInfo() {
2299  if (const MCSection *LineInfo =
2300      Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2301    // Start the dwarf macinfo section.
2302    Asm->OutStreamer.SwitchSection(LineInfo);
2303  }
2304}
2305
2306// Emit inline info using following format.
2307// Section Header:
2308// 1. length of section
2309// 2. Dwarf version number
2310// 3. address size.
2311//
2312// Entries (one "entry" for each function that was inlined):
2313//
2314// 1. offset into __debug_str section for MIPS linkage name, if exists;
2315//   otherwise offset into __debug_str for regular function name.
2316// 2. offset into __debug_str section for regular function name.
2317// 3. an unsigned LEB128 number indicating the number of distinct inlining
2318// instances for the function.
2319//
2320// The rest of the entry consists of a {die_offset, low_pc} pair for each
2321// inlined instance; the die_offset points to the inlined_subroutine die in the
2322// __debug_info section, and the low_pc is the starting address for the
2323// inlining instance.
2324void DwarfDebug::emitDebugInlineInfo() {
2325  if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2326    return;
2327
2328  if (!FirstCU)
2329    return;
2330
2331  Asm->OutStreamer.SwitchSection(
2332                        Asm->getObjFileLowering().getDwarfDebugInlineSection());
2333
2334  Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2335  Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2336                           Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2337
2338  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2339
2340  Asm->OutStreamer.AddComment("Dwarf Version");
2341  Asm->EmitInt16(dwarf::DWARF_VERSION);
2342  Asm->OutStreamer.AddComment("Address Size (in bytes)");
2343  Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2344
2345  for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2346         E = InlinedSPNodes.end(); I != E; ++I) {
2347
2348    const MDNode *Node = *I;
2349    DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2350      = InlineInfo.find(Node);
2351    SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2352    DISubprogram SP(Node);
2353    StringRef LName = SP.getLinkageName();
2354    StringRef Name = SP.getName();
2355
2356    Asm->OutStreamer.AddComment("MIPS linkage name");
2357    if (LName.empty())
2358      Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2359                             DwarfStrSectionSym);
2360    else
2361      Asm->EmitSectionOffset(InfoHolder
2362                             .getStringPoolEntry(getRealLinkageName(LName)),
2363                             DwarfStrSectionSym);
2364
2365    Asm->OutStreamer.AddComment("Function name");
2366    Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2367                           DwarfStrSectionSym);
2368    Asm->EmitULEB128(Labels.size(), "Inline count");
2369
2370    for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2371           LE = Labels.end(); LI != LE; ++LI) {
2372      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2373      Asm->EmitInt32(LI->second->getOffset());
2374
2375      if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2376      Asm->OutStreamer.EmitSymbolValue(LI->first,
2377                                       Asm->getDataLayout().getPointerSize());
2378    }
2379  }
2380
2381  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2382}
2383
2384// DWARF5 Experimental Separate Dwarf emitters.
2385
2386// This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2387// DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2388// DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2389// DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2390CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2391  DICompileUnit DIUnit(N);
2392  StringRef FN = DIUnit.getFilename();
2393  CompilationDir = DIUnit.getDirectory();
2394
2395  DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2396  CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2397                                       DIUnit.getLanguage(), Die, Asm,
2398                                       this, &SkeletonHolder);
2399  // FIXME: This should be the .dwo file.
2400  NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name, FN);
2401
2402  // FIXME: We also need DW_AT_addr_base and DW_AT_dwo_id.
2403
2404  // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2405  // into an entity.
2406  NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2407  // DW_AT_stmt_list is a offset of line number information for this
2408  // compile unit in debug_line section.
2409  if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2410    NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
2411                    Asm->GetTempSymbol("section_line"));
2412  else
2413    NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
2414
2415  if (!CompilationDir.empty())
2416    NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2417
2418  SkeletonHolder.addUnit(NewCU);
2419
2420  return NewCU;
2421}
2422
2423void DwarfDebug::emitSkeletonCU(const MCSection *Section) {
2424  Asm->OutStreamer.SwitchSection(Section);
2425  DIE *Die = SkeletonCU->getCUDie();
2426
2427  // Emit the compile units header.
2428  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(Section->getLabelBeginName(),
2429                                                SkeletonCU->getUniqueID()));
2430
2431  // Emit size of content not including length itself
2432  unsigned ContentSize = Die->getSize() +
2433    sizeof(int16_t) + // DWARF version number
2434    sizeof(int32_t) + // Offset Into Abbrev. Section
2435    sizeof(int8_t);   // Pointer Size (in bytes)
2436
2437  Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2438  Asm->EmitInt32(ContentSize);
2439  Asm->OutStreamer.AddComment("DWARF version number");
2440  Asm->EmitInt16(dwarf::DWARF_VERSION);
2441  Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2442
2443  const MCSection *ASec = Asm->getObjFileLowering().getDwarfAbbrevSection();
2444  Asm->EmitSectionOffset(Asm->GetTempSymbol(ASec->getLabelBeginName()),
2445                         DwarfAbbrevSectionSym);
2446  Asm->OutStreamer.AddComment("Address Size (in bytes)");
2447  Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2448
2449  emitDIE(Die, &SkeletonAbbrevs);
2450  Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(Section->getLabelEndName(),
2451                                                SkeletonCU->getUniqueID()));
2452}
2453
2454void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2455  assert(useSplitDwarf() && "No split dwarf debug info?");
2456  emitAbbrevs(Section, &SkeletonAbbrevs);
2457}
2458
2459// Emit the .debug_info.dwo section for separated dwarf. This contains the
2460// compile units that would normally be in debug_info.
2461void DwarfDebug::emitDebugInfoDWO() {
2462  assert(useSplitDwarf() && "No split dwarf debug info?");
2463  InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2464                       Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2465                       DwarfAbbrevDWOSectionSym);
2466}
2467
2468// Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2469// abbreviations for the .debug_info.dwo section.
2470void DwarfDebug::emitDebugAbbrevDWO() {
2471  assert(useSplitDwarf() && "No split dwarf?");
2472  emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2473              &Abbreviations);
2474}
2475
2476// Emit the .debug_str.dwo section for separated dwarf. This contains the
2477// string section and is identical in format to traditional .debug_str
2478// sections.
2479void DwarfDebug::emitDebugStrDWO() {
2480  assert(useSplitDwarf() && "No split dwarf?");
2481  const MCSection *OffSec = Asm->getObjFileLowering()
2482                            .getDwarfStrOffDWOSection();
2483  const MCSymbol *StrSym = DwarfStrSectionSym;
2484  InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2485                         OffSec, StrSym);
2486}
2487