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