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