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