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