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