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