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