72ce337b203f350bf15d372b7d95699f87ebe445
[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 "DIEHash.h"
18 #include "DwarfAccelTable.h"
19 #include "DwarfUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/DIBuilder.h"
27 #include "llvm/DebugInfo.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/MD5.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/ValueHandle.h"
45 #include "llvm/Target/TargetFrameLowering.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
50 using namespace llvm;
51
52 static cl::opt<bool>
53 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
54                          cl::desc("Disable debug info printing"));
55
56 static cl::opt<bool> UnknownLocations(
57     "use-unknown-locations", cl::Hidden,
58     cl::desc("Make an absence of debug location information explicit."),
59     cl::init(false));
60
61 static cl::opt<bool> GenerateCUHash("generate-cu-hash", cl::Hidden,
62                                     cl::desc("Add the CU hash as the dwo_id."),
63                                     cl::init(false));
64
65 static cl::opt<bool>
66 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
67                        cl::desc("Generate GNU-style pubnames and pubtypes"),
68                        cl::init(false));
69
70 namespace {
71 enum DefaultOnOff { Default, Enable, Disable };
72 }
73
74 static cl::opt<DefaultOnOff>
75 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
76                  cl::desc("Output prototype dwarf accelerator tables."),
77                  cl::values(clEnumVal(Default, "Default for platform"),
78                             clEnumVal(Enable, "Enabled"),
79                             clEnumVal(Disable, "Disabled"), clEnumValEnd),
80                  cl::init(Default));
81
82 static cl::opt<DefaultOnOff>
83 SplitDwarf("split-dwarf", cl::Hidden,
84            cl::desc("Output DWARF5 split debug info."),
85            cl::values(clEnumVal(Default, "Default for platform"),
86                       clEnumVal(Enable, "Enabled"),
87                       clEnumVal(Disable, "Disabled"), clEnumValEnd),
88            cl::init(Default));
89
90 static cl::opt<DefaultOnOff>
91 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
92                  cl::desc("Generate DWARF pubnames and pubtypes sections"),
93                  cl::values(clEnumVal(Default, "Default for platform"),
94                             clEnumVal(Enable, "Enabled"),
95                             clEnumVal(Disable, "Disabled"), clEnumValEnd),
96                  cl::init(Default));
97
98 static cl::opt<unsigned>
99 DwarfVersionNumber("dwarf-version", cl::Hidden,
100                    cl::desc("Generate DWARF for dwarf version."), cl::init(0));
101
102 static cl::opt<bool>
103 DwarfCURanges("generate-dwarf-cu-ranges", cl::Hidden,
104               cl::desc("Generate DW_AT_ranges for compile units"),
105               cl::init(false));
106
107 static const char *const DWARFGroupName = "DWARF Emission";
108 static const char *const DbgTimerName = "DWARF Debug Writer";
109
110 //===----------------------------------------------------------------------===//
111
112 namespace llvm {
113
114 /// resolve - Look in the DwarfDebug map for the MDNode that
115 /// corresponds to the reference.
116 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
117   return DD->resolve(Ref);
118 }
119
120 DIType DbgVariable::getType() const {
121   DIType Ty = Var.getType();
122   // FIXME: isBlockByrefVariable should be reformulated in terms of complex
123   // addresses instead.
124   if (Var.isBlockByrefVariable()) {
125     /* Byref variables, in Blocks, are declared by the programmer as
126        "SomeType VarName;", but the compiler creates a
127        __Block_byref_x_VarName struct, and gives the variable VarName
128        either the struct, or a pointer to the struct, as its type.  This
129        is necessary for various behind-the-scenes things the compiler
130        needs to do with by-reference variables in blocks.
131
132        However, as far as the original *programmer* is concerned, the
133        variable should still have type 'SomeType', as originally declared.
134
135        The following function dives into the __Block_byref_x_VarName
136        struct to find the original type of the variable.  This will be
137        passed back to the code generating the type for the Debug
138        Information Entry for the variable 'VarName'.  'VarName' will then
139        have the original type 'SomeType' in its debug information.
140
141        The original type 'SomeType' will be the type of the field named
142        'VarName' inside the __Block_byref_x_VarName struct.
143
144        NOTE: In order for this to not completely fail on the debugger
145        side, the Debug Information Entry for the variable VarName needs to
146        have a DW_AT_location that tells the debugger how to unwind through
147        the pointers and __Block_byref_x_VarName struct to find the actual
148        value of the variable.  The function addBlockByrefType does this.  */
149     DIType subType = Ty;
150     uint16_t tag = Ty.getTag();
151
152     if (tag == dwarf::DW_TAG_pointer_type)
153       subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
154
155     DIArray Elements = DICompositeType(subType).getTypeArray();
156     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
157       DIDerivedType DT(Elements.getElement(i));
158       if (getName() == DT.getName())
159         return (resolve(DT.getTypeDerivedFrom()));
160     }
161   }
162   return Ty;
163 }
164
165 } // end llvm namespace
166
167 /// Return Dwarf Version by checking module flags.
168 static unsigned getDwarfVersionFromModule(const Module *M) {
169   Value *Val = M->getModuleFlag("Dwarf Version");
170   if (!Val)
171     return dwarf::DWARF_VERSION;
172   return cast<ConstantInt>(Val)->getZExtValue();
173 }
174
175 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
176     : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
177       PrevLabel(NULL), GlobalRangeCount(0),
178       InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
179       SkeletonHolder(A, "skel_string", DIEValueAllocator) {
180
181   DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
182   DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
183   DwarfAddrSectionSym = 0;
184   DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
185   FunctionBeginSym = FunctionEndSym = 0;
186   CurFn = 0;
187   CurMI = 0;
188
189   // Turn on accelerator tables for Darwin by default, pubnames by
190   // default for non-Darwin, and handle split dwarf.
191   bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
192
193   if (DwarfAccelTables == Default)
194     HasDwarfAccelTables = IsDarwin;
195   else
196     HasDwarfAccelTables = DwarfAccelTables == Enable;
197
198   if (SplitDwarf == Default)
199     HasSplitDwarf = false;
200   else
201     HasSplitDwarf = SplitDwarf == Enable;
202
203   if (DwarfPubSections == Default)
204     HasDwarfPubSections = !IsDarwin;
205   else
206     HasDwarfPubSections = DwarfPubSections == Enable;
207
208   DwarfVersion = DwarfVersionNumber
209                      ? DwarfVersionNumber
210                      : getDwarfVersionFromModule(MMI->getModule());
211
212   {
213     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
214     beginModule();
215   }
216 }
217
218 // Switch to the specified MCSection and emit an assembler
219 // temporary label to it if SymbolStem is specified.
220 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
221                                 const char *SymbolStem = 0) {
222   Asm->OutStreamer.SwitchSection(Section);
223   if (!SymbolStem)
224     return 0;
225
226   MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
227   Asm->OutStreamer.EmitLabel(TmpSym);
228   return TmpSym;
229 }
230
231 DwarfFile::~DwarfFile() {
232   for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
233        I != E; ++I)
234     delete *I;
235 }
236
237 MCSymbol *DwarfFile::getStringPoolSym() {
238   return Asm->GetTempSymbol(StringPref);
239 }
240
241 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
242   std::pair<MCSymbol *, unsigned> &Entry =
243       StringPool.GetOrCreateValue(Str).getValue();
244   if (Entry.first)
245     return Entry.first;
246
247   Entry.second = NextStringPoolNumber++;
248   return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
249 }
250
251 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
252   std::pair<MCSymbol *, unsigned> &Entry =
253       StringPool.GetOrCreateValue(Str).getValue();
254   if (Entry.first)
255     return Entry.second;
256
257   Entry.second = NextStringPoolNumber++;
258   Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
259   return Entry.second;
260 }
261
262 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym) {
263   return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
264 }
265
266 unsigned DwarfFile::getAddrPoolIndex(const MCExpr *Sym) {
267   std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
268       AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
269   if (P.second)
270     ++NextAddrPoolNumber;
271   return P.first->second;
272 }
273
274 // Define a unique number for the abbreviation.
275 //
276 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
277   // Check the set for priors.
278   DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
279
280   // If it's newly added.
281   if (InSet == &Abbrev) {
282     // Add to abbreviation list.
283     Abbreviations.push_back(&Abbrev);
284
285     // Assign the vector position + 1 as its number.
286     Abbrev.setNumber(Abbreviations.size());
287   } else {
288     // Assign existing abbreviation number.
289     Abbrev.setNumber(InSet->getNumber());
290   }
291 }
292
293 static bool isObjCClass(StringRef Name) {
294   return Name.startswith("+") || Name.startswith("-");
295 }
296
297 static bool hasObjCCategory(StringRef Name) {
298   if (!isObjCClass(Name))
299     return false;
300
301   return Name.find(") ") != StringRef::npos;
302 }
303
304 static void getObjCClassCategory(StringRef In, StringRef &Class,
305                                  StringRef &Category) {
306   if (!hasObjCCategory(In)) {
307     Class = In.slice(In.find('[') + 1, In.find(' '));
308     Category = "";
309     return;
310   }
311
312   Class = In.slice(In.find('[') + 1, In.find('('));
313   Category = In.slice(In.find('[') + 1, In.find(' '));
314   return;
315 }
316
317 static StringRef getObjCMethodName(StringRef In) {
318   return In.slice(In.find(' ') + 1, In.find(']'));
319 }
320
321 // Helper for sorting sections into a stable output order.
322 static bool SectionSort(const MCSection *A, const MCSection *B) {
323   std::string LA = (A ? A->getLabelBeginName() : "");
324   std::string LB = (B ? B->getLabelBeginName() : "");
325   return LA < LB;
326 }
327
328 // Add the various names to the Dwarf accelerator table names.
329 // TODO: Determine whether or not we should add names for programs
330 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
331 // is only slightly different than the lookup of non-standard ObjC names.
332 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
333   if (!SP.isDefinition())
334     return;
335   TheU->addAccelName(SP.getName(), Die);
336
337   // If the linkage name is different than the name, go ahead and output
338   // that as well into the name table.
339   if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
340     TheU->addAccelName(SP.getLinkageName(), Die);
341
342   // If this is an Objective-C selector name add it to the ObjC accelerator
343   // too.
344   if (isObjCClass(SP.getName())) {
345     StringRef Class, Category;
346     getObjCClassCategory(SP.getName(), Class, Category);
347     TheU->addAccelObjC(Class, Die);
348     if (Category != "")
349       TheU->addAccelObjC(Category, Die);
350     // Also add the base method name to the name table.
351     TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
352   }
353 }
354
355 /// isSubprogramContext - Return true if Context is either a subprogram
356 /// or another context nested inside a subprogram.
357 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
358   if (!Context)
359     return false;
360   DIDescriptor D(Context);
361   if (D.isSubprogram())
362     return true;
363   if (D.isType())
364     return isSubprogramContext(resolve(DIType(Context).getContext()));
365   return false;
366 }
367
368 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
369 // and DW_AT_high_pc attributes. If there are global variables in this
370 // scope then create and insert DIEs for these variables.
371 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
372                                           DISubprogram SP) {
373   DIE *SPDie = SPCU->getDIE(SP);
374
375   assert(SPDie && "Unable to find subprogram DIE!");
376
377   // If we're updating an abstract DIE, then we will be adding the children and
378   // object pointer later on. But what we don't want to do is process the
379   // concrete DIE twice.
380   if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
381     // Pick up abstract subprogram DIE.
382     SPDie =
383         SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
384     SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
385   } else {
386     DISubprogram SPDecl = SP.getFunctionDeclaration();
387     if (!SPDecl.isSubprogram()) {
388       // There is not any need to generate specification DIE for a function
389       // defined at compile unit level. If a function is defined inside another
390       // function then gdb prefers the definition at top level and but does not
391       // expect specification DIE in parent function. So avoid creating
392       // specification DIE for a function defined inside a function.
393       DIScope SPContext = resolve(SP.getContext());
394       if (SP.isDefinition() && !SPContext.isCompileUnit() &&
395           !SPContext.isFile() && !isSubprogramContext(SPContext)) {
396         SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
397
398         // Add arguments.
399         DICompositeType SPTy = SP.getType();
400         DIArray Args = SPTy.getTypeArray();
401         uint16_t SPTag = SPTy.getTag();
402         if (SPTag == dwarf::DW_TAG_subroutine_type)
403           for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
404             DIE *Arg =
405                 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
406             DIType ATy(Args.getElement(i));
407             SPCU->addType(Arg, ATy);
408             if (ATy.isArtificial())
409               SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
410             if (ATy.isObjectPointer())
411               SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
412           }
413         DIE *SPDeclDie = SPDie;
414         SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
415                                       *SPCU->getUnitDie());
416         SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
417       }
418     }
419   }
420
421   SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc, FunctionBeginSym);
422   SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc, FunctionEndSym);
423
424   // Add this range to the list of ranges for the CU.
425   RangeSpan Span(FunctionBeginSym, FunctionEndSym);
426   SPCU->addRange(llvm_move(Span));
427
428   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
429   MachineLocation Location(RI->getFrameRegister(*Asm->MF));
430   SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
431
432   // Add name to the name table, we do this here because we're guaranteed
433   // to have concrete versions of our DW_TAG_subprogram nodes.
434   addSubprogramNames(SPCU, SP, SPDie);
435
436   return SPDie;
437 }
438
439 /// Check whether we should create a DIE for the given Scope, return true
440 /// if we don't create a DIE (the corresponding DIE is null).
441 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
442   if (Scope->isAbstractScope())
443     return false;
444
445   // We don't create a DIE if there is no Range.
446   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
447   if (Ranges.empty())
448     return true;
449
450   if (Ranges.size() > 1)
451     return false;
452
453   // We don't create a DIE if we have a single Range and the end label
454   // is null.
455   SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
456   MCSymbol *End = getLabelAfterInsn(RI->second);
457   return !End;
458 }
459
460 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
461                             dwarf::Attribute A, const MCSymbol *L,
462                             const MCSymbol *Sec) {
463   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
464     U->addSectionLabel(D, A, L);
465   else
466     U->addSectionDelta(D, A, L, Sec);
467 }
468
469 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
470                                    const SmallVectorImpl<InsnRange> &Range) {
471   // Emit offset in .debug_range as a relocatable label. emitDIE will handle
472   // emitting it appropriately.
473   MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
474   addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
475                   DwarfDebugRangeSectionSym);
476
477   RangeSpanList List(RangeSym);
478   for (SmallVectorImpl<InsnRange>::const_iterator RI = Range.begin(),
479                                                   RE = Range.end();
480        RI != RE; ++RI) {
481     RangeSpan Span(getLabelBeforeInsn(RI->first),
482                    getLabelAfterInsn(RI->second));
483     List.addRange(llvm_move(Span));
484   }
485
486   // Add the range list to the set of ranges to be emitted.
487   TheCU->addRangeList(llvm_move(List));
488 }
489
490 // Construct new DW_TAG_lexical_block for this scope and attach
491 // DW_AT_low_pc/DW_AT_high_pc labels.
492 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
493                                           LexicalScope *Scope) {
494   if (isLexicalScopeDIENull(Scope))
495     return 0;
496
497   DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
498   if (Scope->isAbstractScope())
499     return ScopeDIE;
500
501   const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
502
503   // If we have multiple ranges, emit them into the range section.
504   if (ScopeRanges.size() > 1) {
505     addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
506     return ScopeDIE;
507   }
508
509   // Construct the address range for this DIE.
510   SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
511   MCSymbol *Start = getLabelBeforeInsn(RI->first);
512   MCSymbol *End = getLabelAfterInsn(RI->second);
513   assert(End && "End label should not be null!");
514
515   assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
516   assert(End->isDefined() && "Invalid end label for an inlined scope!");
517
518   TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
519   TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
520
521   return ScopeDIE;
522 }
523
524 // This scope represents inlined body of a function. Construct DIE to
525 // represent this concrete inlined copy of the function.
526 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
527                                           LexicalScope *Scope) {
528   const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
529   assert(!ScopeRanges.empty() &&
530          "LexicalScope does not have instruction markers!");
531
532   if (!Scope->getScopeNode())
533     return NULL;
534   DIScope DS(Scope->getScopeNode());
535   DISubprogram InlinedSP = getDISubprogram(DS);
536   DIE *OriginDIE = TheCU->getDIE(InlinedSP);
537   if (!OriginDIE) {
538     DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
539     return NULL;
540   }
541
542   DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
543   TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
544
545   // If we have multiple ranges, emit them into the range section.
546   if (ScopeRanges.size() > 1)
547     addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
548   else {
549     SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
550     MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
551     MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
552
553     if (StartLabel == 0 || EndLabel == 0)
554       llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
555
556     assert(StartLabel->isDefined() &&
557            "Invalid starting label for an inlined scope!");
558     assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
559
560     TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
561     TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
562   }
563
564   InlinedSubprogramDIEs.insert(OriginDIE);
565
566   // Add the call site information to the DIE.
567   DILocation DL(Scope->getInlinedAt());
568   TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
569                  getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
570                                      TheCU->getUniqueID()));
571   TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
572
573   // Add name to the name table, we do this here because we're guaranteed
574   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
575   addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
576
577   return ScopeDIE;
578 }
579
580 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
581                                         LexicalScope *Scope,
582                                         SmallVectorImpl<DIE *> &Children) {
583   DIE *ObjectPointer = NULL;
584
585   // Collect arguments for current function.
586   if (LScopes.isCurrentFunctionScope(Scope))
587     for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
588       if (DbgVariable *ArgDV = CurrentFnArguments[i])
589         if (DIE *Arg =
590                 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
591           Children.push_back(Arg);
592           if (ArgDV->isObjectPointer())
593             ObjectPointer = Arg;
594         }
595
596   // Collect lexical scope children first.
597   const SmallVectorImpl<DbgVariable *> &Variables =
598       ScopeVariables.lookup(Scope);
599   for (unsigned i = 0, N = Variables.size(); i < N; ++i)
600     if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
601                                                     Scope->isAbstractScope())) {
602       Children.push_back(Variable);
603       if (Variables[i]->isObjectPointer())
604         ObjectPointer = Variable;
605     }
606   const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
607   for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
608     if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
609       Children.push_back(Nested);
610   return ObjectPointer;
611 }
612
613 // Construct a DIE for this scope.
614 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
615                                    LexicalScope *Scope) {
616   if (!Scope || !Scope->getScopeNode())
617     return NULL;
618
619   DIScope DS(Scope->getScopeNode());
620
621   SmallVector<DIE *, 8> Children;
622   DIE *ObjectPointer = NULL;
623   bool ChildrenCreated = false;
624
625   // We try to create the scope DIE first, then the children DIEs. This will
626   // avoid creating un-used children then removing them later when we find out
627   // the scope DIE is null.
628   DIE *ScopeDIE = NULL;
629   if (Scope->getInlinedAt())
630     ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
631   else if (DS.isSubprogram()) {
632     ProcessedSPNodes.insert(DS);
633     if (Scope->isAbstractScope()) {
634       ScopeDIE = TheCU->getDIE(DS);
635       // Note down abstract DIE.
636       if (ScopeDIE)
637         AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
638     } else
639       ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
640   } else {
641     // Early exit when we know the scope DIE is going to be null.
642     if (isLexicalScopeDIENull(Scope))
643       return NULL;
644
645     // We create children here when we know the scope DIE is not going to be
646     // null and the children will be added to the scope DIE.
647     ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
648     ChildrenCreated = true;
649
650     // There is no need to emit empty lexical block DIE.
651     std::pair<ImportedEntityMap::const_iterator,
652               ImportedEntityMap::const_iterator> Range =
653         std::equal_range(
654             ScopesWithImportedEntities.begin(),
655             ScopesWithImportedEntities.end(),
656             std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
657             less_first());
658     if (Children.empty() && Range.first == Range.second)
659       return NULL;
660     ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
661     assert(ScopeDIE && "Scope DIE should not be null.");
662     for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
663          ++i)
664       constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
665   }
666
667   if (!ScopeDIE) {
668     assert(Children.empty() &&
669            "We create children only when the scope DIE is not null.");
670     return NULL;
671   }
672   if (!ChildrenCreated)
673     // We create children when the scope DIE is not null.
674     ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
675
676   // Add children
677   for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
678                                         E = Children.end();
679        I != E; ++I)
680     ScopeDIE->addChild(*I);
681
682   if (DS.isSubprogram() && ObjectPointer != NULL)
683     TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
684
685   return ScopeDIE;
686 }
687
688 // Look up the source id with the given directory and source file names.
689 // If none currently exists, create a new id and insert it in the
690 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
691 // as well.
692 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
693                                          unsigned CUID) {
694   // If we use .loc in assembly, we can't separate .file entries according to
695   // compile units. Thus all files will belong to the default compile unit.
696
697   // FIXME: add a better feature test than hasRawTextSupport. Even better,
698   // extend .file to support this.
699   if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
700     CUID = 0;
701
702   // If FE did not provide a file name, then assume stdin.
703   if (FileName.empty())
704     return getOrCreateSourceID("<stdin>", StringRef(), CUID);
705
706   // TODO: this might not belong here. See if we can factor this better.
707   if (DirName == CompilationDir)
708     DirName = "";
709
710   // FileIDCUMap stores the current ID for the given compile unit.
711   unsigned SrcId = FileIDCUMap[CUID] + 1;
712
713   // We look up the CUID/file/dir by concatenating them with a zero byte.
714   SmallString<128> NamePair;
715   NamePair += utostr(CUID);
716   NamePair += '\0';
717   NamePair += DirName;
718   NamePair += '\0'; // Zero bytes are not allowed in paths.
719   NamePair += FileName;
720
721   StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
722   if (Ent.getValue() != SrcId)
723     return Ent.getValue();
724
725   FileIDCUMap[CUID] = SrcId;
726   // Print out a .file directive to specify files for .loc directives.
727   Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
728
729   return SrcId;
730 }
731
732 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
733   if (!GenerateGnuPubSections)
734     return;
735
736   addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubnames,
737                   Asm->GetTempSymbol("gnu_pubnames", U->getUniqueID()),
738                   DwarfGnuPubNamesSectionSym);
739
740   addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubtypes,
741                   Asm->GetTempSymbol("gnu_pubtypes", U->getUniqueID()),
742                   DwarfGnuPubTypesSectionSym);
743 }
744
745 // Create new DwarfCompileUnit for the given metadata node with tag
746 // DW_TAG_compile_unit.
747 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
748   StringRef FN = DIUnit.getFilename();
749   CompilationDir = DIUnit.getDirectory();
750
751   DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
752   DwarfCompileUnit *NewCU = new DwarfCompileUnit(
753       InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
754   InfoHolder.addUnit(NewCU);
755
756   FileIDCUMap[NewCU->getUniqueID()] = 0;
757   // Call this to emit a .file directive if it wasn't emitted for the source
758   // file this CU comes from yet.
759   getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
760
761   NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
762   NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
763                  DIUnit.getLanguage());
764   NewCU->addString(Die, dwarf::DW_AT_name, FN);
765
766   // Define start line table label for each Compile Unit.
767   MCSymbol *LineTableStartSym =
768       Asm->GetTempSymbol("line_table_start", NewCU->getUniqueID());
769   Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
770                                                      NewCU->getUniqueID());
771
772   // Use a single line table if we are using .loc and generating assembly.
773   bool UseTheFirstCU =
774       (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
775       (NewCU->getUniqueID() == 0);
776
777   if (!useSplitDwarf()) {
778     // DW_AT_stmt_list is a offset of line number information for this
779     // compile unit in debug_line section. For split dwarf this is
780     // left in the skeleton CU and so not included.
781     // The line table entries are not always emitted in assembly, so it
782     // is not okay to use line_table_start here.
783     if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
784       NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list,
785                              UseTheFirstCU ? Asm->GetTempSymbol("section_line")
786                                            : LineTableStartSym);
787     else if (UseTheFirstCU)
788       NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
789     else
790       NewCU->addSectionDelta(Die, dwarf::DW_AT_stmt_list, LineTableStartSym,
791                              DwarfLineSectionSym);
792
793     // If we're using split dwarf the compilation dir is going to be in the
794     // skeleton CU and so we don't need to duplicate it here.
795     if (!CompilationDir.empty())
796       NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
797
798     addGnuPubAttributes(NewCU, Die);
799   }
800
801   if (DIUnit.isOptimized())
802     NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
803
804   StringRef Flags = DIUnit.getFlags();
805   if (!Flags.empty())
806     NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
807
808   if (unsigned RVer = DIUnit.getRunTimeVersion())
809     NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
810                    dwarf::DW_FORM_data1, RVer);
811
812   if (!FirstCU)
813     FirstCU = NewCU;
814
815   if (useSplitDwarf()) {
816     NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
817                        DwarfInfoDWOSectionSym);
818     NewCU->setSkeleton(constructSkeletonCU(NewCU));
819   } else
820     NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
821                        DwarfInfoSectionSym);
822
823   CUMap.insert(std::make_pair(DIUnit, NewCU));
824   CUDieMap.insert(std::make_pair(Die, NewCU));
825   return NewCU;
826 }
827
828 // Construct subprogram DIE.
829 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
830                                         const MDNode *N) {
831   // FIXME: We should only call this routine once, however, during LTO if a
832   // program is defined in multiple CUs we could end up calling it out of
833   // beginModule as we walk the CUs.
834
835   DwarfCompileUnit *&CURef = SPMap[N];
836   if (CURef)
837     return;
838   CURef = TheCU;
839
840   DISubprogram SP(N);
841   if (!SP.isDefinition())
842     // This is a method declaration which will be handled while constructing
843     // class type.
844     return;
845
846   DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
847
848   // Expose as a global name.
849   TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
850 }
851
852 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
853                                             const MDNode *N) {
854   DIImportedEntity Module(N);
855   if (!Module.Verify())
856     return;
857   if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
858     constructImportedEntityDIE(TheCU, Module, D);
859 }
860
861 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
862                                             const MDNode *N, DIE *Context) {
863   DIImportedEntity Module(N);
864   if (!Module.Verify())
865     return;
866   return constructImportedEntityDIE(TheCU, Module, Context);
867 }
868
869 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
870                                             const DIImportedEntity &Module,
871                                             DIE *Context) {
872   assert(Module.Verify() &&
873          "Use one of the MDNode * overloads to handle invalid metadata");
874   assert(Context && "Should always have a context for an imported_module");
875   DIE *IMDie = new DIE(Module.getTag());
876   TheCU->insertDIE(Module, IMDie);
877   DIE *EntityDie;
878   DIDescriptor Entity = Module.getEntity();
879   if (Entity.isNameSpace())
880     EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
881   else if (Entity.isSubprogram())
882     EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
883   else if (Entity.isType())
884     EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
885   else
886     EntityDie = TheCU->getDIE(Entity);
887   unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
888                                         Module.getContext().getDirectory(),
889                                         TheCU->getUniqueID());
890   TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
891   TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
892   TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
893   StringRef Name = Module.getName();
894   if (!Name.empty())
895     TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
896   Context->addChild(IMDie);
897 }
898
899 // Emit all Dwarf sections that should come prior to the content. Create
900 // global DIEs and emit initial debug info sections. This is invoked by
901 // the target AsmPrinter.
902 void DwarfDebug::beginModule() {
903   if (DisableDebugInfoPrinting)
904     return;
905
906   const Module *M = MMI->getModule();
907
908   // If module has named metadata anchors then use them, otherwise scan the
909   // module using debug info finder to collect debug info.
910   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
911   if (!CU_Nodes)
912     return;
913   TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
914
915   // Emit initial sections so we can reference labels later.
916   emitSectionLabels();
917
918   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
919     DICompileUnit CUNode(CU_Nodes->getOperand(i));
920     DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
921     DIArray ImportedEntities = CUNode.getImportedEntities();
922     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
923       ScopesWithImportedEntities.push_back(std::make_pair(
924           DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
925           ImportedEntities.getElement(i)));
926     std::sort(ScopesWithImportedEntities.begin(),
927               ScopesWithImportedEntities.end(), less_first());
928     DIArray GVs = CUNode.getGlobalVariables();
929     for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
930       CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
931     DIArray SPs = CUNode.getSubprograms();
932     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
933       constructSubprogramDIE(CU, SPs.getElement(i));
934     DIArray EnumTypes = CUNode.getEnumTypes();
935     for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
936       CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
937     DIArray RetainedTypes = CUNode.getRetainedTypes();
938     for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
939       CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
940     // Emit imported_modules last so that the relevant context is already
941     // available.
942     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
943       constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
944   }
945
946   // Tell MMI that we have debug info.
947   MMI->setDebugInfoAvailability(true);
948
949   // Prime section data.
950   SectionMap[Asm->getObjFileLowering().getTextSection()];
951 }
952
953 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
954 void DwarfDebug::computeInlinedDIEs() {
955   // Attach DW_AT_inline attribute with inlined subprogram DIEs.
956   for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
957                                        AE = InlinedSubprogramDIEs.end();
958        AI != AE; ++AI) {
959     DIE *ISP = *AI;
960     FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
961   }
962   for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
963                                                  AE = AbstractSPDies.end();
964        AI != AE; ++AI) {
965     DIE *ISP = AI->second;
966     if (InlinedSubprogramDIEs.count(ISP))
967       continue;
968     FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
969   }
970 }
971
972 // Collect info for variables that were optimized out.
973 void DwarfDebug::collectDeadVariables() {
974   const Module *M = MMI->getModule();
975
976   if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
977     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
978       DICompileUnit TheCU(CU_Nodes->getOperand(i));
979       DIArray Subprograms = TheCU.getSubprograms();
980       for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
981         DISubprogram SP(Subprograms.getElement(i));
982         if (ProcessedSPNodes.count(SP) != 0)
983           continue;
984         if (!SP.isSubprogram())
985           continue;
986         if (!SP.isDefinition())
987           continue;
988         DIArray Variables = SP.getVariables();
989         if (Variables.getNumElements() == 0)
990           continue;
991
992         // Construct subprogram DIE and add variables DIEs.
993         DwarfCompileUnit *SPCU =
994             static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
995         assert(SPCU && "Unable to find Compile Unit!");
996         // FIXME: See the comment in constructSubprogramDIE about duplicate
997         // subprogram DIEs.
998         constructSubprogramDIE(SPCU, SP);
999         DIE *SPDIE = SPCU->getDIE(SP);
1000         for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
1001           DIVariable DV(Variables.getElement(vi));
1002           if (!DV.isVariable())
1003             continue;
1004           DbgVariable NewVar(DV, NULL, this);
1005           if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
1006             SPDIE->addChild(VariableDIE);
1007         }
1008       }
1009     }
1010   }
1011 }
1012
1013 void DwarfDebug::finalizeModuleInfo() {
1014   // Collect info for variables that were optimized out.
1015   collectDeadVariables();
1016
1017   // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1018   computeInlinedDIEs();
1019
1020   // Handle anything that needs to be done on a per-unit basis after
1021   // all other generation.
1022   for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
1023                                                     E = getUnits().end();
1024        I != E; ++I) {
1025     DwarfUnit *TheU = *I;
1026     // Emit DW_AT_containing_type attribute to connect types with their
1027     // vtable holding type.
1028     TheU->constructContainingTypeDIEs();
1029
1030     // Add CU specific attributes if we need to add any.
1031     if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1032       // If we're splitting the dwarf out now that we've got the entire
1033       // CU then add the dwo id to it.
1034       DwarfCompileUnit *SkCU =
1035           static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
1036       if (useSplitDwarf()) {
1037         // This should be a unique identifier when we want to build .dwp files.
1038         uint64_t ID = 0;
1039         if (GenerateCUHash) {
1040           DIEHash CUHash;
1041           ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1042         }
1043         TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1044                       dwarf::DW_FORM_data8, ID);
1045         SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1046                       dwarf::DW_FORM_data8, ID);
1047       }
1048
1049       // If we have code split among multiple sections or we've requested
1050       // it then emit a DW_AT_ranges attribute on the unit that will remain
1051       // in the .o file, otherwise add a DW_AT_low_pc.
1052       // FIXME: Also add a high pc if we can.
1053       // FIXME: We should use ranges if we have multiple compile units or
1054       // allow reordering of code ala .subsections_via_symbols in mach-o.
1055       DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1056       if (useCURanges() && TheU->getRanges().size())
1057         addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1058                         Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1059                         DwarfDebugRangeSectionSym);
1060       else
1061         U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1062                    0);
1063     }
1064   }
1065
1066   // Compute DIE offsets and sizes.
1067   InfoHolder.computeSizeAndOffsets();
1068   if (useSplitDwarf())
1069     SkeletonHolder.computeSizeAndOffsets();
1070 }
1071
1072 void DwarfDebug::endSections() {
1073   // Filter labels by section.
1074   for (size_t n = 0; n < ArangeLabels.size(); n++) {
1075     const SymbolCU &SCU = ArangeLabels[n];
1076     if (SCU.Sym->isInSection()) {
1077       // Make a note of this symbol and it's section.
1078       const MCSection *Section = &SCU.Sym->getSection();
1079       if (!Section->getKind().isMetadata())
1080         SectionMap[Section].push_back(SCU);
1081     } else {
1082       // Some symbols (e.g. common/bss on mach-o) can have no section but still
1083       // appear in the output. This sucks as we rely on sections to build
1084       // arange spans. We can do it without, but it's icky.
1085       SectionMap[NULL].push_back(SCU);
1086     }
1087   }
1088
1089   // Build a list of sections used.
1090   std::vector<const MCSection *> Sections;
1091   for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1092        it++) {
1093     const MCSection *Section = it->first;
1094     Sections.push_back(Section);
1095   }
1096
1097   // Sort the sections into order.
1098   // This is only done to ensure consistent output order across different runs.
1099   std::sort(Sections.begin(), Sections.end(), SectionSort);
1100
1101   // Add terminating symbols for each section.
1102   for (unsigned ID = 0; ID < Sections.size(); ID++) {
1103     const MCSection *Section = Sections[ID];
1104     MCSymbol *Sym = NULL;
1105
1106     if (Section) {
1107       // We can't call MCSection::getLabelEndName, as it's only safe to do so
1108       // if we know the section name up-front. For user-created sections, the
1109       // resulting
1110       // label may not be valid to use as a label. (section names can use a
1111       // greater
1112       // set of characters on some systems)
1113       Sym = Asm->GetTempSymbol("debug_end", ID);
1114       Asm->OutStreamer.SwitchSection(Section);
1115       Asm->OutStreamer.EmitLabel(Sym);
1116     }
1117
1118     // Insert a final terminator.
1119     SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1120   }
1121
1122   // For now only turn on CU ranges if we've explicitly asked for it,
1123   // we have -ffunction-sections enabled, or we've emitted a function
1124   // into a unique section. At this point all sections should be finalized
1125   // except for dwarf sections.
1126   HasCURanges = DwarfCURanges || Asm->TM.debugUseUniqueSections() ||
1127                 TargetMachine::getFunctionSections();
1128 }
1129
1130 // Emit all Dwarf sections that should come after the content.
1131 void DwarfDebug::endModule() {
1132   assert(CurFn == 0);
1133   assert(CurMI == 0);
1134
1135   if (!FirstCU)
1136     return;
1137
1138   // End any existing sections.
1139   // TODO: Does this need to happen?
1140   endSections();
1141
1142   // Finalize the debug info for the module.
1143   finalizeModuleInfo();
1144
1145   emitDebugStr();
1146
1147   // Emit all the DIEs into a debug info section.
1148   emitDebugInfo();
1149
1150   // Corresponding abbreviations into a abbrev section.
1151   emitAbbreviations();
1152
1153   // Emit info into a debug loc section.
1154   emitDebugLoc();
1155
1156   // Emit info into a debug aranges section.
1157   emitDebugARanges();
1158
1159   // Emit info into a debug ranges section.
1160   emitDebugRanges();
1161
1162   if (useSplitDwarf()) {
1163     emitDebugStrDWO();
1164     emitDebugInfoDWO();
1165     emitDebugAbbrevDWO();
1166     // Emit DWO addresses.
1167     InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1168   }
1169
1170   // Emit info into the dwarf accelerator table sections.
1171   if (useDwarfAccelTables()) {
1172     emitAccelNames();
1173     emitAccelObjC();
1174     emitAccelNamespaces();
1175     emitAccelTypes();
1176   }
1177
1178   // Emit the pubnames and pubtypes sections if requested.
1179   if (HasDwarfPubSections) {
1180     emitDebugPubNames(GenerateGnuPubSections);
1181     emitDebugPubTypes(GenerateGnuPubSections);
1182   }
1183
1184   // clean up.
1185   SPMap.clear();
1186
1187   // Reset these for the next Module if we have one.
1188   FirstCU = NULL;
1189 }
1190
1191 // Find abstract variable, if any, associated with Var.
1192 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1193                                               DebugLoc ScopeLoc) {
1194   LLVMContext &Ctx = DV->getContext();
1195   // More then one inlined variable corresponds to one abstract variable.
1196   DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1197   DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1198   if (AbsDbgVariable)
1199     return AbsDbgVariable;
1200
1201   LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1202   if (!Scope)
1203     return NULL;
1204
1205   AbsDbgVariable = new DbgVariable(Var, NULL, this);
1206   addScopeVariable(Scope, AbsDbgVariable);
1207   AbstractVariables[Var] = AbsDbgVariable;
1208   return AbsDbgVariable;
1209 }
1210
1211 // If Var is a current function argument then add it to CurrentFnArguments list.
1212 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1213   if (!LScopes.isCurrentFunctionScope(Scope))
1214     return false;
1215   DIVariable DV = Var->getVariable();
1216   if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1217     return false;
1218   unsigned ArgNo = DV.getArgNumber();
1219   if (ArgNo == 0)
1220     return false;
1221
1222   size_t Size = CurrentFnArguments.size();
1223   if (Size == 0)
1224     CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1225   // llvm::Function argument size is not good indicator of how many
1226   // arguments does the function have at source level.
1227   if (ArgNo > Size)
1228     CurrentFnArguments.resize(ArgNo * 2);
1229   CurrentFnArguments[ArgNo - 1] = Var;
1230   return true;
1231 }
1232
1233 // Collect variable information from side table maintained by MMI.
1234 void DwarfDebug::collectVariableInfoFromMMITable(
1235     SmallPtrSet<const MDNode *, 16> &Processed) {
1236   MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1237   for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1238                                                          VE = VMap.end();
1239        VI != VE; ++VI) {
1240     const MDNode *Var = VI->first;
1241     if (!Var)
1242       continue;
1243     Processed.insert(Var);
1244     DIVariable DV(Var);
1245     const std::pair<unsigned, DebugLoc> &VP = VI->second;
1246
1247     LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1248
1249     // If variable scope is not found then skip this variable.
1250     if (Scope == 0)
1251       continue;
1252
1253     DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1254     DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1255     RegVar->setFrameIndex(VP.first);
1256     if (!addCurrentFnArgument(RegVar, Scope))
1257       addScopeVariable(Scope, RegVar);
1258     if (AbsDbgVariable)
1259       AbsDbgVariable->setFrameIndex(VP.first);
1260   }
1261 }
1262
1263 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1264 // defined reg.
1265 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1266   assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1267   return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1268          MI->getOperand(0).getReg() &&
1269          (MI->getOperand(1).isImm() ||
1270           (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1271 }
1272
1273 // Get .debug_loc entry for the instruction range starting at MI.
1274 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1275                                          const MCSymbol *FLabel,
1276                                          const MCSymbol *SLabel,
1277                                          const MachineInstr *MI) {
1278   const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1279
1280   assert(MI->getNumOperands() == 3);
1281   if (MI->getOperand(0).isReg()) {
1282     MachineLocation MLoc;
1283     // If the second operand is an immediate, this is a
1284     // register-indirect address.
1285     if (!MI->getOperand(1).isImm())
1286       MLoc.set(MI->getOperand(0).getReg());
1287     else
1288       MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1289     return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1290   }
1291   if (MI->getOperand(0).isImm())
1292     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1293   if (MI->getOperand(0).isFPImm())
1294     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1295   if (MI->getOperand(0).isCImm())
1296     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1297
1298   llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1299 }
1300
1301 // Find variables for each lexical scope.
1302 void
1303 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1304
1305   // Grab the variable info that was squirreled away in the MMI side-table.
1306   collectVariableInfoFromMMITable(Processed);
1307
1308   for (SmallVectorImpl<const MDNode *>::const_iterator
1309            UVI = UserVariables.begin(),
1310            UVE = UserVariables.end();
1311        UVI != UVE; ++UVI) {
1312     const MDNode *Var = *UVI;
1313     if (Processed.count(Var))
1314       continue;
1315
1316     // History contains relevant DBG_VALUE instructions for Var and instructions
1317     // clobbering it.
1318     SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1319     if (History.empty())
1320       continue;
1321     const MachineInstr *MInsn = History.front();
1322
1323     DIVariable DV(Var);
1324     LexicalScope *Scope = NULL;
1325     if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1326         DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1327       Scope = LScopes.getCurrentFunctionScope();
1328     else if (MDNode *IA = DV.getInlinedAt())
1329       Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1330     else
1331       Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1332     // If variable scope is not found then skip this variable.
1333     if (!Scope)
1334       continue;
1335
1336     Processed.insert(DV);
1337     assert(MInsn->isDebugValue() && "History must begin with debug value");
1338     DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1339     DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1340     if (!addCurrentFnArgument(RegVar, Scope))
1341       addScopeVariable(Scope, RegVar);
1342     if (AbsVar)
1343       AbsVar->setMInsn(MInsn);
1344
1345     // Simplify ranges that are fully coalesced.
1346     if (History.size() <= 1 ||
1347         (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1348       RegVar->setMInsn(MInsn);
1349       continue;
1350     }
1351
1352     // Handle multiple DBG_VALUE instructions describing one variable.
1353     RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1354
1355     for (SmallVectorImpl<const MachineInstr *>::const_iterator
1356              HI = History.begin(),
1357              HE = History.end();
1358          HI != HE; ++HI) {
1359       const MachineInstr *Begin = *HI;
1360       assert(Begin->isDebugValue() && "Invalid History entry");
1361
1362       // Check if DBG_VALUE is truncating a range.
1363       if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1364           !Begin->getOperand(0).getReg())
1365         continue;
1366
1367       // Compute the range for a register location.
1368       const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1369       const MCSymbol *SLabel = 0;
1370
1371       if (HI + 1 == HE)
1372         // If Begin is the last instruction in History then its value is valid
1373         // until the end of the function.
1374         SLabel = FunctionEndSym;
1375       else {
1376         const MachineInstr *End = HI[1];
1377         DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1378                      << "\t" << *Begin << "\t" << *End << "\n");
1379         if (End->isDebugValue())
1380           SLabel = getLabelBeforeInsn(End);
1381         else {
1382           // End is a normal instruction clobbering the range.
1383           SLabel = getLabelAfterInsn(End);
1384           assert(SLabel && "Forgot label after clobber instruction");
1385           ++HI;
1386         }
1387       }
1388
1389       // The value is valid until the next DBG_VALUE or clobber.
1390       DotDebugLocEntries.push_back(
1391           getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1392     }
1393     DotDebugLocEntries.push_back(DotDebugLocEntry());
1394   }
1395
1396   // Collect info for variables that were optimized out.
1397   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1398   DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1399   for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1400     DIVariable DV(Variables.getElement(i));
1401     if (!DV || !DV.isVariable() || !Processed.insert(DV))
1402       continue;
1403     if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1404       addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1405   }
1406 }
1407
1408 // Return Label preceding the instruction.
1409 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1410   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1411   assert(Label && "Didn't insert label before instruction");
1412   return Label;
1413 }
1414
1415 // Return Label immediately following the instruction.
1416 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1417   return LabelsAfterInsn.lookup(MI);
1418 }
1419
1420 // Process beginning of an instruction.
1421 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1422   assert(CurMI == 0);
1423   CurMI = MI;
1424   // Check if source location changes, but ignore DBG_VALUE locations.
1425   if (!MI->isDebugValue()) {
1426     DebugLoc DL = MI->getDebugLoc();
1427     if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1428       unsigned Flags = 0;
1429       PrevInstLoc = DL;
1430       if (DL == PrologEndLoc) {
1431         Flags |= DWARF2_FLAG_PROLOGUE_END;
1432         PrologEndLoc = DebugLoc();
1433       }
1434       if (PrologEndLoc.isUnknown())
1435         Flags |= DWARF2_FLAG_IS_STMT;
1436
1437       if (!DL.isUnknown()) {
1438         const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1439         recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1440       } else
1441         recordSourceLine(0, 0, 0, 0);
1442     }
1443   }
1444
1445   // Insert labels where requested.
1446   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1447       LabelsBeforeInsn.find(MI);
1448
1449   // No label needed.
1450   if (I == LabelsBeforeInsn.end())
1451     return;
1452
1453   // Label already assigned.
1454   if (I->second)
1455     return;
1456
1457   if (!PrevLabel) {
1458     PrevLabel = MMI->getContext().CreateTempSymbol();
1459     Asm->OutStreamer.EmitLabel(PrevLabel);
1460   }
1461   I->second = PrevLabel;
1462 }
1463
1464 // Process end of an instruction.
1465 void DwarfDebug::endInstruction() {
1466   assert(CurMI != 0);
1467   // Don't create a new label after DBG_VALUE instructions.
1468   // They don't generate code.
1469   if (!CurMI->isDebugValue())
1470     PrevLabel = 0;
1471
1472   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1473       LabelsAfterInsn.find(CurMI);
1474   CurMI = 0;
1475
1476   // No label needed.
1477   if (I == LabelsAfterInsn.end())
1478     return;
1479
1480   // Label already assigned.
1481   if (I->second)
1482     return;
1483
1484   // We need a label after this instruction.
1485   if (!PrevLabel) {
1486     PrevLabel = MMI->getContext().CreateTempSymbol();
1487     Asm->OutStreamer.EmitLabel(PrevLabel);
1488   }
1489   I->second = PrevLabel;
1490 }
1491
1492 // Each LexicalScope has first instruction and last instruction to mark
1493 // beginning and end of a scope respectively. Create an inverse map that list
1494 // scopes starts (and ends) with an instruction. One instruction may start (or
1495 // end) multiple scopes. Ignore scopes that are not reachable.
1496 void DwarfDebug::identifyScopeMarkers() {
1497   SmallVector<LexicalScope *, 4> WorkList;
1498   WorkList.push_back(LScopes.getCurrentFunctionScope());
1499   while (!WorkList.empty()) {
1500     LexicalScope *S = WorkList.pop_back_val();
1501
1502     const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1503     if (!Children.empty())
1504       for (SmallVectorImpl<LexicalScope *>::const_iterator
1505                SI = Children.begin(),
1506                SE = Children.end();
1507            SI != SE; ++SI)
1508         WorkList.push_back(*SI);
1509
1510     if (S->isAbstractScope())
1511       continue;
1512
1513     const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1514     if (Ranges.empty())
1515       continue;
1516     for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1517                                                     RE = Ranges.end();
1518          RI != RE; ++RI) {
1519       assert(RI->first && "InsnRange does not have first instruction!");
1520       assert(RI->second && "InsnRange does not have second instruction!");
1521       requestLabelBeforeInsn(RI->first);
1522       requestLabelAfterInsn(RI->second);
1523     }
1524   }
1525 }
1526
1527 // Get MDNode for DebugLoc's scope.
1528 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1529   if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1530     return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1531   return DL.getScope(Ctx);
1532 }
1533
1534 // Walk up the scope chain of given debug loc and find line number info
1535 // for the function.
1536 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1537   const MDNode *Scope = getScopeNode(DL, Ctx);
1538   DISubprogram SP = getDISubprogram(Scope);
1539   if (SP.isSubprogram()) {
1540     // Check for number of operands since the compatibility is
1541     // cheap here.
1542     if (SP->getNumOperands() > 19)
1543       return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1544     else
1545       return DebugLoc::get(SP.getLineNumber(), 0, SP);
1546   }
1547
1548   return DebugLoc();
1549 }
1550
1551 // Gather pre-function debug information.  Assumes being called immediately
1552 // after the function entry point has been emitted.
1553 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1554   CurFn = MF;
1555
1556   // If there's no debug info for the function we're not going to do anything.
1557   if (!MMI->hasDebugInfo())
1558     return;
1559
1560   // Grab the lexical scopes for the function, if we don't have any of those
1561   // then we're not going to be able to do anything.
1562   LScopes.initialize(*MF);
1563   if (LScopes.empty())
1564     return;
1565
1566   assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1567
1568   // Make sure that each lexical scope will have a begin/end label.
1569   identifyScopeMarkers();
1570
1571   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1572   // belongs to so that we add to the correct per-cu line table in the
1573   // non-asm case.
1574   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1575   DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1576   assert(TheCU && "Unable to find compile unit!");
1577   if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
1578     // Use a single line table if we are using .loc and generating assembly.
1579     Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1580   else
1581     Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1582
1583   // Emit a label for the function so that we have a beginning address.
1584   FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1585   // Assumes in correct section after the entry point.
1586   Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1587
1588   const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1589   // LiveUserVar - Map physreg numbers to the MDNode they contain.
1590   std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1591
1592   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1593        ++I) {
1594     bool AtBlockEntry = true;
1595     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1596          II != IE; ++II) {
1597       const MachineInstr *MI = II;
1598
1599       if (MI->isDebugValue()) {
1600         assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1601
1602         // Keep track of user variables.
1603         const MDNode *Var =
1604             MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1605
1606         // Variable is in a register, we need to check for clobbers.
1607         if (isDbgValueInDefinedReg(MI))
1608           LiveUserVar[MI->getOperand(0).getReg()] = Var;
1609
1610         // Check the history of this variable.
1611         SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1612         if (History.empty()) {
1613           UserVariables.push_back(Var);
1614           // The first mention of a function argument gets the FunctionBeginSym
1615           // label, so arguments are visible when breaking at function entry.
1616           DIVariable DV(Var);
1617           if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1618               getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1619             LabelsBeforeInsn[MI] = FunctionBeginSym;
1620         } else {
1621           // We have seen this variable before. Try to coalesce DBG_VALUEs.
1622           const MachineInstr *Prev = History.back();
1623           if (Prev->isDebugValue()) {
1624             // Coalesce identical entries at the end of History.
1625             if (History.size() >= 2 &&
1626                 Prev->isIdenticalTo(History[History.size() - 2])) {
1627               DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1628                            << "\t" << *Prev << "\t"
1629                            << *History[History.size() - 2] << "\n");
1630               History.pop_back();
1631             }
1632
1633             // Terminate old register assignments that don't reach MI;
1634             MachineFunction::const_iterator PrevMBB = Prev->getParent();
1635             if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1636                 isDbgValueInDefinedReg(Prev)) {
1637               // Previous register assignment needs to terminate at the end of
1638               // its basic block.
1639               MachineBasicBlock::const_iterator LastMI =
1640                   PrevMBB->getLastNonDebugInstr();
1641               if (LastMI == PrevMBB->end()) {
1642                 // Drop DBG_VALUE for empty range.
1643                 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1644                              << "\t" << *Prev << "\n");
1645                 History.pop_back();
1646               } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1647                 // Terminate after LastMI.
1648                 History.push_back(LastMI);
1649             }
1650           }
1651         }
1652         History.push_back(MI);
1653       } else {
1654         // Not a DBG_VALUE instruction.
1655         if (!MI->isLabel())
1656           AtBlockEntry = false;
1657
1658         // First known non-DBG_VALUE and non-frame setup location marks
1659         // the beginning of the function body.
1660         if (!MI->getFlag(MachineInstr::FrameSetup) &&
1661             (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1662           PrologEndLoc = MI->getDebugLoc();
1663
1664         // Check if the instruction clobbers any registers with debug vars.
1665         for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1666                                               MOE = MI->operands_end();
1667              MOI != MOE; ++MOI) {
1668           if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1669             continue;
1670           for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1671                ++AI) {
1672             unsigned Reg = *AI;
1673             const MDNode *Var = LiveUserVar[Reg];
1674             if (!Var)
1675               continue;
1676             // Reg is now clobbered.
1677             LiveUserVar[Reg] = 0;
1678
1679             // Was MD last defined by a DBG_VALUE referring to Reg?
1680             DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1681             if (HistI == DbgValues.end())
1682               continue;
1683             SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1684             if (History.empty())
1685               continue;
1686             const MachineInstr *Prev = History.back();
1687             // Sanity-check: Register assignments are terminated at the end of
1688             // their block.
1689             if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1690               continue;
1691             // Is the variable still in Reg?
1692             if (!isDbgValueInDefinedReg(Prev) ||
1693                 Prev->getOperand(0).getReg() != Reg)
1694               continue;
1695             // Var is clobbered. Make sure the next instruction gets a label.
1696             History.push_back(MI);
1697           }
1698         }
1699       }
1700     }
1701   }
1702
1703   for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1704        I != E; ++I) {
1705     SmallVectorImpl<const MachineInstr *> &History = I->second;
1706     if (History.empty())
1707       continue;
1708
1709     // Make sure the final register assignments are terminated.
1710     const MachineInstr *Prev = History.back();
1711     if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1712       const MachineBasicBlock *PrevMBB = Prev->getParent();
1713       MachineBasicBlock::const_iterator LastMI =
1714           PrevMBB->getLastNonDebugInstr();
1715       if (LastMI == PrevMBB->end())
1716         // Drop DBG_VALUE for empty range.
1717         History.pop_back();
1718       else if (PrevMBB != &PrevMBB->getParent()->back()) {
1719         // Terminate after LastMI.
1720         History.push_back(LastMI);
1721       }
1722     }
1723     // Request labels for the full history.
1724     for (unsigned i = 0, e = History.size(); i != e; ++i) {
1725       const MachineInstr *MI = History[i];
1726       if (MI->isDebugValue())
1727         requestLabelBeforeInsn(MI);
1728       else
1729         requestLabelAfterInsn(MI);
1730     }
1731   }
1732
1733   PrevInstLoc = DebugLoc();
1734   PrevLabel = FunctionBeginSym;
1735
1736   // Record beginning of function.
1737   if (!PrologEndLoc.isUnknown()) {
1738     DebugLoc FnStartDL =
1739         getFnDebugLoc(PrologEndLoc, MF->getFunction()->getContext());
1740     recordSourceLine(
1741         FnStartDL.getLine(), FnStartDL.getCol(),
1742         FnStartDL.getScope(MF->getFunction()->getContext()),
1743         // We'd like to list the prologue as "not statements" but GDB behaves
1744         // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1745         DWARF2_FLAG_IS_STMT);
1746   }
1747 }
1748
1749 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1750   SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1751   DIVariable DV = Var->getVariable();
1752   // Variables with positive arg numbers are parameters.
1753   if (unsigned ArgNum = DV.getArgNumber()) {
1754     // Keep all parameters in order at the start of the variable list to ensure
1755     // function types are correct (no out-of-order parameters)
1756     //
1757     // This could be improved by only doing it for optimized builds (unoptimized
1758     // builds have the right order to begin with), searching from the back (this
1759     // would catch the unoptimized case quickly), or doing a binary search
1760     // rather than linear search.
1761     SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1762     while (I != Vars.end()) {
1763       unsigned CurNum = (*I)->getVariable().getArgNumber();
1764       // A local (non-parameter) variable has been found, insert immediately
1765       // before it.
1766       if (CurNum == 0)
1767         break;
1768       // A later indexed parameter has been found, insert immediately before it.
1769       if (CurNum > ArgNum)
1770         break;
1771       ++I;
1772     }
1773     Vars.insert(I, Var);
1774     return;
1775   }
1776
1777   Vars.push_back(Var);
1778 }
1779
1780 // Gather and emit post-function debug information.
1781 void DwarfDebug::endFunction(const MachineFunction *MF) {
1782   // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1783   // though the beginFunction may not be called at all.
1784   // We should handle both cases.
1785   if (CurFn == 0)
1786     CurFn = MF;
1787   else
1788     assert(CurFn == MF);
1789   assert(CurFn != 0);
1790
1791   if (!MMI->hasDebugInfo() || LScopes.empty()) {
1792     CurFn = 0;
1793     return;
1794   }
1795
1796   // Define end label for subprogram.
1797   FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1798   // Assumes in correct section after the entry point.
1799   Asm->OutStreamer.EmitLabel(FunctionEndSym);
1800   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1801   Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1802
1803   SmallPtrSet<const MDNode *, 16> ProcessedVars;
1804   collectVariableInfo(ProcessedVars);
1805
1806   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1807   DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1808   assert(TheCU && "Unable to find compile unit!");
1809
1810   // Construct abstract scopes.
1811   ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1812   for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1813     LexicalScope *AScope = AList[i];
1814     DISubprogram SP(AScope->getScopeNode());
1815     if (SP.isSubprogram()) {
1816       // Collect info for variables that were optimized out.
1817       DIArray Variables = SP.getVariables();
1818       for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1819         DIVariable DV(Variables.getElement(i));
1820         if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1821           continue;
1822         // Check that DbgVariable for DV wasn't created earlier, when
1823         // findAbstractVariable() was called for inlined instance of DV.
1824         LLVMContext &Ctx = DV->getContext();
1825         DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1826         if (AbstractVariables.lookup(CleanDV))
1827           continue;
1828         if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1829           addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1830       }
1831     }
1832     if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1833       constructScopeDIE(TheCU, AScope);
1834   }
1835
1836   DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1837
1838   if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1839     TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1840
1841   // Clear debug info
1842   for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1843                                    E = ScopeVariables.end();
1844        I != E; ++I)
1845     DeleteContainerPointers(I->second);
1846   ScopeVariables.clear();
1847   DeleteContainerPointers(CurrentFnArguments);
1848   UserVariables.clear();
1849   DbgValues.clear();
1850   AbstractVariables.clear();
1851   LabelsBeforeInsn.clear();
1852   LabelsAfterInsn.clear();
1853   PrevLabel = NULL;
1854   CurFn = 0;
1855 }
1856
1857 // Register a source line with debug info. Returns the  unique label that was
1858 // emitted and which provides correspondence to the source line list.
1859 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1860                                   unsigned Flags) {
1861   StringRef Fn;
1862   StringRef Dir;
1863   unsigned Src = 1;
1864   if (S) {
1865     DIDescriptor Scope(S);
1866
1867     if (Scope.isCompileUnit()) {
1868       DICompileUnit CU(S);
1869       Fn = CU.getFilename();
1870       Dir = CU.getDirectory();
1871     } else if (Scope.isFile()) {
1872       DIFile F(S);
1873       Fn = F.getFilename();
1874       Dir = F.getDirectory();
1875     } else if (Scope.isSubprogram()) {
1876       DISubprogram SP(S);
1877       Fn = SP.getFilename();
1878       Dir = SP.getDirectory();
1879     } else if (Scope.isLexicalBlockFile()) {
1880       DILexicalBlockFile DBF(S);
1881       Fn = DBF.getFilename();
1882       Dir = DBF.getDirectory();
1883     } else if (Scope.isLexicalBlock()) {
1884       DILexicalBlock DB(S);
1885       Fn = DB.getFilename();
1886       Dir = DB.getDirectory();
1887     } else
1888       llvm_unreachable("Unexpected scope info");
1889
1890     Src = getOrCreateSourceID(
1891         Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1892   }
1893   Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1894 }
1895
1896 //===----------------------------------------------------------------------===//
1897 // Emit Methods
1898 //===----------------------------------------------------------------------===//
1899
1900 // Compute the size and offset of a DIE. The offset is relative to start of the
1901 // CU. It returns the offset after laying out the DIE.
1902 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1903   // Get the children.
1904   const std::vector<DIE *> &Children = Die->getChildren();
1905
1906   // Record the abbreviation.
1907   assignAbbrevNumber(Die->getAbbrev());
1908
1909   // Get the abbreviation for this DIE.
1910   const DIEAbbrev &Abbrev = Die->getAbbrev();
1911
1912   // Set DIE offset
1913   Die->setOffset(Offset);
1914
1915   // Start the size with the size of abbreviation code.
1916   Offset += MCAsmInfo::getULEB128Size(Die->getAbbrevNumber());
1917
1918   const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1919   const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1920
1921   // Size the DIE attribute values.
1922   for (unsigned i = 0, N = Values.size(); i < N; ++i)
1923     // Size attribute value.
1924     Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1925
1926   // Size the DIE children if any.
1927   if (!Children.empty()) {
1928     assert(Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1929            "Children flag not set");
1930
1931     for (unsigned j = 0, M = Children.size(); j < M; ++j)
1932       Offset = computeSizeAndOffset(Children[j], Offset);
1933
1934     // End of children marker.
1935     Offset += sizeof(int8_t);
1936   }
1937
1938   Die->setSize(Offset - Die->getOffset());
1939   return Offset;
1940 }
1941
1942 // Compute the size and offset for each DIE.
1943 void DwarfFile::computeSizeAndOffsets() {
1944   // Offset from the first CU in the debug info section is 0 initially.
1945   unsigned SecOffset = 0;
1946
1947   // Iterate over each compile unit and set the size and offsets for each
1948   // DIE within each compile unit. All offsets are CU relative.
1949   for (SmallVectorImpl<DwarfUnit *>::const_iterator I = CUs.begin(),
1950                                                     E = CUs.end();
1951        I != E; ++I) {
1952     (*I)->setDebugInfoOffset(SecOffset);
1953
1954     // CU-relative offset is reset to 0 here.
1955     unsigned Offset = sizeof(int32_t) +      // Length of Unit Info
1956                       (*I)->getHeaderSize(); // Unit-specific headers
1957
1958     // EndOffset here is CU-relative, after laying out
1959     // all of the CU DIE.
1960     unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1961     SecOffset += EndOffset;
1962   }
1963 }
1964
1965 // Emit initial Dwarf sections with a label at the start of each one.
1966 void DwarfDebug::emitSectionLabels() {
1967   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1968
1969   // Dwarf sections base addresses.
1970   DwarfInfoSectionSym =
1971       emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1972   if (useSplitDwarf())
1973     DwarfInfoDWOSectionSym =
1974         emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1975   DwarfAbbrevSectionSym =
1976       emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1977   if (useSplitDwarf())
1978     DwarfAbbrevDWOSectionSym = emitSectionSym(
1979         Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1980   emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1981
1982   if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1983     emitSectionSym(Asm, MacroInfo);
1984
1985   DwarfLineSectionSym =
1986       emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1987   emitSectionSym(Asm, TLOF.getDwarfLocSection());
1988   if (GenerateGnuPubSections) {
1989     DwarfGnuPubNamesSectionSym =
1990         emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1991     DwarfGnuPubTypesSectionSym =
1992         emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1993   } else if (HasDwarfPubSections) {
1994     emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1995     emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1996   }
1997
1998   DwarfStrSectionSym =
1999       emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
2000   if (useSplitDwarf()) {
2001     DwarfStrDWOSectionSym =
2002         emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
2003     DwarfAddrSectionSym =
2004         emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2005   }
2006   DwarfDebugRangeSectionSym =
2007       emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
2008
2009   DwarfDebugLocSectionSym =
2010       emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
2011 }
2012
2013 // Recursively emits a debug information entry.
2014 void DwarfDebug::emitDIE(DIE *Die) {
2015   // Get the abbreviation for this DIE.
2016   const DIEAbbrev &Abbrev = Die->getAbbrev();
2017
2018   // Emit the code (index) for the abbreviation.
2019   if (Asm->isVerbose())
2020     Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
2021                                 "] 0x" + Twine::utohexstr(Die->getOffset()) +
2022                                 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
2023                                 dwarf::TagString(Abbrev.getTag()));
2024   Asm->EmitULEB128(Abbrev.getNumber());
2025
2026   const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
2027   const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
2028
2029   // Emit the DIE attribute values.
2030   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2031     dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2032     dwarf::Form Form = AbbrevData[i].getForm();
2033     assert(Form && "Too many attributes for DIE (check abbreviation)");
2034
2035     if (Asm->isVerbose())
2036       Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2037
2038     switch (Attr) {
2039     case dwarf::DW_AT_abstract_origin:
2040     case dwarf::DW_AT_type:
2041     case dwarf::DW_AT_friend:
2042     case dwarf::DW_AT_specification:
2043     case dwarf::DW_AT_import:
2044     case dwarf::DW_AT_containing_type: {
2045       DIEEntry *E = cast<DIEEntry>(Values[i]);
2046       DIE *Origin = E->getEntry();
2047       unsigned Addr = Origin->getOffset();
2048       if (Form == dwarf::DW_FORM_ref_addr) {
2049         assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2050         // For DW_FORM_ref_addr, output the offset from beginning of debug info
2051         // section. Origin->getOffset() returns the offset from start of the
2052         // compile unit.
2053         DwarfCompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2054         assert(CU && "CUDie should belong to a CU.");
2055         Addr += CU->getDebugInfoOffset();
2056         if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2057           Asm->EmitLabelPlusOffset(CU->getSectionSym(), Addr,
2058                                    DIEEntry::getRefAddrSize(Asm));
2059         else
2060           Asm->EmitLabelOffsetDifference(CU->getSectionSym(), Addr,
2061                                          CU->getSectionSym(),
2062                                          DIEEntry::getRefAddrSize(Asm));
2063       } else {
2064         // Make sure Origin belong to the same CU.
2065         assert(Die->getUnit() == Origin->getUnit() &&
2066                "The referenced DIE should belong to the same CU in ref4");
2067         Asm->EmitInt32(Addr);
2068       }
2069       break;
2070     }
2071     case dwarf::DW_AT_location: {
2072       if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2073         if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2074           Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2075         else
2076           Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2077       } else {
2078         Values[i]->EmitValue(Asm, Form);
2079       }
2080       break;
2081     }
2082     case dwarf::DW_AT_accessibility: {
2083       if (Asm->isVerbose()) {
2084         DIEInteger *V = cast<DIEInteger>(Values[i]);
2085         Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2086       }
2087       Values[i]->EmitValue(Asm, Form);
2088       break;
2089     }
2090     default:
2091       // Emit an attribute using the defined form.
2092       Values[i]->EmitValue(Asm, Form);
2093       break;
2094     }
2095   }
2096
2097   // Emit the DIE children if any.
2098   if (Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2099     const std::vector<DIE *> &Children = Die->getChildren();
2100
2101     for (unsigned j = 0, M = Children.size(); j < M; ++j)
2102       emitDIE(Children[j]);
2103
2104     Asm->OutStreamer.AddComment("End Of Children Mark");
2105     Asm->EmitInt8(0);
2106   }
2107 }
2108
2109 // Emit the various dwarf units to the unit section USection with
2110 // the abbreviations going into ASection.
2111 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2112                           const MCSymbol *ASectionSym) {
2113   for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
2114        I != E; ++I) {
2115     DwarfUnit *TheU = *I;
2116     DIE *Die = TheU->getUnitDie();
2117     const MCSection *USection = TheU->getSection();
2118     Asm->OutStreamer.SwitchSection(USection);
2119
2120     // Emit the compile units header.
2121     Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
2122
2123     // Emit size of content not including length itself
2124     Asm->OutStreamer.AddComment("Length of Unit");
2125     Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2126
2127     TheU->emitHeader(ASection, ASectionSym);
2128
2129     DD->emitDIE(Die);
2130     Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
2131   }
2132 }
2133
2134 // Emit the debug info section.
2135 void DwarfDebug::emitDebugInfo() {
2136   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2137
2138   Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
2139                    DwarfAbbrevSectionSym);
2140 }
2141
2142 // Emit the abbreviation section.
2143 void DwarfDebug::emitAbbreviations() {
2144   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2145
2146   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2147 }
2148
2149 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2150   // Check to see if it is worth the effort.
2151   if (!Abbreviations.empty()) {
2152     // Start the debug abbrev section.
2153     Asm->OutStreamer.SwitchSection(Section);
2154
2155     // For each abbrevation.
2156     for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2157       // Get abbreviation data
2158       const DIEAbbrev *Abbrev = Abbreviations[i];
2159
2160       // Emit the abbrevations code (base 1 index.)
2161       Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2162
2163       // Emit the abbreviations data.
2164       Abbrev->Emit(Asm);
2165     }
2166
2167     // Mark end of abbreviations.
2168     Asm->EmitULEB128(0, "EOM(3)");
2169   }
2170 }
2171
2172 // Emit the last address of the section and the end of the line matrix.
2173 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2174   // Define last address of section.
2175   Asm->OutStreamer.AddComment("Extended Op");
2176   Asm->EmitInt8(0);
2177
2178   Asm->OutStreamer.AddComment("Op size");
2179   Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2180   Asm->OutStreamer.AddComment("DW_LNE_set_address");
2181   Asm->EmitInt8(dwarf::DW_LNE_set_address);
2182
2183   Asm->OutStreamer.AddComment("Section end label");
2184
2185   Asm->OutStreamer.EmitSymbolValue(
2186       Asm->GetTempSymbol("section_end", SectionEnd),
2187       Asm->getDataLayout().getPointerSize());
2188
2189   // Mark end of matrix.
2190   Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2191   Asm->EmitInt8(0);
2192   Asm->EmitInt8(1);
2193   Asm->EmitInt8(1);
2194 }
2195
2196 // Emit visible names into a hashed accelerator table section.
2197 void DwarfDebug::emitAccelNames() {
2198   DwarfAccelTable AT(
2199       DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2200   for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2201                                                     E = getUnits().end();
2202        I != E; ++I) {
2203     DwarfUnit *TheU = *I;
2204     const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2205     for (StringMap<std::vector<const DIE *> >::const_iterator
2206              GI = Names.begin(),
2207              GE = Names.end();
2208          GI != GE; ++GI) {
2209       StringRef Name = GI->getKey();
2210       const std::vector<const DIE *> &Entities = GI->second;
2211       for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2212                                                     DE = Entities.end();
2213            DI != DE; ++DI)
2214         AT.AddName(Name, *DI);
2215     }
2216   }
2217
2218   AT.FinalizeTable(Asm, "Names");
2219   Asm->OutStreamer.SwitchSection(
2220       Asm->getObjFileLowering().getDwarfAccelNamesSection());
2221   MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2222   Asm->OutStreamer.EmitLabel(SectionBegin);
2223
2224   // Emit the full data.
2225   AT.Emit(Asm, SectionBegin, &InfoHolder);
2226 }
2227
2228 // Emit objective C classes and categories into a hashed accelerator table
2229 // section.
2230 void DwarfDebug::emitAccelObjC() {
2231   DwarfAccelTable AT(
2232       DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2233   for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2234                                                     E = getUnits().end();
2235        I != E; ++I) {
2236     DwarfUnit *TheU = *I;
2237     const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2238     for (StringMap<std::vector<const DIE *> >::const_iterator
2239              GI = Names.begin(),
2240              GE = Names.end();
2241          GI != GE; ++GI) {
2242       StringRef Name = GI->getKey();
2243       const std::vector<const DIE *> &Entities = GI->second;
2244       for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2245                                                     DE = Entities.end();
2246            DI != DE; ++DI)
2247         AT.AddName(Name, *DI);
2248     }
2249   }
2250
2251   AT.FinalizeTable(Asm, "ObjC");
2252   Asm->OutStreamer.SwitchSection(
2253       Asm->getObjFileLowering().getDwarfAccelObjCSection());
2254   MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2255   Asm->OutStreamer.EmitLabel(SectionBegin);
2256
2257   // Emit the full data.
2258   AT.Emit(Asm, SectionBegin, &InfoHolder);
2259 }
2260
2261 // Emit namespace dies into a hashed accelerator table.
2262 void DwarfDebug::emitAccelNamespaces() {
2263   DwarfAccelTable AT(
2264       DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2265   for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2266                                                     E = getUnits().end();
2267        I != E; ++I) {
2268     DwarfUnit *TheU = *I;
2269     const StringMap<std::vector<const DIE *> > &Names =
2270         TheU->getAccelNamespace();
2271     for (StringMap<std::vector<const DIE *> >::const_iterator
2272              GI = Names.begin(),
2273              GE = Names.end();
2274          GI != GE; ++GI) {
2275       StringRef Name = GI->getKey();
2276       const std::vector<const DIE *> &Entities = GI->second;
2277       for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2278                                                     DE = Entities.end();
2279            DI != DE; ++DI)
2280         AT.AddName(Name, *DI);
2281     }
2282   }
2283
2284   AT.FinalizeTable(Asm, "namespac");
2285   Asm->OutStreamer.SwitchSection(
2286       Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2287   MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2288   Asm->OutStreamer.EmitLabel(SectionBegin);
2289
2290   // Emit the full data.
2291   AT.Emit(Asm, SectionBegin, &InfoHolder);
2292 }
2293
2294 // Emit type dies into a hashed accelerator table.
2295 void DwarfDebug::emitAccelTypes() {
2296   std::vector<DwarfAccelTable::Atom> Atoms;
2297   Atoms.push_back(
2298       DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2299   Atoms.push_back(
2300       DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2301   Atoms.push_back(
2302       DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2303   DwarfAccelTable AT(Atoms);
2304   for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2305                                                     E = getUnits().end();
2306        I != E; ++I) {
2307     DwarfUnit *TheU = *I;
2308     const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2309         TheU->getAccelTypes();
2310     for (StringMap<
2311              std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2312              GI = Names.begin(),
2313              GE = Names.end();
2314          GI != GE; ++GI) {
2315       StringRef Name = GI->getKey();
2316       const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2317           GI->second;
2318       for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2319                DI = Entities.begin(),
2320                DE = Entities.end();
2321            DI != DE; ++DI)
2322         AT.AddName(Name, DI->first, DI->second);
2323     }
2324   }
2325
2326   AT.FinalizeTable(Asm, "types");
2327   Asm->OutStreamer.SwitchSection(
2328       Asm->getObjFileLowering().getDwarfAccelTypesSection());
2329   MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2330   Asm->OutStreamer.EmitLabel(SectionBegin);
2331
2332   // Emit the full data.
2333   AT.Emit(Asm, SectionBegin, &InfoHolder);
2334 }
2335
2336 // Public name handling.
2337 // The format for the various pubnames:
2338 //
2339 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2340 // for the DIE that is named.
2341 //
2342 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2343 // into the CU and the index value is computed according to the type of value
2344 // for the DIE that is named.
2345 //
2346 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2347 // it's the offset within the debug_info/debug_types dwo section, however, the
2348 // reference in the pubname header doesn't change.
2349
2350 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2351 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2352                                                         const DIE *Die) {
2353   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2354
2355   // We could have a specification DIE that has our most of our knowledge,
2356   // look for that now.
2357   DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2358   if (SpecVal) {
2359     DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2360     if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2361       Linkage = dwarf::GIEL_EXTERNAL;
2362   } else if (Die->findAttribute(dwarf::DW_AT_external))
2363     Linkage = dwarf::GIEL_EXTERNAL;
2364
2365   switch (Die->getTag()) {
2366   case dwarf::DW_TAG_class_type:
2367   case dwarf::DW_TAG_structure_type:
2368   case dwarf::DW_TAG_union_type:
2369   case dwarf::DW_TAG_enumeration_type:
2370     return dwarf::PubIndexEntryDescriptor(
2371         dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2372                               ? dwarf::GIEL_STATIC
2373                               : dwarf::GIEL_EXTERNAL);
2374   case dwarf::DW_TAG_typedef:
2375   case dwarf::DW_TAG_base_type:
2376   case dwarf::DW_TAG_subrange_type:
2377     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2378   case dwarf::DW_TAG_namespace:
2379     return dwarf::GIEK_TYPE;
2380   case dwarf::DW_TAG_subprogram:
2381     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2382   case dwarf::DW_TAG_constant:
2383   case dwarf::DW_TAG_variable:
2384     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2385   case dwarf::DW_TAG_enumerator:
2386     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2387                                           dwarf::GIEL_STATIC);
2388   default:
2389     return dwarf::GIEK_NONE;
2390   }
2391 }
2392
2393 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2394 ///
2395 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2396   const MCSection *PSec =
2397       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2398                : Asm->getObjFileLowering().getDwarfPubNamesSection();
2399
2400   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2401   const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2402   for (unsigned i = 0; i != Units.size(); ++i) {
2403     DwarfUnit *TheU = Units[i];
2404     unsigned ID = TheU->getUniqueID();
2405
2406     // Start the dwarf pubnames section.
2407     Asm->OutStreamer.SwitchSection(PSec);
2408
2409     // Emit a label so we can reference the beginning of this pubname section.
2410     if (GnuStyle)
2411       Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2412
2413     // Emit the header.
2414     Asm->OutStreamer.AddComment("Length of Public Names Info");
2415     MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2416     MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2417     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2418
2419     Asm->OutStreamer.EmitLabel(BeginLabel);
2420
2421     Asm->OutStreamer.AddComment("DWARF Version");
2422     Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2423
2424     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2425     Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2426
2427     Asm->OutStreamer.AddComment("Compilation Unit Length");
2428     Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2429
2430     // Emit the pubnames for this compilation unit.
2431     const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2432     for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2433                                                 GE = Globals.end();
2434          GI != GE; ++GI) {
2435       const char *Name = GI->getKeyData();
2436       const DIE *Entity = GI->second;
2437
2438       Asm->OutStreamer.AddComment("DIE offset");
2439       Asm->EmitInt32(Entity->getOffset());
2440
2441       if (GnuStyle) {
2442         dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2443         Asm->OutStreamer.AddComment(
2444             Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2445             dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2446         Asm->EmitInt8(Desc.toBits());
2447       }
2448
2449       Asm->OutStreamer.AddComment("External Name");
2450       Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2451     }
2452
2453     Asm->OutStreamer.AddComment("End Mark");
2454     Asm->EmitInt32(0);
2455     Asm->OutStreamer.EmitLabel(EndLabel);
2456   }
2457 }
2458
2459 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2460   const MCSection *PSec =
2461       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2462                : Asm->getObjFileLowering().getDwarfPubTypesSection();
2463
2464   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2465   const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2466   for (unsigned i = 0; i != Units.size(); ++i) {
2467     DwarfUnit *TheU = Units[i];
2468     unsigned ID = TheU->getUniqueID();
2469
2470     // Start the dwarf pubtypes section.
2471     Asm->OutStreamer.SwitchSection(PSec);
2472
2473     // Emit a label so we can reference the beginning of this pubtype section.
2474     if (GnuStyle)
2475       Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2476
2477     // Emit the header.
2478     Asm->OutStreamer.AddComment("Length of Public Types Info");
2479     MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2480     MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2481     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2482
2483     Asm->OutStreamer.EmitLabel(BeginLabel);
2484
2485     Asm->OutStreamer.AddComment("DWARF Version");
2486     Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2487
2488     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2489     Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2490
2491     Asm->OutStreamer.AddComment("Compilation Unit Length");
2492     Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2493
2494     // Emit the pubtypes.
2495     const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2496     for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2497                                                 GE = Globals.end();
2498          GI != GE; ++GI) {
2499       const char *Name = GI->getKeyData();
2500       const DIE *Entity = GI->second;
2501
2502       Asm->OutStreamer.AddComment("DIE offset");
2503       Asm->EmitInt32(Entity->getOffset());
2504
2505       if (GnuStyle) {
2506         dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2507         Asm->OutStreamer.AddComment(
2508             Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2509             dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2510         Asm->EmitInt8(Desc.toBits());
2511       }
2512
2513       Asm->OutStreamer.AddComment("External Name");
2514
2515       // Emit the name with a terminating null byte.
2516       Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2517     }
2518
2519     Asm->OutStreamer.AddComment("End Mark");
2520     Asm->EmitInt32(0);
2521     Asm->OutStreamer.EmitLabel(EndLabel);
2522   }
2523 }
2524
2525 // Emit strings into a string section.
2526 void DwarfFile::emitStrings(const MCSection *StrSection,
2527                             const MCSection *OffsetSection = NULL,
2528                             const MCSymbol *StrSecSym = NULL) {
2529
2530   if (StringPool.empty())
2531     return;
2532
2533   // Start the dwarf str section.
2534   Asm->OutStreamer.SwitchSection(StrSection);
2535
2536   // Get all of the string pool entries and put them in an array by their ID so
2537   // we can sort them.
2538   SmallVector<
2539       std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2540       64> Entries;
2541
2542   for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2543            I = StringPool.begin(),
2544            E = StringPool.end();
2545        I != E; ++I)
2546     Entries.push_back(std::make_pair(I->second.second, &*I));
2547
2548   array_pod_sort(Entries.begin(), Entries.end());
2549
2550   for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2551     // Emit a label for reference from debug information entries.
2552     Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2553
2554     // Emit the string itself with a terminating null byte.
2555     Asm->OutStreamer.EmitBytes(
2556         StringRef(Entries[i].second->getKeyData(),
2557                   Entries[i].second->getKeyLength() + 1));
2558   }
2559
2560   // If we've got an offset section go ahead and emit that now as well.
2561   if (OffsetSection) {
2562     Asm->OutStreamer.SwitchSection(OffsetSection);
2563     unsigned offset = 0;
2564     unsigned size = 4; // FIXME: DWARF64 is 8.
2565     for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2566       Asm->OutStreamer.EmitIntValue(offset, size);
2567       offset += Entries[i].second->getKeyLength() + 1;
2568     }
2569   }
2570 }
2571
2572 // Emit addresses into the section given.
2573 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2574
2575   if (AddressPool.empty())
2576     return;
2577
2578   // Start the dwarf addr section.
2579   Asm->OutStreamer.SwitchSection(AddrSection);
2580
2581   // Order the address pool entries by ID
2582   SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2583
2584   for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2585                                                     E = AddressPool.end();
2586        I != E; ++I)
2587     Entries[I->second] = I->first;
2588
2589   for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2590     // Emit an expression for reference from debug information entries.
2591     if (const MCExpr *Expr = Entries[i])
2592       Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2593     else
2594       Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2595   }
2596 }
2597
2598 // Emit visible names into a debug str section.
2599 void DwarfDebug::emitDebugStr() {
2600   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2601   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2602 }
2603
2604 // Emit locations into the debug loc section.
2605 void DwarfDebug::emitDebugLoc() {
2606   if (DotDebugLocEntries.empty())
2607     return;
2608
2609   for (SmallVectorImpl<DotDebugLocEntry>::iterator
2610            I = DotDebugLocEntries.begin(),
2611            E = DotDebugLocEntries.end();
2612        I != E; ++I) {
2613     DotDebugLocEntry &Entry = *I;
2614     if (I + 1 != DotDebugLocEntries.end())
2615       Entry.Merge(I + 1);
2616   }
2617
2618   // Start the dwarf loc section.
2619   Asm->OutStreamer.SwitchSection(
2620       Asm->getObjFileLowering().getDwarfLocSection());
2621   unsigned char Size = Asm->getDataLayout().getPointerSize();
2622   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2623   unsigned index = 1;
2624   for (SmallVectorImpl<DotDebugLocEntry>::iterator
2625            I = DotDebugLocEntries.begin(),
2626            E = DotDebugLocEntries.end();
2627        I != E; ++I, ++index) {
2628     DotDebugLocEntry &Entry = *I;
2629     if (Entry.isMerged())
2630       continue;
2631     if (Entry.isEmpty()) {
2632       Asm->OutStreamer.EmitIntValue(0, Size);
2633       Asm->OutStreamer.EmitIntValue(0, Size);
2634       Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2635     } else {
2636       Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2637       Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2638       DIVariable DV(Entry.getVariable());
2639       Asm->OutStreamer.AddComment("Loc expr size");
2640       MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2641       MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2642       Asm->EmitLabelDifference(end, begin, 2);
2643       Asm->OutStreamer.EmitLabel(begin);
2644       if (Entry.isInt()) {
2645         DIBasicType BTy(DV.getType());
2646         if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2647                              BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2648           Asm->OutStreamer.AddComment("DW_OP_consts");
2649           Asm->EmitInt8(dwarf::DW_OP_consts);
2650           Asm->EmitSLEB128(Entry.getInt());
2651         } else {
2652           Asm->OutStreamer.AddComment("DW_OP_constu");
2653           Asm->EmitInt8(dwarf::DW_OP_constu);
2654           Asm->EmitULEB128(Entry.getInt());
2655         }
2656       } else if (Entry.isLocation()) {
2657         MachineLocation Loc = Entry.getLoc();
2658         if (!DV.hasComplexAddress())
2659           // Regular entry.
2660           Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2661         else {
2662           // Complex address entry.
2663           unsigned N = DV.getNumAddrElements();
2664           unsigned i = 0;
2665           if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2666             if (Loc.getOffset()) {
2667               i = 2;
2668               Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2669               Asm->OutStreamer.AddComment("DW_OP_deref");
2670               Asm->EmitInt8(dwarf::DW_OP_deref);
2671               Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2672               Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2673               Asm->EmitSLEB128(DV.getAddrElement(1));
2674             } else {
2675               // If first address element is OpPlus then emit
2676               // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2677               MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2678               Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2679               i = 2;
2680             }
2681           } else {
2682             Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2683           }
2684
2685           // Emit remaining complex address elements.
2686           for (; i < N; ++i) {
2687             uint64_t Element = DV.getAddrElement(i);
2688             if (Element == DIBuilder::OpPlus) {
2689               Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2690               Asm->EmitULEB128(DV.getAddrElement(++i));
2691             } else if (Element == DIBuilder::OpDeref) {
2692               if (!Loc.isReg())
2693                 Asm->EmitInt8(dwarf::DW_OP_deref);
2694             } else
2695               llvm_unreachable("unknown Opcode found in complex address");
2696           }
2697         }
2698       }
2699       // else ... ignore constant fp. There is not any good way to
2700       // to represent them here in dwarf.
2701       Asm->OutStreamer.EmitLabel(end);
2702     }
2703   }
2704 }
2705
2706 struct SymbolCUSorter {
2707   SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2708   const MCStreamer &Streamer;
2709
2710   bool operator()(const SymbolCU &A, const SymbolCU &B) {
2711     unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2712     unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2713
2714     // Symbols with no order assigned should be placed at the end.
2715     // (e.g. section end labels)
2716     if (IA == 0)
2717       IA = (unsigned)(-1);
2718     if (IB == 0)
2719       IB = (unsigned)(-1);
2720     return IA < IB;
2721   }
2722 };
2723
2724 static bool CUSort(const DwarfUnit *A, const DwarfUnit *B) {
2725   return (A->getUniqueID() < B->getUniqueID());
2726 }
2727
2728 struct ArangeSpan {
2729   const MCSymbol *Start, *End;
2730 };
2731
2732 // Emit a debug aranges section, containing a CU lookup for any
2733 // address we can tie back to a CU.
2734 void DwarfDebug::emitDebugARanges() {
2735   // Start the dwarf aranges section.
2736   Asm->OutStreamer.SwitchSection(
2737       Asm->getObjFileLowering().getDwarfARangesSection());
2738
2739   typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2740
2741   SpansType Spans;
2742
2743   // Build a list of sections used.
2744   std::vector<const MCSection *> Sections;
2745   for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2746        it++) {
2747     const MCSection *Section = it->first;
2748     Sections.push_back(Section);
2749   }
2750
2751   // Sort the sections into order.
2752   // This is only done to ensure consistent output order across different runs.
2753   std::sort(Sections.begin(), Sections.end(), SectionSort);
2754
2755   // Build a set of address spans, sorted by CU.
2756   for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2757     const MCSection *Section = Sections[SecIdx];
2758     SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2759     if (List.size() < 2)
2760       continue;
2761
2762     // Sort the symbols by offset within the section.
2763     SymbolCUSorter sorter(Asm->OutStreamer);
2764     std::sort(List.begin(), List.end(), sorter);
2765
2766     // If we have no section (e.g. common), just write out
2767     // individual spans for each symbol.
2768     if (Section == NULL) {
2769       for (size_t n = 0; n < List.size(); n++) {
2770         const SymbolCU &Cur = List[n];
2771
2772         ArangeSpan Span;
2773         Span.Start = Cur.Sym;
2774         Span.End = NULL;
2775         if (Cur.CU)
2776           Spans[Cur.CU].push_back(Span);
2777       }
2778     } else {
2779       // Build spans between each label.
2780       const MCSymbol *StartSym = List[0].Sym;
2781       for (size_t n = 1; n < List.size(); n++) {
2782         const SymbolCU &Prev = List[n - 1];
2783         const SymbolCU &Cur = List[n];
2784
2785         // Try and build the longest span we can within the same CU.
2786         if (Cur.CU != Prev.CU) {
2787           ArangeSpan Span;
2788           Span.Start = StartSym;
2789           Span.End = Cur.Sym;
2790           Spans[Prev.CU].push_back(Span);
2791           StartSym = Cur.Sym;
2792         }
2793       }
2794     }
2795   }
2796
2797   unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2798
2799   // Build a list of CUs used.
2800   std::vector<DwarfCompileUnit *> CUs;
2801   for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2802     DwarfCompileUnit *CU = it->first;
2803     CUs.push_back(CU);
2804   }
2805
2806   // Sort the CU list (again, to ensure consistent output order).
2807   std::sort(CUs.begin(), CUs.end(), CUSort);
2808
2809   // Emit an arange table for each CU we used.
2810   for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2811     DwarfCompileUnit *CU = CUs[CUIdx];
2812     std::vector<ArangeSpan> &List = Spans[CU];
2813
2814     // Emit size of content not including length itself.
2815     unsigned ContentSize =
2816         sizeof(int16_t) + // DWARF ARange version number
2817         sizeof(int32_t) + // Offset of CU in the .debug_info section
2818         sizeof(int8_t) +  // Pointer Size (in bytes)
2819         sizeof(int8_t);   // Segment Size (in bytes)
2820
2821     unsigned TupleSize = PtrSize * 2;
2822
2823     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2824     unsigned Padding =
2825         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2826
2827     ContentSize += Padding;
2828     ContentSize += (List.size() + 1) * TupleSize;
2829
2830     // For each compile unit, write the list of spans it covers.
2831     Asm->OutStreamer.AddComment("Length of ARange Set");
2832     Asm->EmitInt32(ContentSize);
2833     Asm->OutStreamer.AddComment("DWARF Arange version number");
2834     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2835     Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2836     Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2837     Asm->OutStreamer.AddComment("Address Size (in bytes)");
2838     Asm->EmitInt8(PtrSize);
2839     Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2840     Asm->EmitInt8(0);
2841
2842     Asm->OutStreamer.EmitFill(Padding, 0xff);
2843
2844     for (unsigned n = 0; n < List.size(); n++) {
2845       const ArangeSpan &Span = List[n];
2846       Asm->EmitLabelReference(Span.Start, PtrSize);
2847
2848       // Calculate the size as being from the span start to it's end.
2849       if (Span.End) {
2850         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2851       } else {
2852         // For symbols without an end marker (e.g. common), we
2853         // write a single arange entry containing just that one symbol.
2854         uint64_t Size = SymSize[Span.Start];
2855         if (Size == 0)
2856           Size = 1;
2857
2858         Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2859       }
2860     }
2861
2862     Asm->OutStreamer.AddComment("ARange terminator");
2863     Asm->OutStreamer.EmitIntValue(0, PtrSize);
2864     Asm->OutStreamer.EmitIntValue(0, PtrSize);
2865   }
2866 }
2867
2868 // Emit visible names into a debug ranges section.
2869 void DwarfDebug::emitDebugRanges() {
2870   // Start the dwarf ranges section.
2871   Asm->OutStreamer.SwitchSection(
2872       Asm->getObjFileLowering().getDwarfRangesSection());
2873
2874   // Size for our labels.
2875   unsigned char Size = Asm->getDataLayout().getPointerSize();
2876
2877   // Grab the specific ranges for the compile units in the module.
2878   for (DenseMap<const MDNode *, DwarfCompileUnit *>::iterator I = CUMap.begin(),
2879                                                               E = CUMap.end();
2880        I != E; ++I) {
2881     DwarfCompileUnit *TheCU = I->second;
2882
2883     // Emit a symbol so we can find the beginning of our ranges.
2884     Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2885
2886     // Iterate over the misc ranges for the compile units in the module.
2887     const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2888     for (SmallVectorImpl<RangeSpanList>::const_iterator I = RangeLists.begin(),
2889                                                         E = RangeLists.end();
2890          I != E; ++I) {
2891       const RangeSpanList &List = *I;
2892
2893       // Emit our symbol so we can find the beginning of the range.
2894       Asm->OutStreamer.EmitLabel(List.getSym());
2895
2896       for (SmallVectorImpl<RangeSpan>::const_iterator
2897                RI = List.getRanges().begin(),
2898                RE = List.getRanges().end();
2899            RI != RE; ++RI) {
2900         const RangeSpan &Range = *RI;
2901         const MCSymbol *Begin = Range.getStart();
2902         const MCSymbol *End = Range.getEnd();
2903         assert(Begin && "Range without a begin symbol?");
2904         assert(End && "Range without an end symbol?");
2905         Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2906         Asm->OutStreamer.EmitSymbolValue(End, Size);
2907       }
2908
2909       // And terminate the list with two 0 values.
2910       Asm->OutStreamer.EmitIntValue(0, Size);
2911       Asm->OutStreamer.EmitIntValue(0, Size);
2912     }
2913
2914     // Now emit a range for the CU itself.
2915     if (useCURanges()) {
2916       Asm->OutStreamer.EmitLabel(
2917           Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2918       const SmallVectorImpl<RangeSpan> &Ranges = TheCU->getRanges();
2919       for (uint32_t i = 0, e = Ranges.size(); i != e; ++i) {
2920         RangeSpan Range = Ranges[i];
2921         const MCSymbol *Begin = Range.getStart();
2922         const MCSymbol *End = Range.getEnd();
2923         assert(Begin && "Range without a begin symbol?");
2924         assert(End && "Range without an end symbol?");
2925         Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2926         Asm->OutStreamer.EmitSymbolValue(End, Size);
2927       }
2928       // And terminate the list with two 0 values.
2929       Asm->OutStreamer.EmitIntValue(0, Size);
2930       Asm->OutStreamer.EmitIntValue(0, Size);
2931     }
2932   }
2933 }
2934
2935 // DWARF5 Experimental Separate Dwarf emitters.
2936
2937 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2938                                   DwarfUnit *NewU) {
2939   NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2940                        U->getCUNode().getSplitDebugFilename());
2941
2942   // Relocate to the beginning of the addr_base section, else 0 for the
2943   // beginning of the one for this compile unit.
2944   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2945     NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2946   else
2947     NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2948
2949   if (!CompilationDir.empty())
2950     NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2951
2952   addGnuPubAttributes(NewU, Die);
2953
2954   SkeletonHolder.addUnit(NewU);
2955 }
2956
2957 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2958 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2959 // DW_AT_ranges_base, DW_AT_addr_base.
2960 // TODO: Implement DW_AT_ranges_base.
2961 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2962
2963   DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2964   DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2965       CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2966   NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2967                      DwarfInfoSectionSym);
2968
2969   // DW_AT_stmt_list is a offset of line number information for this
2970   // compile unit in debug_line section.
2971   // FIXME: Should handle multiple compile units.
2972   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2973     NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list, DwarfLineSectionSym);
2974   else
2975     NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
2976
2977   initSkeletonUnit(CU, Die, NewCU);
2978
2979   return NewCU;
2980 }
2981
2982 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2983 // DW_AT_addr_base.
2984 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(const DwarfTypeUnit *TU) {
2985
2986   DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2987   DwarfTypeUnit *NewTU = new DwarfTypeUnit(
2988       TU->getUniqueID(), Die, TU->getCUNode(), Asm, this, &SkeletonHolder);
2989   NewTU->setTypeSignature(TU->getTypeSignature());
2990   NewTU->setType(NULL);
2991   NewTU->initSection(
2992       Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2993
2994   initSkeletonUnit(TU, Die, NewTU);
2995   return NewTU;
2996 }
2997
2998 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2999 // compile units that would normally be in debug_info.
3000 void DwarfDebug::emitDebugInfoDWO() {
3001   assert(useSplitDwarf() && "No split dwarf debug info?");
3002   InfoHolder.emitUnits(this,
3003                        Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3004                        DwarfAbbrevDWOSectionSym);
3005 }
3006
3007 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3008 // abbreviations for the .debug_info.dwo section.
3009 void DwarfDebug::emitDebugAbbrevDWO() {
3010   assert(useSplitDwarf() && "No split dwarf?");
3011   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
3012 }
3013
3014 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3015 // string section and is identical in format to traditional .debug_str
3016 // sections.
3017 void DwarfDebug::emitDebugStrDWO() {
3018   assert(useSplitDwarf() && "No split dwarf?");
3019   const MCSection *OffSec =
3020       Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3021   const MCSymbol *StrSym = DwarfStrSectionSym;
3022   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3023                          OffSec, StrSym);
3024 }
3025
3026 void DwarfDebug::addDwarfTypeUnitType(DICompileUnit CUNode,
3027                                       StringRef Identifier, DIE *RefDie,
3028                                       DICompositeType CTy) {
3029
3030   const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
3031   if (TU) {
3032     CUMap.begin()->second->addDIETypeSignature(RefDie, *TU);
3033     return;
3034   }
3035
3036   DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3037   DwarfTypeUnit *NewTU = new DwarfTypeUnit(
3038       InfoHolder.getUnits().size(), UnitDie, CUNode, Asm, this, &InfoHolder);
3039   TU = NewTU;
3040   InfoHolder.addUnit(NewTU);
3041
3042   NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3043                  CUNode.getLanguage());
3044
3045   MD5 Hash;
3046   Hash.update(Identifier);
3047   // ... take the least significant 8 bytes and return those. Our MD5
3048   // implementation always returns its results in little endian, swap bytes
3049   // appropriately.
3050   MD5::MD5Result Result;
3051   Hash.final(Result);
3052   uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
3053   NewTU->setTypeSignature(Signature);
3054   if (useSplitDwarf())
3055     NewTU->setSkeleton(constructSkeletonTU(NewTU));
3056
3057   NewTU->setType(NewTU->createTypeDIE(CTy));
3058
3059   NewTU->initSection(
3060       useSplitDwarf()
3061           ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
3062           : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
3063
3064   CUMap.begin()->second->addDIETypeSignature(RefDie, *NewTU);
3065 }