OSDN Git Service

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