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