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