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