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