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