1 //===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp --*- C++ -*--===//
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 Microsoft CodeView debug info.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeViewDebug.h"
15 #include "llvm/DebugInfo/CodeView/CodeView.h"
16 #include "llvm/DebugInfo/CodeView/Line.h"
17 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
18 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
19 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCSectionCOFF.h"
22 #include "llvm/MC/MCSymbol.h"
23 #include "llvm/Support/COFF.h"
24 #include "llvm/Target/TargetSubtargetInfo.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
26 #include "llvm/Target/TargetFrameLowering.h"
27 
28 using namespace llvm;
29 using namespace llvm::codeview;
30 
31 CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
32     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
33   // If module doesn't have named metadata anchors or COFF debug section
34   // is not available, skip any debug info related stuff.
35   if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
36       !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
37     Asm = nullptr;
38     return;
39   }
40 
41   // Tell MMI that we have debug info.
42   MMI->setDebugInfoAvailability(true);
43 }
44 
45 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
46   std::string &Filepath = FileToFilepathMap[File];
47   if (!Filepath.empty())
48     return Filepath;
49 
50   StringRef Dir = File->getDirectory(), Filename = File->getFilename();
51 
52   // Clang emits directory and relative filename info into the IR, but CodeView
53   // operates on full paths.  We could change Clang to emit full paths too, but
54   // that would increase the IR size and probably not needed for other users.
55   // For now, just concatenate and canonicalize the path here.
56   if (Filename.find(':') == 1)
57     Filepath = Filename;
58   else
59     Filepath = (Dir + "\\" + Filename).str();
60 
61   // Canonicalize the path.  We have to do it textually because we may no longer
62   // have access the file in the filesystem.
63   // First, replace all slashes with backslashes.
64   std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
65 
66   // Remove all "\.\" with "\".
67   size_t Cursor = 0;
68   while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
69     Filepath.erase(Cursor, 2);
70 
71   // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
72   // path should be well-formatted, e.g. start with a drive letter, etc.
73   Cursor = 0;
74   while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
75     // Something's wrong if the path starts with "\..\", abort.
76     if (Cursor == 0)
77       break;
78 
79     size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
80     if (PrevSlash == std::string::npos)
81       // Something's wrong, abort.
82       break;
83 
84     Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
85     // The next ".." might be following the one we've just erased.
86     Cursor = PrevSlash;
87   }
88 
89   // Remove all duplicate backslashes.
90   Cursor = 0;
91   while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
92     Filepath.erase(Cursor, 1);
93 
94   return Filepath;
95 }
96 
97 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
98   unsigned NextId = FileIdMap.size() + 1;
99   auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
100   if (Insertion.second) {
101     // We have to compute the full filepath and emit a .cv_file directive.
102     StringRef FullPath = getFullFilepath(F);
103     NextId = OS.EmitCVFileDirective(NextId, FullPath);
104     assert(NextId == FileIdMap.size() && ".cv_file directive failed");
105   }
106   return Insertion.first->second;
107 }
108 
109 CodeViewDebug::InlineSite &
110 CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
111                              const DISubprogram *Inlinee) {
112   auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
113   InlineSite *Site = &SiteInsertion.first->second;
114   if (SiteInsertion.second) {
115     Site->SiteFuncId = NextFuncId++;
116     Site->Inlinee = Inlinee;
117     InlinedSubprograms.insert(Inlinee);
118     recordFuncIdForSubprogram(Inlinee);
119   }
120   return *Site;
121 }
122 
123 TypeIndex CodeViewDebug::getGenericFunctionTypeIndex() {
124   if (VoidFnTyIdx.getIndex() != 0)
125     return VoidFnTyIdx;
126 
127   ArrayRef<TypeIndex> NoArgs;
128   ArgListRecord ArgListRec(TypeRecordKind::ArgList, NoArgs);
129   TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
130 
131   ProcedureRecord Procedure(TypeIndex::Void(), CallingConvention::NearC,
132                             FunctionOptions::None, 0, ArgListIndex);
133   VoidFnTyIdx = TypeTable.writeProcedure(Procedure);
134   return VoidFnTyIdx;
135 }
136 
137 void CodeViewDebug::recordFuncIdForSubprogram(const DISubprogram *SP) {
138   TypeIndex ParentScope = TypeIndex(0);
139   StringRef DisplayName = SP->getDisplayName();
140   FuncIdRecord FuncId(ParentScope, getGenericFunctionTypeIndex(), DisplayName);
141   TypeIndex TI = TypeTable.writeFuncId(FuncId);
142   TypeIndices[SP] = TI;
143 }
144 
145 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
146                                         const DILocation *InlinedAt) {
147   if (InlinedAt) {
148     // This variable was inlined. Associate it with the InlineSite.
149     const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
150     InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
151     Site.InlinedLocals.emplace_back(Var);
152   } else {
153     // This variable goes in the main ProcSym.
154     CurFn->Locals.emplace_back(Var);
155   }
156 }
157 
158 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
159                                const DILocation *Loc) {
160   auto B = Locs.begin(), E = Locs.end();
161   if (std::find(B, E, Loc) == E)
162     Locs.push_back(Loc);
163 }
164 
165 void CodeViewDebug::maybeRecordLocation(DebugLoc DL,
166                                         const MachineFunction *MF) {
167   // Skip this instruction if it has the same location as the previous one.
168   if (DL == CurFn->LastLoc)
169     return;
170 
171   const DIScope *Scope = DL.get()->getScope();
172   if (!Scope)
173     return;
174 
175   // Skip this line if it is longer than the maximum we can record.
176   LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
177   if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
178       LI.isNeverStepInto())
179     return;
180 
181   ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
182   if (CI.getStartColumn() != DL.getCol())
183     return;
184 
185   if (!CurFn->HaveLineInfo)
186     CurFn->HaveLineInfo = true;
187   unsigned FileId = 0;
188   if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
189     FileId = CurFn->LastFileId;
190   else
191     FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
192   CurFn->LastLoc = DL;
193 
194   unsigned FuncId = CurFn->FuncId;
195   if (const DILocation *SiteLoc = DL->getInlinedAt()) {
196     const DILocation *Loc = DL.get();
197 
198     // If this location was actually inlined from somewhere else, give it the ID
199     // of the inline call site.
200     FuncId =
201         getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
202 
203     // Ensure we have links in the tree of inline call sites.
204     bool FirstLoc = true;
205     while ((SiteLoc = Loc->getInlinedAt())) {
206       InlineSite &Site =
207           getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
208       if (!FirstLoc)
209         addLocIfNotPresent(Site.ChildSites, Loc);
210       FirstLoc = false;
211       Loc = SiteLoc;
212     }
213     addLocIfNotPresent(CurFn->ChildSites, Loc);
214   }
215 
216   OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
217                         /*PrologueEnd=*/false,
218                         /*IsStmt=*/false, DL->getFilename());
219 }
220 
221 void CodeViewDebug::emitCodeViewMagicVersion() {
222   OS.EmitValueToAlignment(4);
223   OS.AddComment("Debug section magic");
224   OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
225 }
226 
227 void CodeViewDebug::endModule() {
228   if (FnDebugInfo.empty())
229     return;
230 
231   emitTypeInformation();
232 
233   assert(Asm != nullptr);
234 
235   // The COFF .debug$S section consists of several subsections, each starting
236   // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
237   // of the payload followed by the payload itself.  The subsections are 4-byte
238   // aligned.
239 
240   // Make a subsection for all the inlined subprograms.
241   emitInlineeLinesSubsection();
242 
243   // Emit per-function debug information.
244   for (auto &P : FnDebugInfo)
245     emitDebugInfoForFunction(P.first, P.second);
246 
247   // Switch back to the generic .debug$S section after potentially processing
248   // comdat symbol sections.
249   switchToDebugSectionForSymbol(nullptr);
250 
251   // This subsection holds a file index to offset in string table table.
252   OS.AddComment("File index to string table offset subsection");
253   OS.EmitCVFileChecksumsDirective();
254 
255   // This subsection holds the string table.
256   OS.AddComment("String table");
257   OS.EmitCVStringTableDirective();
258 
259   clear();
260 }
261 
262 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
263   // Microsoft's linker seems to have trouble with symbol names longer than
264   // 0xffd8 bytes.
265   S = S.substr(0, 0xffd8);
266   SmallString<32> NullTerminatedString(S);
267   NullTerminatedString.push_back('\0');
268   OS.EmitBytes(NullTerminatedString);
269 }
270 
271 void CodeViewDebug::emitTypeInformation() {
272   // Do nothing if we have no debug info or if no non-trivial types were emitted
273   // to TypeTable during codegen.
274   NamedMDNode *CU_Nodes =
275       MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
276   if (!CU_Nodes)
277     return;
278   if (TypeTable.empty())
279     return;
280 
281   // Start the .debug$T section with 0x4.
282   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
283   emitCodeViewMagicVersion();
284 
285   TypeTable.ForEachRecord(
286       [&](TypeIndex Index, const MemoryTypeTableBuilder::Record *R) {
287         // Each record should be 4 byte aligned. We achieve that by emitting
288         // LF_PAD padding bytes. The on-disk record size includes the padding
289         // bytes so that consumers don't have to skip past them.
290         uint64_t RecordSize = R->size() + 2;
291         uint64_t AlignedSize = alignTo(RecordSize, 4);
292         uint64_t AlignedRecordSize = AlignedSize - 2;
293         assert(AlignedRecordSize < (1 << 16) && "type record size overflow");
294         OS.AddComment("Type record length");
295         OS.EmitIntValue(AlignedRecordSize, 2);
296         OS.AddComment("Type record data");
297         OS.EmitBytes(StringRef(R->data(), R->size()));
298         // Pad the record with LF_PAD bytes.
299         for (unsigned I = AlignedSize - RecordSize; I > 0; --I)
300           OS.EmitIntValue(LF_PAD0 + I, 1);
301       });
302 }
303 
304 void CodeViewDebug::emitInlineeLinesSubsection() {
305   if (InlinedSubprograms.empty())
306     return;
307 
308   // Use the generic .debug$S section.
309   switchToDebugSectionForSymbol(nullptr);
310 
311   MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
312            *InlineEnd = MMI->getContext().createTempSymbol();
313 
314   OS.AddComment("Inlinee lines subsection");
315   OS.EmitIntValue(unsigned(ModuleSubstreamKind::InlineeLines), 4);
316   OS.AddComment("Subsection size");
317   OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 4);
318   OS.EmitLabel(InlineBegin);
319 
320   // We don't provide any extra file info.
321   // FIXME: Find out if debuggers use this info.
322   OS.AddComment("Inlinee lines signature");
323   OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
324 
325   for (const DISubprogram *SP : InlinedSubprograms) {
326     assert(TypeIndices.count(SP));
327     TypeIndex InlineeIdx = TypeIndices[SP];
328 
329     OS.AddBlankLine();
330     unsigned FileId = maybeRecordFile(SP->getFile());
331     OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
332                   SP->getFilename() + Twine(':') + Twine(SP->getLine()));
333     OS.AddBlankLine();
334     // The filechecksum table uses 8 byte entries for now, and file ids start at
335     // 1.
336     unsigned FileOffset = (FileId - 1) * 8;
337     OS.AddComment("Type index of inlined function");
338     OS.EmitIntValue(InlineeIdx.getIndex(), 4);
339     OS.AddComment("Offset into filechecksum table");
340     OS.EmitIntValue(FileOffset, 4);
341     OS.AddComment("Starting line number");
342     OS.EmitIntValue(SP->getLine(), 4);
343   }
344 
345   OS.EmitLabel(InlineEnd);
346 }
347 
348 void CodeViewDebug::collectInlineSiteChildren(
349     SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
350     const InlineSite &Site) {
351   for (const DILocation *ChildSiteLoc : Site.ChildSites) {
352     auto I = FI.InlineSites.find(ChildSiteLoc);
353     const InlineSite &ChildSite = I->second;
354     Children.push_back(ChildSite.SiteFuncId);
355     collectInlineSiteChildren(Children, FI, ChildSite);
356   }
357 }
358 
359 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
360                                         const DILocation *InlinedAt,
361                                         const InlineSite &Site) {
362   MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
363            *InlineEnd = MMI->getContext().createTempSymbol();
364 
365   assert(TypeIndices.count(Site.Inlinee));
366   TypeIndex InlineeIdx = TypeIndices[Site.Inlinee];
367 
368   // SymbolRecord
369   OS.AddComment("Record length");
370   OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2);   // RecordLength
371   OS.EmitLabel(InlineBegin);
372   OS.AddComment("Record kind: S_INLINESITE");
373   OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
374 
375   OS.AddComment("PtrParent");
376   OS.EmitIntValue(0, 4);
377   OS.AddComment("PtrEnd");
378   OS.EmitIntValue(0, 4);
379   OS.AddComment("Inlinee type index");
380   OS.EmitIntValue(InlineeIdx.getIndex(), 4);
381 
382   unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
383   unsigned StartLineNum = Site.Inlinee->getLine();
384   SmallVector<unsigned, 3> SecondaryFuncIds;
385   collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
386 
387   OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
388                                     FI.Begin, FI.End, SecondaryFuncIds);
389 
390   OS.EmitLabel(InlineEnd);
391 
392   for (const LocalVariable &Var : Site.InlinedLocals)
393     emitLocalVariable(Var);
394 
395   // Recurse on child inlined call sites before closing the scope.
396   for (const DILocation *ChildSite : Site.ChildSites) {
397     auto I = FI.InlineSites.find(ChildSite);
398     assert(I != FI.InlineSites.end() &&
399            "child site not in function inline site map");
400     emitInlinedCallSite(FI, ChildSite, I->second);
401   }
402 
403   // Close the scope.
404   OS.AddComment("Record length");
405   OS.EmitIntValue(2, 2);                                  // RecordLength
406   OS.AddComment("Record kind: S_INLINESITE_END");
407   OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
408 }
409 
410 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
411   // If we have a symbol, it may be in a section that is COMDAT. If so, find the
412   // comdat key. A section may be comdat because of -ffunction-sections or
413   // because it is comdat in the IR.
414   MCSectionCOFF *GVSec =
415       GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
416   const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
417 
418   MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
419       Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
420   DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
421 
422   OS.SwitchSection(DebugSec);
423 
424   // Emit the magic version number if this is the first time we've switched to
425   // this section.
426   if (ComdatDebugSections.insert(DebugSec).second)
427     emitCodeViewMagicVersion();
428 }
429 
430 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
431                                              FunctionInfo &FI) {
432   // For each function there is a separate subsection
433   // which holds the PC to file:line table.
434   const MCSymbol *Fn = Asm->getSymbol(GV);
435   assert(Fn);
436 
437   // Switch to the to a comdat section, if appropriate.
438   switchToDebugSectionForSymbol(Fn);
439 
440   StringRef FuncName;
441   if (auto *SP = GV->getSubprogram())
442     FuncName = SP->getDisplayName();
443 
444   // If our DISubprogram name is empty, use the mangled name.
445   if (FuncName.empty())
446     FuncName = GlobalValue::getRealLinkageName(GV->getName());
447 
448   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
449   MCSymbol *SymbolsBegin = MMI->getContext().createTempSymbol(),
450            *SymbolsEnd = MMI->getContext().createTempSymbol();
451   OS.AddComment("Symbol subsection for " + Twine(FuncName));
452   OS.EmitIntValue(unsigned(ModuleSubstreamKind::Symbols), 4);
453   OS.AddComment("Subsection size");
454   OS.emitAbsoluteSymbolDiff(SymbolsEnd, SymbolsBegin, 4);
455   OS.EmitLabel(SymbolsBegin);
456   {
457     MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
458              *ProcRecordEnd = MMI->getContext().createTempSymbol();
459     OS.AddComment("Record length");
460     OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
461     OS.EmitLabel(ProcRecordBegin);
462 
463     OS.AddComment("Record kind: S_GPROC32_ID");
464     OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
465 
466     // These fields are filled in by tools like CVPACK which run after the fact.
467     OS.AddComment("PtrParent");
468     OS.EmitIntValue(0, 4);
469     OS.AddComment("PtrEnd");
470     OS.EmitIntValue(0, 4);
471     OS.AddComment("PtrNext");
472     OS.EmitIntValue(0, 4);
473     // This is the important bit that tells the debugger where the function
474     // code is located and what's its size:
475     OS.AddComment("Code size");
476     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
477     OS.AddComment("Offset after prologue");
478     OS.EmitIntValue(0, 4);
479     OS.AddComment("Offset before epilogue");
480     OS.EmitIntValue(0, 4);
481     OS.AddComment("Function type index");
482     OS.EmitIntValue(0, 4);
483     OS.AddComment("Function section relative address");
484     OS.EmitCOFFSecRel32(Fn);
485     OS.AddComment("Function section index");
486     OS.EmitCOFFSectionIndex(Fn);
487     OS.AddComment("Flags");
488     OS.EmitIntValue(0, 1);
489     // Emit the function display name as a null-terminated string.
490     OS.AddComment("Function name");
491     // Truncate the name so we won't overflow the record length field.
492     emitNullTerminatedSymbolName(OS, FuncName);
493     OS.EmitLabel(ProcRecordEnd);
494 
495     for (const LocalVariable &Var : FI.Locals)
496       emitLocalVariable(Var);
497 
498     // Emit inlined call site information. Only emit functions inlined directly
499     // into the parent function. We'll emit the other sites recursively as part
500     // of their parent inline site.
501     for (const DILocation *InlinedAt : FI.ChildSites) {
502       auto I = FI.InlineSites.find(InlinedAt);
503       assert(I != FI.InlineSites.end() &&
504              "child site not in function inline site map");
505       emitInlinedCallSite(FI, InlinedAt, I->second);
506     }
507 
508     // We're done with this function.
509     OS.AddComment("Record length");
510     OS.EmitIntValue(0x0002, 2);
511     OS.AddComment("Record kind: S_PROC_ID_END");
512     OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
513   }
514   OS.EmitLabel(SymbolsEnd);
515   // Every subsection must be aligned to a 4-byte boundary.
516   OS.EmitValueToAlignment(4);
517 
518   // We have an assembler directive that takes care of the whole line table.
519   OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
520 }
521 
522 CodeViewDebug::LocalVarDefRange
523 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
524   LocalVarDefRange DR;
525   DR.InMemory = -1;
526   DR.DataOffset = Offset;
527   assert(DR.DataOffset == Offset && "truncation");
528   DR.StructOffset = 0;
529   DR.CVRegister = CVRegister;
530   return DR;
531 }
532 
533 CodeViewDebug::LocalVarDefRange
534 CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
535   LocalVarDefRange DR;
536   DR.InMemory = 0;
537   DR.DataOffset = 0;
538   DR.StructOffset = 0;
539   DR.CVRegister = CVRegister;
540   return DR;
541 }
542 
543 void CodeViewDebug::collectVariableInfoFromMMITable(
544     DenseSet<InlinedVariable> &Processed) {
545   const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
546   const TargetFrameLowering *TFI = TSI.getFrameLowering();
547   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
548 
549   for (const MachineModuleInfo::VariableDbgInfo &VI :
550        MMI->getVariableDbgInfo()) {
551     if (!VI.Var)
552       continue;
553     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
554            "Expected inlined-at fields to agree");
555 
556     Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
557     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
558 
559     // If variable scope is not found then skip this variable.
560     if (!Scope)
561       continue;
562 
563     // Get the frame register used and the offset.
564     unsigned FrameReg = 0;
565     int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
566     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
567 
568     // Calculate the label ranges.
569     LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
570     for (const InsnRange &Range : Scope->getRanges()) {
571       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
572       const MCSymbol *End = getLabelAfterInsn(Range.second);
573       End = End ? End : Asm->getFunctionEnd();
574       DefRange.Ranges.emplace_back(Begin, End);
575     }
576 
577     LocalVariable Var;
578     Var.DIVar = VI.Var;
579     Var.DefRanges.emplace_back(std::move(DefRange));
580     recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
581   }
582 }
583 
584 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
585   DenseSet<InlinedVariable> Processed;
586   // Grab the variable info that was squirreled away in the MMI side-table.
587   collectVariableInfoFromMMITable(Processed);
588 
589   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
590 
591   for (const auto &I : DbgValues) {
592     InlinedVariable IV = I.first;
593     if (Processed.count(IV))
594       continue;
595     const DILocalVariable *DIVar = IV.first;
596     const DILocation *InlinedAt = IV.second;
597 
598     // Instruction ranges, specifying where IV is accessible.
599     const auto &Ranges = I.second;
600 
601     LexicalScope *Scope = nullptr;
602     if (InlinedAt)
603       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
604     else
605       Scope = LScopes.findLexicalScope(DIVar->getScope());
606     // If variable scope is not found then skip this variable.
607     if (!Scope)
608       continue;
609 
610     LocalVariable Var;
611     Var.DIVar = DIVar;
612 
613     // Calculate the definition ranges.
614     for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
615       const InsnRange &Range = *I;
616       const MachineInstr *DVInst = Range.first;
617       assert(DVInst->isDebugValue() && "Invalid History entry");
618       const DIExpression *DIExpr = DVInst->getDebugExpression();
619 
620       // Bail if there is a complex DWARF expression for now.
621       if (DIExpr && DIExpr->getNumElements() > 0)
622         continue;
623 
624       // Bail if operand 0 is not a valid register. This means the variable is a
625       // simple constant, or is described by a complex expression.
626       // FIXME: Find a way to represent constant variables, since they are
627       // relatively common.
628       unsigned Reg =
629           DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
630       if (Reg == 0)
631         continue;
632 
633       // Handle the two cases we can handle: indirect in memory and in register.
634       bool IsIndirect = DVInst->getOperand(1).isImm();
635       unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
636       {
637         LocalVarDefRange DefRange;
638         if (IsIndirect) {
639           int64_t Offset = DVInst->getOperand(1).getImm();
640           DefRange = createDefRangeMem(CVReg, Offset);
641         } else {
642           DefRange = createDefRangeReg(CVReg);
643         }
644         if (Var.DefRanges.empty() ||
645             Var.DefRanges.back().isDifferentLocation(DefRange)) {
646           Var.DefRanges.emplace_back(std::move(DefRange));
647         }
648       }
649 
650       // Compute the label range.
651       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
652       const MCSymbol *End = getLabelAfterInsn(Range.second);
653       if (!End) {
654         if (std::next(I) != E)
655           End = getLabelBeforeInsn(std::next(I)->first);
656         else
657           End = Asm->getFunctionEnd();
658       }
659 
660       // If the last range end is our begin, just extend the last range.
661       // Otherwise make a new range.
662       SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
663           Var.DefRanges.back().Ranges;
664       if (!Ranges.empty() && Ranges.back().second == Begin)
665         Ranges.back().second = End;
666       else
667         Ranges.emplace_back(Begin, End);
668 
669       // FIXME: Do more range combining.
670     }
671 
672     recordLocalVariable(std::move(Var), InlinedAt);
673   }
674 }
675 
676 void CodeViewDebug::beginFunction(const MachineFunction *MF) {
677   assert(!CurFn && "Can't process two functions at once!");
678 
679   if (!Asm || !MMI->hasDebugInfo())
680     return;
681 
682   DebugHandlerBase::beginFunction(MF);
683 
684   const Function *GV = MF->getFunction();
685   assert(FnDebugInfo.count(GV) == false);
686   CurFn = &FnDebugInfo[GV];
687   CurFn->FuncId = NextFuncId++;
688   CurFn->Begin = Asm->getFunctionBegin();
689 
690   // Find the end of the function prolog.  First known non-DBG_VALUE and
691   // non-frame setup location marks the beginning of the function body.
692   // FIXME: is there a simpler a way to do this? Can we just search
693   // for the first instruction of the function, not the last of the prolog?
694   DebugLoc PrologEndLoc;
695   bool EmptyPrologue = true;
696   for (const auto &MBB : *MF) {
697     for (const auto &MI : MBB) {
698       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
699           MI.getDebugLoc()) {
700         PrologEndLoc = MI.getDebugLoc();
701         break;
702       } else if (!MI.isDebugValue()) {
703         EmptyPrologue = false;
704       }
705     }
706   }
707 
708   // Record beginning of function if we have a non-empty prologue.
709   if (PrologEndLoc && !EmptyPrologue) {
710     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
711     maybeRecordLocation(FnStartDL, MF);
712   }
713 }
714 
715 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
716   // LocalSym record, see SymbolRecord.h for more info.
717   MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
718            *LocalEnd = MMI->getContext().createTempSymbol();
719   OS.AddComment("Record length");
720   OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
721   OS.EmitLabel(LocalBegin);
722 
723   OS.AddComment("Record kind: S_LOCAL");
724   OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
725 
726   LocalSymFlags Flags = LocalSymFlags::None;
727   if (Var.DIVar->isParameter())
728     Flags |= LocalSymFlags::IsParameter;
729   if (Var.DefRanges.empty())
730     Flags |= LocalSymFlags::IsOptimizedOut;
731 
732   OS.AddComment("TypeIndex");
733   OS.EmitIntValue(TypeIndex::Int32().getIndex(), 4);
734   OS.AddComment("Flags");
735   OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
736   // Truncate the name so we won't overflow the record length field.
737   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
738   OS.EmitLabel(LocalEnd);
739 
740   // Calculate the on disk prefix of the appropriate def range record. The
741   // records and on disk formats are described in SymbolRecords.h. BytePrefix
742   // should be big enough to hold all forms without memory allocation.
743   SmallString<20> BytePrefix;
744   for (const LocalVarDefRange &DefRange : Var.DefRanges) {
745     BytePrefix.clear();
746     // FIXME: Handle bitpieces.
747     if (DefRange.StructOffset != 0)
748       continue;
749 
750     if (DefRange.InMemory) {
751       DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
752                                  0, 0, ArrayRef<LocalVariableAddrGap>());
753       ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
754       BytePrefix +=
755           StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
756       BytePrefix +=
757           StringRef(reinterpret_cast<const char *>(&Sym.Header),
758                     sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
759     } else {
760       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
761       // Unclear what matters here.
762       DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
763                               ArrayRef<LocalVariableAddrGap>());
764       ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
765       BytePrefix +=
766           StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
767       BytePrefix +=
768           StringRef(reinterpret_cast<const char *>(&Sym.Header),
769                     sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
770     }
771     OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
772   }
773 }
774 
775 void CodeViewDebug::endFunction(const MachineFunction *MF) {
776   if (!Asm || !CurFn)  // We haven't created any debug info for this function.
777     return;
778 
779   const Function *GV = MF->getFunction();
780   assert(FnDebugInfo.count(GV));
781   assert(CurFn == &FnDebugInfo[GV]);
782 
783   collectVariableInfo(GV->getSubprogram());
784 
785   DebugHandlerBase::endFunction(MF);
786 
787   // Don't emit anything if we don't have any line tables.
788   if (!CurFn->HaveLineInfo) {
789     FnDebugInfo.erase(GV);
790     CurFn = nullptr;
791     return;
792   }
793 
794   CurFn->End = Asm->getFunctionEnd();
795 
796   CurFn = nullptr;
797 }
798 
799 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
800   DebugHandlerBase::beginInstruction(MI);
801 
802   // Ignore DBG_VALUE locations and function prologue.
803   if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
804     return;
805   DebugLoc DL = MI->getDebugLoc();
806   if (DL == PrevInstLoc || !DL)
807     return;
808   maybeRecordLocation(DL, Asm->MF);
809 }
810