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