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