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