Also add the linkage name to the name accelerator tables if it exists
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfDebug.cpp
1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "DwarfDebug.h"
16 #include "DIE.h"
17 #include "DwarfAccelTable.h"
18 #include "DwarfCompileUnit.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Module.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCSection.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetFrameLowering.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Analysis/DebugInfo.h"
35 #include "llvm/Analysis/DIBuilder.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/ValueHandle.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Support/Path.h"
46 using namespace llvm;
47
48 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
49                                               cl::Hidden,
50      cl::desc("Disable debug info printing"));
51
52 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
53      cl::desc("Make an absence of debug location information explicit."),
54      cl::init(false));
55
56 static cl::opt<bool> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
57      cl::desc("Output prototype dwarf accelerator tables."),
58      cl::init(false));
59
60 namespace {
61   const char *DWARFGroupName = "DWARF Emission";
62   const char *DbgTimerName = "DWARF Debug Writer";
63 } // end anonymous namespace
64
65 //===----------------------------------------------------------------------===//
66
67 /// Configuration values for initial hash set sizes (log2).
68 ///
69 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
70
71 namespace llvm {
72
73 DIType DbgVariable::getType() const {
74   DIType Ty = Var.getType();
75   // FIXME: isBlockByrefVariable should be reformulated in terms of complex
76   // addresses instead.
77   if (Var.isBlockByrefVariable()) {
78     /* Byref variables, in Blocks, are declared by the programmer as
79        "SomeType VarName;", but the compiler creates a
80        __Block_byref_x_VarName struct, and gives the variable VarName
81        either the struct, or a pointer to the struct, as its type.  This
82        is necessary for various behind-the-scenes things the compiler
83        needs to do with by-reference variables in blocks.
84        
85        However, as far as the original *programmer* is concerned, the
86        variable should still have type 'SomeType', as originally declared.
87        
88        The following function dives into the __Block_byref_x_VarName
89        struct to find the original type of the variable.  This will be
90        passed back to the code generating the type for the Debug
91        Information Entry for the variable 'VarName'.  'VarName' will then
92        have the original type 'SomeType' in its debug information.
93        
94        The original type 'SomeType' will be the type of the field named
95        'VarName' inside the __Block_byref_x_VarName struct.
96        
97        NOTE: In order for this to not completely fail on the debugger
98        side, the Debug Information Entry for the variable VarName needs to
99        have a DW_AT_location that tells the debugger how to unwind through
100        the pointers and __Block_byref_x_VarName struct to find the actual
101        value of the variable.  The function addBlockByrefType does this.  */
102     DIType subType = Ty;
103     unsigned tag = Ty.getTag();
104     
105     if (tag == dwarf::DW_TAG_pointer_type) {
106       DIDerivedType DTy = DIDerivedType(Ty);
107       subType = DTy.getTypeDerivedFrom();
108     }
109     
110     DICompositeType blockStruct = DICompositeType(subType);
111     DIArray Elements = blockStruct.getTypeArray();
112     
113     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
114       DIDescriptor Element = Elements.getElement(i);
115       DIDerivedType DT = DIDerivedType(Element);
116       if (getName() == DT.getName())
117         return (DT.getTypeDerivedFrom());
118     }
119     return Ty;
120   }
121   return Ty;
122 }
123
124 } // end llvm namespace
125
126 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
127   : Asm(A), MMI(Asm->MMI), FirstCU(0),
128     AbbreviationsSet(InitAbbreviationsSetSize),
129     PrevLabel(NULL) {
130   NextStringPoolNumber = 0;
131
132   DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
133   DwarfStrSectionSym = TextSectionSym = 0;
134   DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
135   FunctionBeginSym = FunctionEndSym = 0;
136   {
137     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
138     beginModule(M);
139   }
140 }
141 DwarfDebug::~DwarfDebug() {
142 }
143
144 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
145 /// temporary label to it if SymbolStem is specified.
146 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
147                                 const char *SymbolStem = 0) {
148   Asm->OutStreamer.SwitchSection(Section);
149   if (!SymbolStem) return 0;
150
151   MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
152   Asm->OutStreamer.EmitLabel(TmpSym);
153   return TmpSym;
154 }
155
156 MCSymbol *DwarfDebug::getStringPool() {
157   return Asm->GetTempSymbol("section_str");
158 }
159
160 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
161   std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
162   if (Entry.first) return Entry.first;
163
164   Entry.second = NextStringPoolNumber++;
165   return Entry.first = Asm->GetTempSymbol("string", Entry.second);
166 }
167
168 /// assignAbbrevNumber - Define a unique number for the abbreviation.
169 ///
170 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
171   // Profile the node so that we can make it unique.
172   FoldingSetNodeID ID;
173   Abbrev.Profile(ID);
174
175   // Check the set for priors.
176   DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
177
178   // If it's newly added.
179   if (InSet == &Abbrev) {
180     // Add to abbreviation list.
181     Abbreviations.push_back(&Abbrev);
182
183     // Assign the vector position + 1 as its number.
184     Abbrev.setNumber(Abbreviations.size());
185   } else {
186     // Assign existing abbreviation number.
187     Abbrev.setNumber(InSet->getNumber());
188   }
189 }
190
191 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
192 /// printer to not emit usual symbol prefix before the symbol name is used then
193 /// return linkage name after skipping this special LLVM prefix.
194 static StringRef getRealLinkageName(StringRef LinkageName) {
195   char One = '\1';
196   if (LinkageName.startswith(StringRef(&One, 1)))
197     return LinkageName.substr(1);
198   return LinkageName;
199 }
200
201 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
202 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
203 /// If there are global variables in this scope then create and insert
204 /// DIEs for these variables.
205 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
206                                           const MDNode *SPNode) {
207   DIE *SPDie = SPCU->getDIE(SPNode);
208
209   assert(SPDie && "Unable to find subprogram DIE!");
210   DISubprogram SP(SPNode);
211
212   DISubprogram SPDecl = SP.getFunctionDeclaration();
213   if (!SPDecl.isSubprogram()) {
214     // There is not any need to generate specification DIE for a function
215     // defined at compile unit level. If a function is defined inside another
216     // function then gdb prefers the definition at top level and but does not
217     // expect specification DIE in parent function. So avoid creating
218     // specification DIE for a function defined inside a function.
219     if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
220         !SP.getContext().isFile() &&
221         !isSubprogramContext(SP.getContext())) {
222       SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
223       
224       // Add arguments.
225       DICompositeType SPTy = SP.getType();
226       DIArray Args = SPTy.getTypeArray();
227       unsigned SPTag = SPTy.getTag();
228       if (SPTag == dwarf::DW_TAG_subroutine_type)
229         for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
230           DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
231           DIType ATy = DIType(DIType(Args.getElement(i)));
232           SPCU->addType(Arg, ATy);
233           if (ATy.isArtificial())
234             SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
235           SPDie->addChild(Arg);
236         }
237       DIE *SPDeclDie = SPDie;
238       SPDie = new DIE(dwarf::DW_TAG_subprogram);
239       SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
240                         SPDeclDie);
241       SPCU->addDie(SPDie);
242     }
243   }
244   // Pick up abstract subprogram DIE.
245   if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
246     SPDie = new DIE(dwarf::DW_TAG_subprogram);
247     SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
248                       dwarf::DW_FORM_ref4, AbsSPDIE);
249     SPCU->addDie(SPDie);
250   }
251
252   SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
253                  Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
254   SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
255                  Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
256   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
257   MachineLocation Location(RI->getFrameRegister(*Asm->MF));
258   SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
259
260   return SPDie;
261 }
262
263 /// constructLexicalScope - Construct new DW_TAG_lexical_block
264 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
265 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU, 
266                                           LexicalScope *Scope) {
267   DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
268   if (Scope->isAbstractScope())
269     return ScopeDIE;
270
271   const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
272   if (Ranges.empty())
273     return 0;
274
275   SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
276   if (Ranges.size() > 1) {
277     // .debug_range section has not been laid out yet. Emit offset in
278     // .debug_range as a uint, size 4, for now. emitDIE will handle
279     // DW_AT_ranges appropriately.
280     TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
281                    DebugRangeSymbols.size() 
282                    * Asm->getTargetData().getPointerSize());
283     for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
284          RE = Ranges.end(); RI != RE; ++RI) {
285       DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
286       DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
287     }
288     DebugRangeSymbols.push_back(NULL);
289     DebugRangeSymbols.push_back(NULL);
290     return ScopeDIE;
291   }
292
293   const MCSymbol *Start = getLabelBeforeInsn(RI->first);
294   const MCSymbol *End = getLabelAfterInsn(RI->second);
295
296   if (End == 0) return 0;
297
298   assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
299   assert(End->isDefined() && "Invalid end label for an inlined scope!");
300
301   TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
302   TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
303
304   return ScopeDIE;
305 }
306
307 /// constructInlinedScopeDIE - This scope represents inlined body of
308 /// a function. Construct DIE to represent this concrete inlined copy
309 /// of the function.
310 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
311                                           LexicalScope *Scope) {
312   const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
313   assert(Ranges.empty() == false &&
314          "LexicalScope does not have instruction markers!");
315
316   if (!Scope->getScopeNode())
317     return NULL;
318   DIScope DS(Scope->getScopeNode());
319   DISubprogram InlinedSP = getDISubprogram(DS);
320   DIE *OriginDIE = TheCU->getDIE(InlinedSP);
321   if (!OriginDIE) {
322     DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
323     return NULL;
324   }
325
326   SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
327   const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
328   const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
329
330   if (StartLabel == 0 || EndLabel == 0) {
331     assert(0 && "Unexpected Start and End labels for a inlined scope!");
332     return 0;
333   }
334   assert(StartLabel->isDefined() &&
335          "Invalid starting label for an inlined scope!");
336   assert(EndLabel->isDefined() &&
337          "Invalid end label for an inlined scope!");
338
339   DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
340   TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
341                      dwarf::DW_FORM_ref4, OriginDIE);
342
343   if (Ranges.size() > 1) {
344     // .debug_range section has not been laid out yet. Emit offset in
345     // .debug_range as a uint, size 4, for now. emitDIE will handle
346     // DW_AT_ranges appropriately.
347     TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
348                    DebugRangeSymbols.size() 
349                    * Asm->getTargetData().getPointerSize());
350     for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
351          RE = Ranges.end(); RI != RE; ++RI) {
352       DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
353       DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
354     }
355     DebugRangeSymbols.push_back(NULL);
356     DebugRangeSymbols.push_back(NULL);
357   } else {
358     TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 
359                     StartLabel);
360     TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, 
361                     EndLabel);
362   }
363
364   InlinedSubprogramDIEs.insert(OriginDIE);
365
366   // Track the start label for this inlined function.
367   //.debug_inlined section specification does not clearly state how
368   // to emit inlined scope that is split into multiple instruction ranges.
369   // For now, use first instruction range and emit low_pc/high_pc pair and
370   // corresponding .debug_inlined section entry for this pair.
371   DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
372     I = InlineInfo.find(InlinedSP);
373
374   if (I == InlineInfo.end()) {
375     InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
376     InlinedSPNodes.push_back(InlinedSP);
377   } else
378     I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
379
380   DILocation DL(Scope->getInlinedAt());
381   TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
382   TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
383
384   return ScopeDIE;
385 }
386
387 /// constructScopeDIE - Construct a DIE for this scope.
388 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
389   if (!Scope || !Scope->getScopeNode())
390     return NULL;
391
392   SmallVector<DIE *, 8> Children;
393
394   // Collect arguments for current function.
395   if (LScopes.isCurrentFunctionScope(Scope))
396     for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
397       if (DbgVariable *ArgDV = CurrentFnArguments[i])
398         if (DIE *Arg = 
399             TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope()))
400           Children.push_back(Arg);
401
402   // Collect lexical scope children first.
403   const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
404   for (unsigned i = 0, N = Variables.size(); i < N; ++i)
405     if (DIE *Variable = 
406         TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope()))
407       Children.push_back(Variable);
408   const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
409   for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
410     if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
411       Children.push_back(Nested);
412   DIScope DS(Scope->getScopeNode());
413   DIE *ScopeDIE = NULL;
414   if (Scope->getInlinedAt())
415     ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
416   else if (DS.isSubprogram()) {
417     ProcessedSPNodes.insert(DS);
418     if (Scope->isAbstractScope()) {
419       ScopeDIE = TheCU->getDIE(DS);
420       // Note down abstract DIE.
421       if (ScopeDIE)
422         AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
423     }
424     else
425       ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
426   }
427   else {
428     // There is no need to emit empty lexical block DIE.
429     if (Children.empty())
430       return NULL;
431     ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
432   }
433   
434   if (!ScopeDIE) return NULL;
435
436   // Add children
437   for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
438          E = Children.end(); I != E; ++I)
439     ScopeDIE->addChild(*I);
440
441   if (DS.isSubprogram())
442    TheCU->addPubTypes(DISubprogram(DS));
443
444   if (DS.isSubprogram() && !Scope->isAbstractScope()) {
445     DISubprogram SP = DISubprogram(DS);
446     TheCU->addAccelName(SP.getName(), ScopeDIE);
447
448     // If the linkage name is different than the name, go ahead and output
449     // that as well into the name table.
450     if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
451       TheCU->addAccelName(SP.getLinkageName(), ScopeDIE);
452   }
453
454  return ScopeDIE;
455 }
456
457 /// GetOrCreateSourceID - Look up the source id with the given directory and
458 /// source file names. If none currently exists, create a new id and insert it
459 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
460 /// maps as well.
461 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName, 
462                                          StringRef DirName) {
463   // If FE did not provide a file name, then assume stdin.
464   if (FileName.empty())
465     return GetOrCreateSourceID("<stdin>", StringRef());
466
467   // TODO: this might not belong here. See if we can factor this better.
468   if (DirName == CompilationDir)
469     DirName = "";
470
471   unsigned SrcId = SourceIdMap.size()+1;
472   std::pair<std::string, std::string> SourceName =
473       std::make_pair(FileName, DirName);
474   std::pair<std::pair<std::string, std::string>, unsigned> Entry =
475       make_pair(SourceName, SrcId);
476
477   std::map<std::pair<std::string, std::string>, unsigned>::iterator I;
478   bool NewlyInserted;
479   tie(I, NewlyInserted) = SourceIdMap.insert(Entry);
480   if (!NewlyInserted)
481     return I->second;
482
483   // Print out a .file directive to specify files for .loc directives.
484   Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.first.second,
485                                           Entry.first.first);
486
487   return SrcId;
488 }
489
490 /// constructCompileUnit - Create new CompileUnit for the given
491 /// metadata node with tag DW_TAG_compile_unit.
492 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
493   DICompileUnit DIUnit(N);
494   StringRef FN = DIUnit.getFilename();
495   CompilationDir = DIUnit.getDirectory();
496   unsigned ID = GetOrCreateSourceID(FN, CompilationDir);
497
498   DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
499   CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
500   NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
501   NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
502                  DIUnit.getLanguage());
503   NewCU->addString(Die, dwarf::DW_AT_name, FN);
504   // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
505   // simplifies debug range entries.
506   NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
507   // DW_AT_stmt_list is a offset of line number information for this
508   // compile unit in debug_line section.
509   if (Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
510     NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
511                     Asm->GetTempSymbol("section_line"));
512   else
513     NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
514
515   if (!CompilationDir.empty())
516     NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
517   if (DIUnit.isOptimized())
518     NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
519
520   StringRef Flags = DIUnit.getFlags();
521   if (!Flags.empty())
522     NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
523   
524   if (unsigned RVer = DIUnit.getRunTimeVersion())
525     NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
526             dwarf::DW_FORM_data1, RVer);
527
528   if (!FirstCU)
529     FirstCU = NewCU;
530   CUMap.insert(std::make_pair(N, NewCU));
531   return NewCU;
532 }
533
534 static bool isObjCClass(StringRef Name) {
535   return Name.startswith("+") || Name.startswith("-");
536 }
537
538 static bool hasObjCCategory(StringRef Name) {
539   if (!isObjCClass(Name)) return false;
540
541   size_t pos = Name.find(')');
542   if (pos != std::string::npos) {
543     if (Name[pos+1] != ' ') return false;
544     return true;
545   }
546   return false;
547 }
548
549 static void getObjCClassCategory(StringRef In, StringRef &Class,
550                                  StringRef &Category) {
551   if (!hasObjCCategory(In)) {
552     Class = In.slice(In.find('[') + 1, In.find(' '));
553     Category = "";
554     return;
555   }
556
557   Class = In.slice(In.find('[') + 1, In.find('('));
558   Category = In.slice(In.find('[') + 1, In.find(' '));
559   return;
560 }
561
562 static StringRef getObjCMethodName(StringRef In) {
563   return In.slice(In.find(' ') + 1, In.find(']'));
564 }
565
566 /// construct SubprogramDIE - Construct subprogram DIE.
567 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU, 
568                                         const MDNode *N) {
569   CompileUnit *&CURef = SPMap[N];
570   if (CURef)
571     return;
572   CURef = TheCU;
573
574   DISubprogram SP(N);
575   if (!SP.isDefinition())
576     // This is a method declaration which will be handled while constructing
577     // class type.
578     return;
579
580   DISubprogram SPDecl = SP.getFunctionDeclaration();
581   DIE *DeclDie = NULL;
582   if (SPDecl.isSubprogram()) {
583     DeclDie = TheCU->getOrCreateSubprogramDIE(SPDecl);
584   }
585
586   DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
587
588   if (DeclDie) {
589     // Refer function declaration directly.
590     TheCU->addDIEEntry(SubprogramDie, dwarf::DW_AT_specification,
591                        dwarf::DW_FORM_ref4, DeclDie);
592   }
593
594   // Add to map.
595   TheCU->insertDIE(N, SubprogramDie);
596
597   // Add to context owner.
598   TheCU->addToContextOwner(SubprogramDie, SP.getContext());
599
600   // Expose as global.
601   TheCU->addGlobal(SP.getName(), SubprogramDie);
602
603   // Add to Accel Names
604   TheCU->addAccelName(SP.getName(), SubprogramDie);
605
606   // If the linkage name is different than the name, go ahead and output
607   // that as well into the name table.
608   if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
609     TheCU->addAccelName(SP.getLinkageName(), SubprogramDie);
610
611   // If this is an Objective-C selector name add it to the ObjC accelerator too.
612   if (isObjCClass(SP.getName())) {
613     StringRef Class, Category;
614     getObjCClassCategory(SP.getName(), Class, Category);
615     TheCU->addAccelObjC(Class, SubprogramDie);
616     if (Category != "")
617       TheCU->addAccelObjC(Category, SubprogramDie);
618     // Also add the base method name to the name table.
619     TheCU->addAccelName(getObjCMethodName(SP.getName()), SubprogramDie);
620   }
621   
622   return;
623 }
624
625 /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
626 /// as llvm.dbg.enum and llvm.dbg.ty
627 void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
628   if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
629     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
630       const MDNode *N = NMD->getOperand(i);
631       if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
632         constructSubprogramDIE(CU, N);
633     }
634   
635   if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
636     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
637       const MDNode *N = NMD->getOperand(i);
638       if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
639         CU->createGlobalVariableDIE(N);
640     }
641   
642   if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
643     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
644       DIType Ty(NMD->getOperand(i));
645       if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
646         CU->getOrCreateTypeDIE(Ty);
647     }
648   
649   if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
650     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
651       DIType Ty(NMD->getOperand(i));
652       if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
653         CU->getOrCreateTypeDIE(Ty);
654     }
655 }
656
657 /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
658 /// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
659 bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
660   DebugInfoFinder DbgFinder;
661   DbgFinder.processModule(*M);
662   
663   bool HasDebugInfo = false;
664   // Scan all the compile-units to see if there are any marked as the main
665   // unit. If not, we do not generate debug info.
666   for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
667          E = DbgFinder.compile_unit_end(); I != E; ++I) {
668     if (DICompileUnit(*I).isMain()) {
669       HasDebugInfo = true;
670       break;
671     }
672   }
673   if (!HasDebugInfo) return false;
674   
675   // Create all the compile unit DIEs.
676   for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
677          E = DbgFinder.compile_unit_end(); I != E; ++I)
678     constructCompileUnit(*I);
679   
680   // Create DIEs for each global variable.
681   for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
682          E = DbgFinder.global_variable_end(); I != E; ++I) {
683     const MDNode *N = *I;
684     if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
685       CU->createGlobalVariableDIE(N);
686   }
687     
688   // Create DIEs for each subprogram.
689   for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
690          E = DbgFinder.subprogram_end(); I != E; ++I) {
691     const MDNode *N = *I;
692     if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
693       constructSubprogramDIE(CU, N);
694   }
695
696   return HasDebugInfo;
697 }
698
699 /// beginModule - Emit all Dwarf sections that should come prior to the
700 /// content. Create global DIEs and emit initial debug info sections.
701 /// This is invoked by the target AsmPrinter.
702 void DwarfDebug::beginModule(Module *M) {
703   if (DisableDebugInfoPrinting)
704     return;
705
706   // If module has named metadata anchors then use them, otherwise scan the
707   // module using debug info finder to collect debug info.
708   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
709   if (CU_Nodes) {
710     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
711       DICompileUnit CUNode(CU_Nodes->getOperand(i));
712       CompileUnit *CU = constructCompileUnit(CUNode);
713       DIArray GVs = CUNode.getGlobalVariables();
714       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
715         CU->createGlobalVariableDIE(GVs.getElement(i));
716       DIArray SPs = CUNode.getSubprograms();
717       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
718         constructSubprogramDIE(CU, SPs.getElement(i));
719       DIArray EnumTypes = CUNode.getEnumTypes();
720       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
721         CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
722       DIArray RetainedTypes = CUNode.getRetainedTypes();
723       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
724         CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
725     }
726   } else if (!collectLegacyDebugInfo(M))
727     return;
728
729   collectInfoFromNamedMDNodes(M);
730   
731   // Tell MMI that we have debug info.
732   MMI->setDebugInfoAvailability(true);
733   
734   // Emit initial sections.
735   EmitSectionLabels();
736
737   // Prime section data.
738   SectionMap.insert(Asm->getObjFileLowering().getTextSection());
739 }
740
741 /// endModule - Emit all Dwarf sections that should come after the content.
742 ///
743 void DwarfDebug::endModule() {
744   if (!FirstCU) return;
745   const Module *M = MMI->getModule();
746   DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
747
748   // Collect info for variables that were optimized out.
749   if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
750     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
751       DICompileUnit TheCU(CU_Nodes->getOperand(i));
752       DIArray Subprograms = TheCU.getSubprograms();
753       for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
754         DISubprogram SP(Subprograms.getElement(i));
755         if (ProcessedSPNodes.count(SP) != 0) continue;
756         if (!SP.Verify()) continue;
757         if (!SP.isDefinition()) continue;
758         DIArray Variables = SP.getVariables();
759         if (Variables.getNumElements() == 0) continue;
760
761         LexicalScope *Scope = 
762           new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
763         DeadFnScopeMap[SP] = Scope;
764         
765         // Construct subprogram DIE and add variables DIEs.
766         CompileUnit *SPCU = CUMap.lookup(TheCU);
767         assert(SPCU && "Unable to find Compile Unit!");
768         constructSubprogramDIE(SPCU, SP);
769         DIE *ScopeDIE = SPCU->getDIE(SP);
770         for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
771           DIVariable DV(Variables.getElement(vi));
772           if (!DV.Verify()) continue;
773           DbgVariable *NewVar = new DbgVariable(DV, NULL);
774           if (DIE *VariableDIE = 
775               SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
776             ScopeDIE->addChild(VariableDIE);
777         }
778       }
779     }
780   }
781
782   // Attach DW_AT_inline attribute with inlined subprogram DIEs.
783   for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
784          AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
785     DIE *ISP = *AI;
786     FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
787   }
788
789   // Emit DW_AT_containing_type attribute to connect types with their
790   // vtable holding type.
791   for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
792          CUE = CUMap.end(); CUI != CUE; ++CUI) {
793     CompileUnit *TheCU = CUI->second;
794     TheCU->constructContainingTypeDIEs();
795   }
796
797   // Standard sections final addresses.
798   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
799   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
800   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
801   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
802
803   // End text sections.
804   for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
805     Asm->OutStreamer.SwitchSection(SectionMap[i]);
806     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
807   }
808
809   // Compute DIE offsets and sizes.
810   computeSizeAndOffsets();
811
812   // Emit all the DIEs into a debug info section
813   emitDebugInfo();
814
815   // Corresponding abbreviations into a abbrev section.
816   emitAbbreviations();
817
818   // Emit info into a dwarf accelerator table sections.
819   if (DwarfAccelTables) {
820     emitAccelNames();
821     emitAccelObjC();
822     emitAccelNamespaces();
823     emitAccelTypes();
824   }
825   
826   // Emit info into a debug pubnames section.
827   emitDebugPubNames();
828
829   // Emit info into a debug pubtypes section.
830   emitDebugPubTypes();
831
832   // Emit info into a debug loc section.
833   emitDebugLoc();
834
835   // Emit info into a debug aranges section.
836   EmitDebugARanges();
837
838   // Emit info into a debug ranges section.
839   emitDebugRanges();
840
841   // Emit info into a debug macinfo section.
842   emitDebugMacInfo();
843
844   // Emit inline info.
845   emitDebugInlineInfo();
846
847   // Emit info into a debug str section.
848   emitDebugStr();
849
850   // clean up.
851   DeleteContainerSeconds(DeadFnScopeMap);
852   SPMap.clear();
853   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
854          E = CUMap.end(); I != E; ++I)
855     delete I->second;
856   FirstCU = NULL;  // Reset for the next Module, if any.
857 }
858
859 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
860 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
861                                               DebugLoc ScopeLoc) {
862   LLVMContext &Ctx = DV->getContext();
863   // More then one inlined variable corresponds to one abstract variable.
864   DIVariable Var = cleanseInlinedVariable(DV, Ctx);
865   DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
866   if (AbsDbgVariable)
867     return AbsDbgVariable;
868
869   LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
870   if (!Scope)
871     return NULL;
872
873   AbsDbgVariable = new DbgVariable(Var, NULL);
874   addScopeVariable(Scope, AbsDbgVariable);
875   AbstractVariables[Var] = AbsDbgVariable;
876   return AbsDbgVariable;
877 }
878
879 /// addCurrentFnArgument - If Var is a current function argument then add
880 /// it to CurrentFnArguments list.
881 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
882                                       DbgVariable *Var, LexicalScope *Scope) {
883   if (!LScopes.isCurrentFunctionScope(Scope))
884     return false;
885   DIVariable DV = Var->getVariable();
886   if (DV.getTag() != dwarf::DW_TAG_arg_variable)
887     return false;
888   unsigned ArgNo = DV.getArgNumber();
889   if (ArgNo == 0) 
890     return false;
891
892   size_t Size = CurrentFnArguments.size();
893   if (Size == 0)
894     CurrentFnArguments.resize(MF->getFunction()->arg_size());
895   // llvm::Function argument size is not good indicator of how many
896   // arguments does the function have at source level.
897   if (ArgNo > Size)
898     CurrentFnArguments.resize(ArgNo * 2);
899   CurrentFnArguments[ArgNo - 1] = Var;
900   return true;
901 }
902
903 /// collectVariableInfoFromMMITable - Collect variable information from
904 /// side table maintained by MMI.
905 void
906 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
907                                    SmallPtrSet<const MDNode *, 16> &Processed) {
908   MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
909   for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
910          VE = VMap.end(); VI != VE; ++VI) {
911     const MDNode *Var = VI->first;
912     if (!Var) continue;
913     Processed.insert(Var);
914     DIVariable DV(Var);
915     const std::pair<unsigned, DebugLoc> &VP = VI->second;
916
917     LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
918
919     // If variable scope is not found then skip this variable.
920     if (Scope == 0)
921       continue;
922
923     DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
924     DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
925     RegVar->setFrameIndex(VP.first);
926     if (!addCurrentFnArgument(MF, RegVar, Scope))
927       addScopeVariable(Scope, RegVar);
928     if (AbsDbgVariable)
929       AbsDbgVariable->setFrameIndex(VP.first);
930   }
931 }
932
933 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
934 /// DBG_VALUE instruction, is in a defined reg.
935 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
936   assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
937   return MI->getNumOperands() == 3 &&
938          MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
939          MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
940 }
941
942 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
943 /// at MI.
944 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm, 
945                                          const MCSymbol *FLabel, 
946                                          const MCSymbol *SLabel,
947                                          const MachineInstr *MI) {
948   const MDNode *Var =  MI->getOperand(MI->getNumOperands() - 1).getMetadata();
949
950   if (MI->getNumOperands() != 3) {
951     MachineLocation MLoc = Asm->getDebugValueLocation(MI);
952     return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
953   }
954   if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
955     MachineLocation MLoc;
956     MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
957     return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
958   }
959   if (MI->getOperand(0).isImm())
960     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
961   if (MI->getOperand(0).isFPImm())
962     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
963   if (MI->getOperand(0).isCImm())
964     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
965
966   assert(0 && "Unexpected 3 operand DBG_VALUE instruction!");
967   return DotDebugLocEntry();
968 }
969
970 /// collectVariableInfo - Find variables for each lexical scope.
971 void
972 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
973                                 SmallPtrSet<const MDNode *, 16> &Processed) {
974
975   /// collection info from MMI table.
976   collectVariableInfoFromMMITable(MF, Processed);
977
978   for (SmallVectorImpl<const MDNode*>::const_iterator
979          UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
980          ++UVI) {
981     const MDNode *Var = *UVI;
982     if (Processed.count(Var))
983       continue;
984
985     // History contains relevant DBG_VALUE instructions for Var and instructions
986     // clobbering it.
987     SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
988     if (History.empty())
989       continue;
990     const MachineInstr *MInsn = History.front();
991
992     DIVariable DV(Var);
993     LexicalScope *Scope = NULL;
994     if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
995         DISubprogram(DV.getContext()).describes(MF->getFunction()))
996       Scope = LScopes.getCurrentFunctionScope();
997     else {
998       if (DV.getVersion() <= LLVMDebugVersion9)
999         Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1000       else {
1001         if (MDNode *IA = DV.getInlinedAt())
1002           Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1003         else
1004           Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1005       }
1006     }
1007     // If variable scope is not found then skip this variable.
1008     if (!Scope)
1009       continue;
1010
1011     Processed.insert(DV);
1012     assert(MInsn->isDebugValue() && "History must begin with debug value");
1013     DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1014     DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1015     if (!addCurrentFnArgument(MF, RegVar, Scope))
1016       addScopeVariable(Scope, RegVar);
1017     if (AbsVar)
1018       AbsVar->setMInsn(MInsn);
1019
1020     // Simple ranges that are fully coalesced.
1021     if (History.size() <= 1 || (History.size() == 2 &&
1022                                 MInsn->isIdenticalTo(History.back()))) {
1023       RegVar->setMInsn(MInsn);
1024       continue;
1025     }
1026
1027     // handle multiple DBG_VALUE instructions describing one variable.
1028     RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1029
1030     for (SmallVectorImpl<const MachineInstr*>::const_iterator
1031            HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1032       const MachineInstr *Begin = *HI;
1033       assert(Begin->isDebugValue() && "Invalid History entry");
1034
1035       // Check if DBG_VALUE is truncating a range.
1036       if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1037           && !Begin->getOperand(0).getReg())
1038         continue;
1039
1040       // Compute the range for a register location.
1041       const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1042       const MCSymbol *SLabel = 0;
1043
1044       if (HI + 1 == HE)
1045         // If Begin is the last instruction in History then its value is valid
1046         // until the end of the function.
1047         SLabel = FunctionEndSym;
1048       else {
1049         const MachineInstr *End = HI[1];
1050         DEBUG(dbgs() << "DotDebugLoc Pair:\n" 
1051               << "\t" << *Begin << "\t" << *End << "\n");
1052         if (End->isDebugValue())
1053           SLabel = getLabelBeforeInsn(End);
1054         else {
1055           // End is a normal instruction clobbering the range.
1056           SLabel = getLabelAfterInsn(End);
1057           assert(SLabel && "Forgot label after clobber instruction");
1058           ++HI;
1059         }
1060       }
1061
1062       // The value is valid until the next DBG_VALUE or clobber.
1063       DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1064     }
1065     DotDebugLocEntries.push_back(DotDebugLocEntry());
1066   }
1067
1068   // Collect info for variables that were optimized out.
1069   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1070   DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1071   for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1072     DIVariable DV(Variables.getElement(i));
1073     if (!DV || !DV.Verify() || !Processed.insert(DV))
1074       continue;
1075     if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1076       addScopeVariable(Scope, new DbgVariable(DV, NULL));
1077   }
1078 }
1079
1080 /// getLabelBeforeInsn - Return Label preceding the instruction.
1081 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1082   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1083   assert(Label && "Didn't insert label before instruction");
1084   return Label;
1085 }
1086
1087 /// getLabelAfterInsn - Return Label immediately following the instruction.
1088 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1089   return LabelsAfterInsn.lookup(MI);
1090 }
1091
1092 /// beginInstruction - Process beginning of an instruction.
1093 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1094   // Check if source location changes, but ignore DBG_VALUE locations.
1095   if (!MI->isDebugValue()) {
1096     DebugLoc DL = MI->getDebugLoc();
1097     if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1098       unsigned Flags = DWARF2_FLAG_IS_STMT;
1099       PrevInstLoc = DL;
1100       if (DL == PrologEndLoc) {
1101         Flags |= DWARF2_FLAG_PROLOGUE_END;
1102         PrologEndLoc = DebugLoc();
1103       }
1104       if (!DL.isUnknown()) {
1105         const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1106         recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1107       } else
1108         recordSourceLine(0, 0, 0, 0);
1109     }
1110   }
1111
1112   // Insert labels where requested.
1113   DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1114     LabelsBeforeInsn.find(MI);
1115
1116   // No label needed.
1117   if (I == LabelsBeforeInsn.end())
1118     return;
1119
1120   // Label already assigned.
1121   if (I->second)
1122     return;
1123
1124   if (!PrevLabel) {
1125     PrevLabel = MMI->getContext().CreateTempSymbol();
1126     Asm->OutStreamer.EmitLabel(PrevLabel);
1127   }
1128   I->second = PrevLabel;
1129 }
1130
1131 /// endInstruction - Process end of an instruction.
1132 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1133   // Don't create a new label after DBG_VALUE instructions.
1134   // They don't generate code.
1135   if (!MI->isDebugValue())
1136     PrevLabel = 0;
1137
1138   DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1139     LabelsAfterInsn.find(MI);
1140
1141   // No label needed.
1142   if (I == LabelsAfterInsn.end())
1143     return;
1144
1145   // Label already assigned.
1146   if (I->second)
1147     return;
1148
1149   // We need a label after this instruction.
1150   if (!PrevLabel) {
1151     PrevLabel = MMI->getContext().CreateTempSymbol();
1152     Asm->OutStreamer.EmitLabel(PrevLabel);
1153   }
1154   I->second = PrevLabel;
1155 }
1156
1157 /// identifyScopeMarkers() -
1158 /// Each LexicalScope has first instruction and last instruction to mark
1159 /// beginning and end of a scope respectively. Create an inverse map that list
1160 /// scopes starts (and ends) with an instruction. One instruction may start (or
1161 /// end) multiple scopes. Ignore scopes that are not reachable.
1162 void DwarfDebug::identifyScopeMarkers() {
1163   SmallVector<LexicalScope *, 4> WorkList;
1164   WorkList.push_back(LScopes.getCurrentFunctionScope());
1165   while (!WorkList.empty()) {
1166     LexicalScope *S = WorkList.pop_back_val();
1167
1168     const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1169     if (!Children.empty())
1170       for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1171              SE = Children.end(); SI != SE; ++SI)
1172         WorkList.push_back(*SI);
1173
1174     if (S->isAbstractScope())
1175       continue;
1176
1177     const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1178     if (Ranges.empty())
1179       continue;
1180     for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1181            RE = Ranges.end(); RI != RE; ++RI) {
1182       assert(RI->first && "InsnRange does not have first instruction!");
1183       assert(RI->second && "InsnRange does not have second instruction!");
1184       requestLabelBeforeInsn(RI->first);
1185       requestLabelAfterInsn(RI->second);
1186     }
1187   }
1188 }
1189
1190 /// getScopeNode - Get MDNode for DebugLoc's scope.
1191 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1192   if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1193     return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1194   return DL.getScope(Ctx);
1195 }
1196
1197 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1198 /// line number  info for the function.
1199 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1200   const MDNode *Scope = getScopeNode(DL, Ctx);
1201   DISubprogram SP = getDISubprogram(Scope);
1202   if (SP.Verify()) 
1203     return DebugLoc::get(SP.getLineNumber(), 0, SP);
1204   return DebugLoc();
1205 }
1206
1207 /// beginFunction - Gather pre-function debug information.  Assumes being
1208 /// emitted immediately after the function entry point.
1209 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1210   if (!MMI->hasDebugInfo()) return;
1211   LScopes.initialize(*MF);
1212   if (LScopes.empty()) return;
1213   identifyScopeMarkers();
1214
1215   FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1216                                         Asm->getFunctionNumber());
1217   // Assumes in correct section after the entry point.
1218   Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1219
1220   assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1221
1222   const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1223   /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1224   std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1225
1226   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1227        I != E; ++I) {
1228     bool AtBlockEntry = true;
1229     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1230          II != IE; ++II) {
1231       const MachineInstr *MI = II;
1232
1233       if (MI->isDebugValue()) {
1234         assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1235
1236         // Keep track of user variables.
1237         const MDNode *Var =
1238           MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1239
1240         // Variable is in a register, we need to check for clobbers.
1241         if (isDbgValueInDefinedReg(MI))
1242           LiveUserVar[MI->getOperand(0).getReg()] = Var;
1243
1244         // Check the history of this variable.
1245         SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1246         if (History.empty()) {
1247           UserVariables.push_back(Var);
1248           // The first mention of a function argument gets the FunctionBeginSym
1249           // label, so arguments are visible when breaking at function entry.
1250           DIVariable DV(Var);
1251           if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1252               DISubprogram(getDISubprogram(DV.getContext()))
1253                 .describes(MF->getFunction()))
1254             LabelsBeforeInsn[MI] = FunctionBeginSym;
1255         } else {
1256           // We have seen this variable before. Try to coalesce DBG_VALUEs.
1257           const MachineInstr *Prev = History.back();
1258           if (Prev->isDebugValue()) {
1259             // Coalesce identical entries at the end of History.
1260             if (History.size() >= 2 &&
1261                 Prev->isIdenticalTo(History[History.size() - 2])) {
1262               DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1263                     << "\t" << *Prev 
1264                     << "\t" << *History[History.size() - 2] << "\n");
1265               History.pop_back();
1266             }
1267
1268             // Terminate old register assignments that don't reach MI;
1269             MachineFunction::const_iterator PrevMBB = Prev->getParent();
1270             if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1271                 isDbgValueInDefinedReg(Prev)) {
1272               // Previous register assignment needs to terminate at the end of
1273               // its basic block.
1274               MachineBasicBlock::const_iterator LastMI =
1275                 PrevMBB->getLastNonDebugInstr();
1276               if (LastMI == PrevMBB->end()) {
1277                 // Drop DBG_VALUE for empty range.
1278                 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1279                       << "\t" << *Prev << "\n");
1280                 History.pop_back();
1281               }
1282               else {
1283                 // Terminate after LastMI.
1284                 History.push_back(LastMI);
1285               }
1286             }
1287           }
1288         }
1289         History.push_back(MI);
1290       } else {
1291         // Not a DBG_VALUE instruction.
1292         if (!MI->isLabel())
1293           AtBlockEntry = false;
1294
1295         // First known non DBG_VALUE location marks beginning of function
1296         // body.
1297         if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1298           PrologEndLoc = MI->getDebugLoc();
1299
1300         // Check if the instruction clobbers any registers with debug vars.
1301         for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1302                MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1303           if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1304             continue;
1305           for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1306                unsigned Reg = *AI; ++AI) {
1307             const MDNode *Var = LiveUserVar[Reg];
1308             if (!Var)
1309               continue;
1310             // Reg is now clobbered.
1311             LiveUserVar[Reg] = 0;
1312
1313             // Was MD last defined by a DBG_VALUE referring to Reg?
1314             DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1315             if (HistI == DbgValues.end())
1316               continue;
1317             SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1318             if (History.empty())
1319               continue;
1320             const MachineInstr *Prev = History.back();
1321             // Sanity-check: Register assignments are terminated at the end of
1322             // their block.
1323             if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1324               continue;
1325             // Is the variable still in Reg?
1326             if (!isDbgValueInDefinedReg(Prev) ||
1327                 Prev->getOperand(0).getReg() != Reg)
1328               continue;
1329             // Var is clobbered. Make sure the next instruction gets a label.
1330             History.push_back(MI);
1331           }
1332         }
1333       }
1334     }
1335   }
1336
1337   for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1338        I != E; ++I) {
1339     SmallVectorImpl<const MachineInstr*> &History = I->second;
1340     if (History.empty())
1341       continue;
1342
1343     // Make sure the final register assignments are terminated.
1344     const MachineInstr *Prev = History.back();
1345     if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1346       const MachineBasicBlock *PrevMBB = Prev->getParent();
1347       MachineBasicBlock::const_iterator LastMI = 
1348         PrevMBB->getLastNonDebugInstr();
1349       if (LastMI == PrevMBB->end())
1350         // Drop DBG_VALUE for empty range.
1351         History.pop_back();
1352       else {
1353         // Terminate after LastMI.
1354         History.push_back(LastMI);
1355       }
1356     }
1357     // Request labels for the full history.
1358     for (unsigned i = 0, e = History.size(); i != e; ++i) {
1359       const MachineInstr *MI = History[i];
1360       if (MI->isDebugValue())
1361         requestLabelBeforeInsn(MI);
1362       else
1363         requestLabelAfterInsn(MI);
1364     }
1365   }
1366
1367   PrevInstLoc = DebugLoc();
1368   PrevLabel = FunctionBeginSym;
1369
1370   // Record beginning of function.
1371   if (!PrologEndLoc.isUnknown()) {
1372     DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1373                                        MF->getFunction()->getContext());
1374     recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1375                      FnStartDL.getScope(MF->getFunction()->getContext()),
1376                      DWARF2_FLAG_IS_STMT);
1377   }
1378 }
1379
1380 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1381 //  SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1382   ScopeVariables[LS].push_back(Var);
1383 //  Vars.push_back(Var);
1384 }
1385
1386 /// endFunction - Gather and emit post-function debug information.
1387 ///
1388 void DwarfDebug::endFunction(const MachineFunction *MF) {
1389   if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1390
1391   // Define end label for subprogram.
1392   FunctionEndSym = Asm->GetTempSymbol("func_end",
1393                                       Asm->getFunctionNumber());
1394   // Assumes in correct section after the entry point.
1395   Asm->OutStreamer.EmitLabel(FunctionEndSym);
1396   
1397   SmallPtrSet<const MDNode *, 16> ProcessedVars;
1398   collectVariableInfo(MF, ProcessedVars);
1399   
1400   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1401   CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1402   assert(TheCU && "Unable to find compile unit!");
1403
1404   // Construct abstract scopes.
1405   ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1406   for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1407     LexicalScope *AScope = AList[i];
1408     DISubprogram SP(AScope->getScopeNode());
1409     if (SP.Verify()) {
1410       // Collect info for variables that were optimized out.
1411       DIArray Variables = SP.getVariables();
1412       for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1413         DIVariable DV(Variables.getElement(i));
1414         if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1415           continue;
1416         if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1417           addScopeVariable(Scope, new DbgVariable(DV, NULL));
1418       }
1419     }
1420     if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1421       constructScopeDIE(TheCU, AScope);
1422   }
1423   
1424   DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1425   
1426   if (!DisableFramePointerElim(*MF))
1427     TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1428                    dwarf::DW_FORM_flag, 1);
1429
1430   DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1431                                                MMI->getFrameMoves()));
1432
1433   // Clear debug info
1434   for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1435          I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1436     DeleteContainerPointers(I->second);
1437   ScopeVariables.clear();
1438   DeleteContainerPointers(CurrentFnArguments);
1439   UserVariables.clear();
1440   DbgValues.clear();
1441   AbstractVariables.clear();
1442   LabelsBeforeInsn.clear();
1443   LabelsAfterInsn.clear();
1444   PrevLabel = NULL;
1445 }
1446
1447 /// recordSourceLine - Register a source line with debug info. Returns the
1448 /// unique label that was emitted and which provides correspondence to
1449 /// the source line list.
1450 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1451                                   unsigned Flags) {
1452   StringRef Fn;
1453   StringRef Dir;
1454   unsigned Src = 1;
1455   if (S) {
1456     DIDescriptor Scope(S);
1457
1458     if (Scope.isCompileUnit()) {
1459       DICompileUnit CU(S);
1460       Fn = CU.getFilename();
1461       Dir = CU.getDirectory();
1462     } else if (Scope.isFile()) {
1463       DIFile F(S);
1464       Fn = F.getFilename();
1465       Dir = F.getDirectory();
1466     } else if (Scope.isSubprogram()) {
1467       DISubprogram SP(S);
1468       Fn = SP.getFilename();
1469       Dir = SP.getDirectory();
1470     } else if (Scope.isLexicalBlockFile()) {
1471       DILexicalBlockFile DBF(S);
1472       Fn = DBF.getFilename();
1473       Dir = DBF.getDirectory();
1474     } else if (Scope.isLexicalBlock()) {
1475       DILexicalBlock DB(S);
1476       Fn = DB.getFilename();
1477       Dir = DB.getDirectory();
1478     } else
1479       assert(0 && "Unexpected scope info");
1480
1481     Src = GetOrCreateSourceID(Fn, Dir);
1482   }
1483   Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1484 }
1485
1486 //===----------------------------------------------------------------------===//
1487 // Emit Methods
1488 //===----------------------------------------------------------------------===//
1489
1490 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1491 ///
1492 unsigned
1493 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1494   // Get the children.
1495   const std::vector<DIE *> &Children = Die->getChildren();
1496
1497   // If not last sibling and has children then add sibling offset attribute.
1498   if (!Last && !Children.empty())
1499     Die->addSiblingOffset(DIEValueAllocator);
1500
1501   // Record the abbreviation.
1502   assignAbbrevNumber(Die->getAbbrev());
1503
1504   // Get the abbreviation for this DIE.
1505   unsigned AbbrevNumber = Die->getAbbrevNumber();
1506   const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1507
1508   // Set DIE offset
1509   Die->setOffset(Offset);
1510
1511   // Start the size with the size of abbreviation code.
1512   Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1513
1514   const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1515   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1516
1517   // Size the DIE attribute values.
1518   for (unsigned i = 0, N = Values.size(); i < N; ++i)
1519     // Size attribute value.
1520     Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1521
1522   // Size the DIE children if any.
1523   if (!Children.empty()) {
1524     assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1525            "Children flag not set");
1526
1527     for (unsigned j = 0, M = Children.size(); j < M; ++j)
1528       Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1529
1530     // End of children marker.
1531     Offset += sizeof(int8_t);
1532   }
1533
1534   Die->setSize(Offset - Die->getOffset());
1535   return Offset;
1536 }
1537
1538 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1539 ///
1540 void DwarfDebug::computeSizeAndOffsets() {
1541   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1542          E = CUMap.end(); I != E; ++I) {
1543     // Compute size of compile unit header.
1544     unsigned Offset = 
1545       sizeof(int32_t) + // Length of Compilation Unit Info
1546       sizeof(int16_t) + // DWARF version number
1547       sizeof(int32_t) + // Offset Into Abbrev. Section
1548       sizeof(int8_t);   // Pointer Size (in bytes)
1549     computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1550   }
1551 }
1552
1553 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1554 /// the start of each one.
1555 void DwarfDebug::EmitSectionLabels() {
1556   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1557
1558   // Dwarf sections base addresses.
1559   DwarfInfoSectionSym =
1560     EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1561   DwarfAbbrevSectionSym =
1562     EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1563   EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1564
1565   if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1566     EmitSectionSym(Asm, MacroInfo);
1567
1568   EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1569   EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1570   EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1571   EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1572   DwarfStrSectionSym =
1573     EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1574   DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1575                                              "debug_range");
1576
1577   DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1578                                            "section_debug_loc");
1579
1580   TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1581   EmitSectionSym(Asm, TLOF.getDataSection());
1582 }
1583
1584 /// emitDIE - Recursively emits a debug information entry.
1585 ///
1586 void DwarfDebug::emitDIE(DIE *Die) {
1587   // Get the abbreviation for this DIE.
1588   unsigned AbbrevNumber = Die->getAbbrevNumber();
1589   const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1590
1591   // Emit the code (index) for the abbreviation.
1592   if (Asm->isVerbose())
1593     Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1594                                 Twine::utohexstr(Die->getOffset()) + ":0x" +
1595                                 Twine::utohexstr(Die->getSize()) + " " +
1596                                 dwarf::TagString(Abbrev->getTag()));
1597   Asm->EmitULEB128(AbbrevNumber);
1598
1599   const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1600   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1601
1602   // Emit the DIE attribute values.
1603   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1604     unsigned Attr = AbbrevData[i].getAttribute();
1605     unsigned Form = AbbrevData[i].getForm();
1606     assert(Form && "Too many attributes for DIE (check abbreviation)");
1607
1608     if (Asm->isVerbose())
1609       Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1610
1611     switch (Attr) {
1612     case dwarf::DW_AT_sibling:
1613       Asm->EmitInt32(Die->getSiblingOffset());
1614       break;
1615     case dwarf::DW_AT_abstract_origin: {
1616       DIEEntry *E = cast<DIEEntry>(Values[i]);
1617       DIE *Origin = E->getEntry();
1618       unsigned Addr = Origin->getOffset();
1619       Asm->EmitInt32(Addr);
1620       break;
1621     }
1622     case dwarf::DW_AT_ranges: {
1623       // DW_AT_range Value encodes offset in debug_range section.
1624       DIEInteger *V = cast<DIEInteger>(Values[i]);
1625
1626       if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1627         Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1628                                  V->getValue(),
1629                                  4);
1630       } else {
1631         Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1632                                        V->getValue(),
1633                                        DwarfDebugRangeSectionSym,
1634                                        4);
1635       }
1636       break;
1637     }
1638     case dwarf::DW_AT_location: {
1639       if (DIELabel *L = dyn_cast<DIELabel>(Values[i]))
1640         Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1641       else
1642         Values[i]->EmitValue(Asm, Form);
1643       break;
1644     }
1645     case dwarf::DW_AT_accessibility: {
1646       if (Asm->isVerbose()) {
1647         DIEInteger *V = cast<DIEInteger>(Values[i]);
1648         Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1649       }
1650       Values[i]->EmitValue(Asm, Form);
1651       break;
1652     }
1653     default:
1654       // Emit an attribute using the defined form.
1655       Values[i]->EmitValue(Asm, Form);
1656       break;
1657     }
1658   }
1659
1660   // Emit the DIE children if any.
1661   if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1662     const std::vector<DIE *> &Children = Die->getChildren();
1663
1664     for (unsigned j = 0, M = Children.size(); j < M; ++j)
1665       emitDIE(Children[j]);
1666
1667     if (Asm->isVerbose())
1668       Asm->OutStreamer.AddComment("End Of Children Mark");
1669     Asm->EmitInt8(0);
1670   }
1671 }
1672
1673 /// emitDebugInfo - Emit the debug info section.
1674 ///
1675 void DwarfDebug::emitDebugInfo() {
1676   // Start debug info section.
1677   Asm->OutStreamer.SwitchSection(
1678                             Asm->getObjFileLowering().getDwarfInfoSection());
1679   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1680          E = CUMap.end(); I != E; ++I) {
1681     CompileUnit *TheCU = I->second;
1682     DIE *Die = TheCU->getCUDie();
1683
1684     // Emit the compile units header.
1685     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1686                                                   TheCU->getID()));
1687
1688     // Emit size of content not including length itself
1689     unsigned ContentSize = Die->getSize() +
1690       sizeof(int16_t) + // DWARF version number
1691       sizeof(int32_t) + // Offset Into Abbrev. Section
1692       sizeof(int8_t);   // Pointer Size (in bytes)
1693
1694     Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1695     Asm->EmitInt32(ContentSize);
1696     Asm->OutStreamer.AddComment("DWARF version number");
1697     Asm->EmitInt16(dwarf::DWARF_VERSION);
1698     Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1699     Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1700                            DwarfAbbrevSectionSym);
1701     Asm->OutStreamer.AddComment("Address Size (in bytes)");
1702     Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1703
1704     emitDIE(Die);
1705     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1706   }
1707 }
1708
1709 /// emitAbbreviations - Emit the abbreviation section.
1710 ///
1711 void DwarfDebug::emitAbbreviations() const {
1712   // Check to see if it is worth the effort.
1713   if (!Abbreviations.empty()) {
1714     // Start the debug abbrev section.
1715     Asm->OutStreamer.SwitchSection(
1716                             Asm->getObjFileLowering().getDwarfAbbrevSection());
1717
1718     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1719
1720     // For each abbrevation.
1721     for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1722       // Get abbreviation data
1723       const DIEAbbrev *Abbrev = Abbreviations[i];
1724
1725       // Emit the abbrevations code (base 1 index.)
1726       Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1727
1728       // Emit the abbreviations data.
1729       Abbrev->Emit(Asm);
1730     }
1731
1732     // Mark end of abbreviations.
1733     Asm->EmitULEB128(0, "EOM(3)");
1734
1735     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1736   }
1737 }
1738
1739 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1740 /// the line matrix.
1741 ///
1742 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1743   // Define last address of section.
1744   Asm->OutStreamer.AddComment("Extended Op");
1745   Asm->EmitInt8(0);
1746
1747   Asm->OutStreamer.AddComment("Op size");
1748   Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1749   Asm->OutStreamer.AddComment("DW_LNE_set_address");
1750   Asm->EmitInt8(dwarf::DW_LNE_set_address);
1751
1752   Asm->OutStreamer.AddComment("Section end label");
1753
1754   Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1755                                    Asm->getTargetData().getPointerSize(),
1756                                    0/*AddrSpace*/);
1757
1758   // Mark end of matrix.
1759   Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1760   Asm->EmitInt8(0);
1761   Asm->EmitInt8(1);
1762   Asm->EmitInt8(1);
1763 }
1764
1765 /// emitAccelNames - Emit visible names into a hashed accelerator table
1766 /// section.
1767 void DwarfDebug::emitAccelNames() {
1768   DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1769                                            dwarf::DW_FORM_data4));
1770   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1771          E = CUMap.end(); I != E; ++I) {
1772     CompileUnit *TheCU = I->second;
1773     const StringMap<DIE*> &Names = TheCU->getAccelNames();
1774     for (StringMap<DIE*>::const_iterator
1775            GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1776       const char *Name = GI->getKeyData();
1777       DIE *Entity = GI->second;
1778       AT.AddName(Name, Entity);
1779     }
1780   }
1781
1782   AT.FinalizeTable(Asm, "Names");
1783   Asm->OutStreamer.SwitchSection(
1784     Asm->getObjFileLowering().getDwarfAccelNamesSection());
1785   MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1786   Asm->OutStreamer.EmitLabel(SectionBegin);
1787
1788   // Emit the full data.
1789   AT.Emit(Asm, SectionBegin, this);
1790 }
1791
1792 /// emitAccelObjC - Emit objective C classes and categories into a hashed
1793 /// accelerator table section.
1794 void DwarfDebug::emitAccelObjC() {
1795   DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1796                                            dwarf::DW_FORM_data4));
1797   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1798          E = CUMap.end(); I != E; ++I) {
1799     CompileUnit *TheCU = I->second;
1800     const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
1801     for (StringMap<std::vector<DIE*> >::const_iterator
1802            GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1803       const char *Name = GI->getKeyData();
1804       std::vector<DIE *> Entities = GI->second;
1805       for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1806              DE = Entities.end(); DI != DE; ++DI)
1807         AT.AddName(Name, (*DI));
1808     }
1809   }
1810
1811   AT.FinalizeTable(Asm, "ObjC");
1812   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1813                                  .getDwarfAccelObjCSection());
1814   MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1815   Asm->OutStreamer.EmitLabel(SectionBegin);
1816
1817   // Emit the full data.
1818   AT.Emit(Asm, SectionBegin, this);
1819 }
1820
1821 /// emitAccelNamespace - Emit namespace dies into a hashed accelerator
1822 /// table.
1823 void DwarfDebug::emitAccelNamespaces() {
1824   DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1825                                            dwarf::DW_FORM_data4));
1826   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1827          E = CUMap.end(); I != E; ++I) {
1828     CompileUnit *TheCU = I->second;
1829     const StringMap<DIE*> &Names = TheCU->getAccelNamespace();
1830     for (StringMap<DIE*>::const_iterator
1831            GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1832       const char *Name = GI->getKeyData();
1833       DIE *Entity = GI->second;
1834       AT.AddName(Name, Entity);
1835     }
1836   }
1837
1838   AT.FinalizeTable(Asm, "namespac");
1839   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1840                                  .getDwarfAccelNamespaceSection());
1841   MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1842   Asm->OutStreamer.EmitLabel(SectionBegin);
1843
1844   // Emit the full data.
1845   AT.Emit(Asm, SectionBegin, this);
1846 }
1847
1848 /// emitAccelTypes() - Emit type dies into a hashed accelerator table.
1849 void DwarfDebug::emitAccelTypes() {
1850   DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1851                                            dwarf::DW_FORM_data4));
1852   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1853          E = CUMap.end(); I != E; ++I) {
1854     CompileUnit *TheCU = I->second;
1855     const StringMap<DIE*> &Names = TheCU->getAccelTypes();
1856     for (StringMap<DIE*>::const_iterator
1857            GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1858       const char *Name = GI->getKeyData();
1859       DIE *Entity = GI->second;
1860       AT.AddName(Name, Entity);
1861     }
1862   }
1863
1864   AT.FinalizeTable(Asm, "types");
1865   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1866                                  .getDwarfAccelTypesSection());
1867   MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1868   Asm->OutStreamer.EmitLabel(SectionBegin);
1869
1870   // Emit the full data.
1871   AT.Emit(Asm, SectionBegin, this);
1872 }
1873
1874 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1875 ///
1876 void DwarfDebug::emitDebugPubNames() {
1877   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1878          E = CUMap.end(); I != E; ++I) {
1879     CompileUnit *TheCU = I->second;
1880     // Start the dwarf pubnames section.
1881     Asm->OutStreamer.SwitchSection(
1882       Asm->getObjFileLowering().getDwarfPubNamesSection());
1883
1884     Asm->OutStreamer.AddComment("Length of Public Names Info");
1885     Asm->EmitLabelDifference(
1886       Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1887       Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1888
1889     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1890                                                   TheCU->getID()));
1891
1892     Asm->OutStreamer.AddComment("DWARF Version");
1893     Asm->EmitInt16(dwarf::DWARF_VERSION);
1894
1895     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1896     Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1897                            DwarfInfoSectionSym);
1898
1899     Asm->OutStreamer.AddComment("Compilation Unit Length");
1900     Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1901                              Asm->GetTempSymbol("info_begin", TheCU->getID()),
1902                              4);
1903
1904     const StringMap<DIE*> &Globals = TheCU->getGlobals();
1905     for (StringMap<DIE*>::const_iterator
1906            GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1907       const char *Name = GI->getKeyData();
1908       DIE *Entity = GI->second;
1909
1910       Asm->OutStreamer.AddComment("DIE offset");
1911       Asm->EmitInt32(Entity->getOffset());
1912
1913       if (Asm->isVerbose())
1914         Asm->OutStreamer.AddComment("External Name");
1915       Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1916     }
1917
1918     Asm->OutStreamer.AddComment("End Mark");
1919     Asm->EmitInt32(0);
1920     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1921                                                   TheCU->getID()));
1922   }
1923 }
1924
1925 void DwarfDebug::emitDebugPubTypes() {
1926   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1927          E = CUMap.end(); I != E; ++I) {
1928     CompileUnit *TheCU = I->second;
1929     // Start the dwarf pubtypes section.
1930     Asm->OutStreamer.SwitchSection(
1931       Asm->getObjFileLowering().getDwarfPubTypesSection());
1932     Asm->OutStreamer.AddComment("Length of Public Types Info");
1933     Asm->EmitLabelDifference(
1934       Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1935       Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1936
1937     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1938                                                   TheCU->getID()));
1939
1940     if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1941     Asm->EmitInt16(dwarf::DWARF_VERSION);
1942
1943     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1944     Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1945                            DwarfInfoSectionSym);
1946
1947     Asm->OutStreamer.AddComment("Compilation Unit Length");
1948     Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1949                              Asm->GetTempSymbol("info_begin", TheCU->getID()),
1950                              4);
1951
1952     const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1953     for (StringMap<DIE*>::const_iterator
1954            GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1955       const char *Name = GI->getKeyData();
1956       DIE *Entity = GI->second;
1957
1958       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1959       Asm->EmitInt32(Entity->getOffset());
1960
1961       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1962       Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1963     }
1964
1965     Asm->OutStreamer.AddComment("End Mark");
1966     Asm->EmitInt32(0);
1967     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1968                                                   TheCU->getID()));
1969   }
1970 }
1971
1972 /// emitDebugStr - Emit visible names into a debug str section.
1973 ///
1974 void DwarfDebug::emitDebugStr() {
1975   // Check to see if it is worth the effort.
1976   if (StringPool.empty()) return;
1977
1978   // Start the dwarf str section.
1979   Asm->OutStreamer.SwitchSection(
1980                                 Asm->getObjFileLowering().getDwarfStrSection());
1981
1982   // Get all of the string pool entries and put them in an array by their ID so
1983   // we can sort them.
1984   SmallVector<std::pair<unsigned,
1985       StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1986
1987   for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1988        I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1989     Entries.push_back(std::make_pair(I->second.second, &*I));
1990
1991   array_pod_sort(Entries.begin(), Entries.end());
1992
1993   for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1994     // Emit a label for reference from debug information entries.
1995     Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1996
1997     // Emit the string itself.
1998     Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1999     Asm->OutStreamer.EmitZeros(1, 0);
2000   }
2001 }
2002
2003 /// emitDebugLoc - Emit visible names into a debug loc section.
2004 ///
2005 void DwarfDebug::emitDebugLoc() {
2006   if (DotDebugLocEntries.empty())
2007     return;
2008
2009   for (SmallVector<DotDebugLocEntry, 4>::iterator
2010          I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2011        I != E; ++I) {
2012     DotDebugLocEntry &Entry = *I;
2013     if (I + 1 != DotDebugLocEntries.end())
2014       Entry.Merge(I+1);
2015   }
2016
2017   // Start the dwarf loc section.
2018   Asm->OutStreamer.SwitchSection(
2019     Asm->getObjFileLowering().getDwarfLocSection());
2020   unsigned char Size = Asm->getTargetData().getPointerSize();
2021   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2022   unsigned index = 1;
2023   for (SmallVector<DotDebugLocEntry, 4>::iterator
2024          I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2025        I != E; ++I, ++index) {
2026     DotDebugLocEntry &Entry = *I;
2027     if (Entry.isMerged()) continue;
2028     if (Entry.isEmpty()) {
2029       Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2030       Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2031       Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2032     } else {
2033       Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2034       Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2035       DIVariable DV(Entry.Variable);
2036       Asm->OutStreamer.AddComment("Loc expr size");
2037       MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2038       MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2039       Asm->EmitLabelDifference(end, begin, 2);
2040       Asm->OutStreamer.EmitLabel(begin);
2041       if (Entry.isInt()) {
2042         DIBasicType BTy(DV.getType());
2043         if (BTy.Verify() &&
2044             (BTy.getEncoding()  == dwarf::DW_ATE_signed 
2045              || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2046           Asm->OutStreamer.AddComment("DW_OP_consts");
2047           Asm->EmitInt8(dwarf::DW_OP_consts);
2048           Asm->EmitSLEB128(Entry.getInt());
2049         } else {
2050           Asm->OutStreamer.AddComment("DW_OP_constu");
2051           Asm->EmitInt8(dwarf::DW_OP_constu);
2052           Asm->EmitULEB128(Entry.getInt());
2053         }
2054       } else if (Entry.isLocation()) {
2055         if (!DV.hasComplexAddress()) 
2056           // Regular entry.
2057           Asm->EmitDwarfRegOp(Entry.Loc);
2058         else {
2059           // Complex address entry.
2060           unsigned N = DV.getNumAddrElements();
2061           unsigned i = 0;
2062           if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2063             if (Entry.Loc.getOffset()) {
2064               i = 2;
2065               Asm->EmitDwarfRegOp(Entry.Loc);
2066               Asm->OutStreamer.AddComment("DW_OP_deref");
2067               Asm->EmitInt8(dwarf::DW_OP_deref);
2068               Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2069               Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2070               Asm->EmitSLEB128(DV.getAddrElement(1));
2071             } else {
2072               // If first address element is OpPlus then emit
2073               // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2074               MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2075               Asm->EmitDwarfRegOp(Loc);
2076               i = 2;
2077             }
2078           } else {
2079             Asm->EmitDwarfRegOp(Entry.Loc);
2080           }
2081           
2082           // Emit remaining complex address elements.
2083           for (; i < N; ++i) {
2084             uint64_t Element = DV.getAddrElement(i);
2085             if (Element == DIBuilder::OpPlus) {
2086               Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2087               Asm->EmitULEB128(DV.getAddrElement(++i));
2088             } else if (Element == DIBuilder::OpDeref)
2089               Asm->EmitInt8(dwarf::DW_OP_deref);
2090             else llvm_unreachable("unknown Opcode found in complex address");
2091           }
2092         }
2093       }
2094       // else ... ignore constant fp. There is not any good way to
2095       // to represent them here in dwarf.
2096       Asm->OutStreamer.EmitLabel(end);
2097     }
2098   }
2099 }
2100
2101 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2102 ///
2103 void DwarfDebug::EmitDebugARanges() {
2104   // Start the dwarf aranges section.
2105   Asm->OutStreamer.SwitchSection(
2106                           Asm->getObjFileLowering().getDwarfARangesSection());
2107 }
2108
2109 /// emitDebugRanges - Emit visible names into a debug ranges section.
2110 ///
2111 void DwarfDebug::emitDebugRanges() {
2112   // Start the dwarf ranges section.
2113   Asm->OutStreamer.SwitchSection(
2114     Asm->getObjFileLowering().getDwarfRangesSection());
2115   unsigned char Size = Asm->getTargetData().getPointerSize();
2116   for (SmallVector<const MCSymbol *, 8>::iterator
2117          I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2118        I != E; ++I) {
2119     if (*I)
2120       Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2121     else
2122       Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2123   }
2124 }
2125
2126 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2127 ///
2128 void DwarfDebug::emitDebugMacInfo() {
2129   if (const MCSection *LineInfo =
2130       Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2131     // Start the dwarf macinfo section.
2132     Asm->OutStreamer.SwitchSection(LineInfo);
2133   }
2134 }
2135
2136 /// emitDebugInlineInfo - Emit inline info using following format.
2137 /// Section Header:
2138 /// 1. length of section
2139 /// 2. Dwarf version number
2140 /// 3. address size.
2141 ///
2142 /// Entries (one "entry" for each function that was inlined):
2143 ///
2144 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2145 ///   otherwise offset into __debug_str for regular function name.
2146 /// 2. offset into __debug_str section for regular function name.
2147 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2148 /// instances for the function.
2149 ///
2150 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2151 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2152 /// __debug_info section, and the low_pc is the starting address for the
2153 /// inlining instance.
2154 void DwarfDebug::emitDebugInlineInfo() {
2155   if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
2156     return;
2157
2158   if (!FirstCU)
2159     return;
2160
2161   Asm->OutStreamer.SwitchSection(
2162                         Asm->getObjFileLowering().getDwarfDebugInlineSection());
2163
2164   Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2165   Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2166                            Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2167
2168   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2169
2170   Asm->OutStreamer.AddComment("Dwarf Version");
2171   Asm->EmitInt16(dwarf::DWARF_VERSION);
2172   Asm->OutStreamer.AddComment("Address Size (in bytes)");
2173   Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2174
2175   for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2176          E = InlinedSPNodes.end(); I != E; ++I) {
2177
2178     const MDNode *Node = *I;
2179     DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2180       = InlineInfo.find(Node);
2181     SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2182     DISubprogram SP(Node);
2183     StringRef LName = SP.getLinkageName();
2184     StringRef Name = SP.getName();
2185
2186     Asm->OutStreamer.AddComment("MIPS linkage name");
2187     if (LName.empty()) {
2188       Asm->OutStreamer.EmitBytes(Name, 0);
2189       Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2190     } else
2191       Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2192                              DwarfStrSectionSym);
2193
2194     Asm->OutStreamer.AddComment("Function name");
2195     Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2196     Asm->EmitULEB128(Labels.size(), "Inline count");
2197
2198     for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2199            LE = Labels.end(); LI != LE; ++LI) {
2200       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2201       Asm->EmitInt32(LI->second->getOffset());
2202
2203       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2204       Asm->OutStreamer.EmitSymbolValue(LI->first,
2205                                        Asm->getTargetData().getPointerSize(),0);
2206     }
2207   }
2208
2209   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2210 }