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