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