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