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