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