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