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