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/MCSymbol.h"
22 #include "llvm/Support/COFF.h"
23 #include "llvm/Target/TargetSubtargetInfo.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/Target/TargetFrameLowering.h"
26 
27 using namespace llvm;
28 using namespace llvm::codeview;
29 
30 CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
31     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
32   // If module doesn't have named metadata anchors or COFF debug section
33   // is not available, skip any debug info related stuff.
34   if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
35       !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
36     Asm = nullptr;
37     return;
38   }
39 
40   // Tell MMI that we have debug info.
41   MMI->setDebugInfoAvailability(true);
42 }
43 
44 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
45   std::string &Filepath = FileToFilepathMap[File];
46   if (!Filepath.empty())
47     return Filepath;
48 
49   StringRef Dir = File->getDirectory(), Filename = File->getFilename();
50 
51   // Clang emits directory and relative filename info into the IR, but CodeView
52   // operates on full paths.  We could change Clang to emit full paths too, but
53   // that would increase the IR size and probably not needed for other users.
54   // For now, just concatenate and canonicalize the path here.
55   if (Filename.find(':') == 1)
56     Filepath = Filename;
57   else
58     Filepath = (Dir + "\\" + Filename).str();
59 
60   // Canonicalize the path.  We have to do it textually because we may no longer
61   // have access the file in the filesystem.
62   // First, replace all slashes with backslashes.
63   std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
64 
65   // Remove all "\.\" with "\".
66   size_t Cursor = 0;
67   while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
68     Filepath.erase(Cursor, 2);
69 
70   // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
71   // path should be well-formatted, e.g. start with a drive letter, etc.
72   Cursor = 0;
73   while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
74     // Something's wrong if the path starts with "\..\", abort.
75     if (Cursor == 0)
76       break;
77 
78     size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
79     if (PrevSlash == std::string::npos)
80       // Something's wrong, abort.
81       break;
82 
83     Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
84     // The next ".." might be following the one we've just erased.
85     Cursor = PrevSlash;
86   }
87 
88   // Remove all duplicate backslashes.
89   Cursor = 0;
90   while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
91     Filepath.erase(Cursor, 1);
92 
93   return Filepath;
94 }
95 
96 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
97   unsigned NextId = FileIdMap.size() + 1;
98   auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
99   if (Insertion.second) {
100     // We have to compute the full filepath and emit a .cv_file directive.
101     StringRef FullPath = getFullFilepath(F);
102     NextId = OS.EmitCVFileDirective(NextId, FullPath);
103     assert(NextId == FileIdMap.size() && ".cv_file directive failed");
104   }
105   return Insertion.first->second;
106 }
107 
108 CodeViewDebug::InlineSite &CodeViewDebug::getInlineSite(const DILocation *Loc) {
109   const DILocation *InlinedAt = Loc->getInlinedAt();
110   auto Insertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
111   InlineSite *Site = &Insertion.first->second;
112   if (Insertion.second) {
113     Site->SiteFuncId = NextFuncId++;
114     Site->Inlinee = Loc->getScope()->getSubprogram();
115     InlinedSubprograms.insert(Loc->getScope()->getSubprogram());
116   }
117   return *Site;
118 }
119 
120 void CodeViewDebug::maybeRecordLocation(DebugLoc DL,
121                                         const MachineFunction *MF) {
122   // Skip this instruction if it has the same location as the previous one.
123   if (DL == CurFn->LastLoc)
124     return;
125 
126   const DIScope *Scope = DL.get()->getScope();
127   if (!Scope)
128     return;
129 
130   // Skip this line if it is longer than the maximum we can record.
131   LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
132   if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
133       LI.isNeverStepInto())
134     return;
135 
136   ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
137   if (CI.getStartColumn() != DL.getCol())
138     return;
139 
140   if (!CurFn->HaveLineInfo)
141     CurFn->HaveLineInfo = true;
142   unsigned FileId = 0;
143   if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
144     FileId = CurFn->LastFileId;
145   else
146     FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
147   CurFn->LastLoc = DL;
148 
149   unsigned FuncId = CurFn->FuncId;
150   if (const DILocation *Loc = DL->getInlinedAt()) {
151     // If this location was actually inlined from somewhere else, give it the ID
152     // of the inline call site.
153     FuncId = getInlineSite(DL.get()).SiteFuncId;
154     CurFn->ChildSites.push_back(Loc);
155     // Ensure we have links in the tree of inline call sites.
156     const DILocation *ChildLoc = nullptr;
157     while (Loc->getInlinedAt()) {
158       InlineSite &Site = getInlineSite(Loc);
159       if (ChildLoc) {
160         // Record the child inline site if not already present.
161         auto B = Site.ChildSites.begin(), E = Site.ChildSites.end();
162         if (std::find(B, E, Loc) != E)
163           break;
164         Site.ChildSites.push_back(Loc);
165       }
166       ChildLoc = Loc;
167     }
168   }
169 
170   OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
171                         /*PrologueEnd=*/false,
172                         /*IsStmt=*/false, DL->getFilename());
173 }
174 
175 void CodeViewDebug::endModule() {
176   if (FnDebugInfo.empty())
177     return;
178 
179   emitTypeInformation();
180 
181   // FIXME: For functions that are comdat, we should emit separate .debug$S
182   // sections that are comdat associative with the main function instead of
183   // having one big .debug$S section.
184   assert(Asm != nullptr);
185   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
186   OS.AddComment("Debug section magic");
187   OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
188 
189   // The COFF .debug$S section consists of several subsections, each starting
190   // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
191   // of the payload followed by the payload itself.  The subsections are 4-byte
192   // aligned.
193 
194   // Make a subsection for all the inlined subprograms.
195   emitInlineeLinesSubsection();
196 
197   // Emit per-function debug information.
198   for (auto &P : FnDebugInfo)
199     emitDebugInfoForFunction(P.first, P.second);
200 
201   // This subsection holds a file index to offset in string table table.
202   OS.AddComment("File index to string table offset subsection");
203   OS.EmitCVFileChecksumsDirective();
204 
205   // This subsection holds the string table.
206   OS.AddComment("String table");
207   OS.EmitCVStringTableDirective();
208 
209   clear();
210 }
211 
212 void CodeViewDebug::emitTypeInformation() {
213   // Start the .debug$T section with 0x4.
214   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
215   OS.AddComment("Debug section magic");
216   OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
217 
218   NamedMDNode *CU_Nodes =
219       MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
220   if (!CU_Nodes)
221     return;
222 
223   // This type info currently only holds function ids for use with inline call
224   // frame info. All functions are assigned a simple 'void ()' type. Emit that
225   // type here.
226   TypeIndex ArgListIdx = getNextTypeIndex();
227   OS.AddComment("Type record length");
228   OS.EmitIntValue(2 + sizeof(ArgList), 2);
229   OS.AddComment("Leaf type: LF_ARGLIST");
230   OS.EmitIntValue(LF_ARGLIST, 2);
231   OS.AddComment("Number of arguments");
232   OS.EmitIntValue(0, 4);
233 
234   TypeIndex VoidProcIdx = getNextTypeIndex();
235   OS.AddComment("Type record length");
236   OS.EmitIntValue(2 + sizeof(ProcedureType), 2);
237   OS.AddComment("Leaf type: LF_PROCEDURE");
238   OS.EmitIntValue(LF_PROCEDURE, 2);
239   OS.AddComment("Return type index");
240   OS.EmitIntValue(TypeIndex::Void().getIndex(), 4);
241   OS.AddComment("Calling convention");
242   OS.EmitIntValue(char(CallingConvention::NearC), 1);
243   OS.AddComment("Function options");
244   OS.EmitIntValue(char(FunctionOptions::None), 1);
245   OS.AddComment("# of parameters");
246   OS.EmitIntValue(0, 2);
247   OS.AddComment("Argument list type index");
248   OS.EmitIntValue(ArgListIdx.getIndex(), 4);
249 
250   for (MDNode *N : CU_Nodes->operands()) {
251     auto *CUNode = cast<DICompileUnit>(N);
252     for (auto *SP : CUNode->getSubprograms()) {
253       StringRef DisplayName = SP->getDisplayName();
254       OS.AddComment("Type record length");
255       OS.EmitIntValue(2 + sizeof(FuncId) + DisplayName.size() + 1, 2);
256       OS.AddComment("Leaf type: LF_FUNC_ID");
257       OS.EmitIntValue(LF_FUNC_ID, 2);
258 
259       OS.AddComment("Scope type index");
260       OS.EmitIntValue(TypeIndex().getIndex(), 4);
261       OS.AddComment("Function type");
262       OS.EmitIntValue(VoidProcIdx.getIndex(), 4);
263       {
264         SmallString<32> NullTerminatedString(DisplayName);
265         if (NullTerminatedString.empty() || NullTerminatedString.back() != '\0')
266           NullTerminatedString.push_back('\0');
267         OS.AddComment("Function name");
268         OS.EmitBytes(NullTerminatedString);
269       }
270 
271       TypeIndex FuncIdIdx = getNextTypeIndex();
272       SubprogramToFuncId.insert(std::make_pair(SP, FuncIdIdx));
273     }
274   }
275 }
276 
277 void CodeViewDebug::emitInlineeLinesSubsection() {
278   if (InlinedSubprograms.empty())
279     return;
280 
281   MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
282            *InlineEnd = MMI->getContext().createTempSymbol();
283 
284   OS.AddComment("Inlinee lines subsection");
285   OS.EmitIntValue(unsigned(ModuleSubstreamKind::InlineeLines), 4);
286   OS.AddComment("Subsection size");
287   OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 4);
288   OS.EmitLabel(InlineBegin);
289 
290   // We don't provide any extra file info.
291   // FIXME: Find out if debuggers use this info.
292   OS.AddComment("Inlinee lines signature");
293   OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
294 
295   for (const DISubprogram *SP : InlinedSubprograms) {
296     OS.AddBlankLine();
297     TypeIndex TypeId = SubprogramToFuncId[SP];
298     unsigned FileId = maybeRecordFile(SP->getFile());
299     OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
300                   SP->getFilename() + Twine(':') + Twine(SP->getLine()));
301     OS.AddBlankLine();
302     // The filechecksum table uses 8 byte entries for now, and file ids start at
303     // 1.
304     unsigned FileOffset = (FileId - 1) * 8;
305     OS.AddComment("Type index of inlined function");
306     OS.EmitIntValue(TypeId.getIndex(), 4);
307     OS.AddComment("Offset into filechecksum table");
308     OS.EmitIntValue(FileOffset, 4);
309     OS.AddComment("Starting line number");
310     OS.EmitIntValue(SP->getLine(), 4);
311   }
312 
313   OS.EmitLabel(InlineEnd);
314 }
315 
316 void CodeViewDebug::collectInlineSiteChildren(
317     SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
318     const InlineSite &Site) {
319   for (const DILocation *ChildSiteLoc : Site.ChildSites) {
320     auto I = FI.InlineSites.find(ChildSiteLoc);
321     const InlineSite &ChildSite = I->second;
322     Children.push_back(ChildSite.SiteFuncId);
323     collectInlineSiteChildren(Children, FI, ChildSite);
324   }
325 }
326 
327 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
328                                         const DILocation *InlinedAt,
329                                         const InlineSite &Site) {
330   MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
331            *InlineEnd = MMI->getContext().createTempSymbol();
332 
333   assert(SubprogramToFuncId.count(Site.Inlinee));
334   TypeIndex InlineeIdx = SubprogramToFuncId[Site.Inlinee];
335 
336   // SymbolRecord
337   OS.AddComment("Record length");
338   OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2);   // RecordLength
339   OS.EmitLabel(InlineBegin);
340   OS.AddComment("Record kind: S_INLINESITE");
341   OS.EmitIntValue(SymbolRecordKind::S_INLINESITE, 2); // RecordKind
342 
343   OS.AddComment("PtrParent");
344   OS.EmitIntValue(0, 4);
345   OS.AddComment("PtrEnd");
346   OS.EmitIntValue(0, 4);
347   OS.AddComment("Inlinee type index");
348   OS.EmitIntValue(InlineeIdx.getIndex(), 4);
349 
350   unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
351   unsigned StartLineNum = Site.Inlinee->getLine();
352   SmallVector<unsigned, 3> SecondaryFuncIds;
353   collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
354 
355   OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
356                                     FI.Begin, FI.End, SecondaryFuncIds);
357 
358   OS.EmitLabel(InlineEnd);
359 
360   for (const LocalVariable &Var : Site.InlinedLocals)
361     emitLocalVariable(Var);
362 
363   // Recurse on child inlined call sites before closing the scope.
364   for (const DILocation *ChildSite : Site.ChildSites) {
365     auto I = FI.InlineSites.find(ChildSite);
366     assert(I != FI.InlineSites.end() &&
367            "child site not in function inline site map");
368     emitInlinedCallSite(FI, ChildSite, I->second);
369   }
370 
371   // Close the scope.
372   OS.AddComment("Record length");
373   OS.EmitIntValue(2, 2);                                  // RecordLength
374   OS.AddComment("Record kind: S_INLINESITE_END");
375   OS.EmitIntValue(SymbolRecordKind::S_INLINESITE_END, 2); // RecordKind
376 }
377 
378 static void emitNullTerminatedString(MCStreamer &OS, StringRef S) {
379   SmallString<32> NullTerminatedString(S);
380   if (NullTerminatedString.empty() || NullTerminatedString.back() != '\0')
381     NullTerminatedString.push_back('\0');
382   OS.EmitBytes(NullTerminatedString);
383 }
384 
385 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
386                                              FunctionInfo &FI) {
387   // For each function there is a separate subsection
388   // which holds the PC to file:line table.
389   const MCSymbol *Fn = Asm->getSymbol(GV);
390   assert(Fn);
391 
392   StringRef FuncName;
393   if (auto *SP = getDISubprogram(GV))
394     FuncName = SP->getDisplayName();
395 
396   // If our DISubprogram name is empty, use the mangled name.
397   if (FuncName.empty())
398     FuncName = GlobalValue::getRealLinkageName(GV->getName());
399 
400   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
401   MCSymbol *SymbolsBegin = MMI->getContext().createTempSymbol(),
402            *SymbolsEnd = MMI->getContext().createTempSymbol();
403   OS.AddComment("Symbol subsection for " + Twine(FuncName));
404   OS.EmitIntValue(unsigned(ModuleSubstreamKind::Symbols), 4);
405   OS.AddComment("Subsection size");
406   OS.emitAbsoluteSymbolDiff(SymbolsEnd, SymbolsBegin, 4);
407   OS.EmitLabel(SymbolsBegin);
408   {
409     MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
410              *ProcRecordEnd = MMI->getContext().createTempSymbol();
411     OS.AddComment("Record length");
412     OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
413     OS.EmitLabel(ProcRecordBegin);
414 
415     OS.AddComment("Record kind: S_GPROC32_ID");
416     OS.EmitIntValue(unsigned(SymbolRecordKind::S_GPROC32_ID), 2);
417 
418     // These fields are filled in by tools like CVPACK which run after the fact.
419     OS.AddComment("PtrParent");
420     OS.EmitIntValue(0, 4);
421     OS.AddComment("PtrEnd");
422     OS.EmitIntValue(0, 4);
423     OS.AddComment("PtrNext");
424     OS.EmitIntValue(0, 4);
425     // This is the important bit that tells the debugger where the function
426     // code is located and what's its size:
427     OS.AddComment("Code size");
428     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
429     OS.AddComment("Offset after prologue");
430     OS.EmitIntValue(0, 4);
431     OS.AddComment("Offset before epilogue");
432     OS.EmitIntValue(0, 4);
433     OS.AddComment("Function type index");
434     OS.EmitIntValue(0, 4);
435     OS.AddComment("Function section relative address");
436     OS.EmitCOFFSecRel32(Fn);
437     OS.AddComment("Function section index");
438     OS.EmitCOFFSectionIndex(Fn);
439     OS.AddComment("Flags");
440     OS.EmitIntValue(0, 1);
441     // Emit the function display name as a null-terminated string.
442     OS.AddComment("Function name");
443     emitNullTerminatedString(OS, FuncName);
444     OS.EmitLabel(ProcRecordEnd);
445 
446     for (const LocalVariable &Var : FI.Locals)
447       emitLocalVariable(Var);
448 
449     // Emit inlined call site information. Only emit functions inlined directly
450     // into the parent function. We'll emit the other sites recursively as part
451     // of their parent inline site.
452     for (const DILocation *InlinedAt : FI.ChildSites) {
453       auto I = FI.InlineSites.find(InlinedAt);
454       assert(I != FI.InlineSites.end() &&
455              "child site not in function inline site map");
456       emitInlinedCallSite(FI, InlinedAt, I->second);
457     }
458 
459     // We're done with this function.
460     OS.AddComment("Record length");
461     OS.EmitIntValue(0x0002, 2);
462     OS.AddComment("Record kind: S_PROC_ID_END");
463     OS.EmitIntValue(unsigned(SymbolRecordKind::S_PROC_ID_END), 2);
464   }
465   OS.EmitLabel(SymbolsEnd);
466   // Every subsection must be aligned to a 4-byte boundary.
467   OS.EmitValueToAlignment(4);
468 
469   // We have an assembler directive that takes care of the whole line table.
470   OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
471 }
472 
473 void CodeViewDebug::collectVariableInfoFromMMITable() {
474   for (const auto &VI : MMI->getVariableDbgInfo()) {
475     if (!VI.Var)
476       continue;
477     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
478            "Expected inlined-at fields to agree");
479 
480     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
481 
482     // If variable scope is not found then skip this variable.
483     if (!Scope)
484       continue;
485 
486     LocalVariable Var;
487     Var.DIVar = VI.Var;
488 
489     // Get the frame register used and the offset.
490     unsigned FrameReg = 0;
491     const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
492     const TargetFrameLowering *TFI = TSI.getFrameLowering();
493     const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
494     Var.RegisterOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
495     Var.CVRegister = TRI->getCodeViewRegNum(FrameReg);
496 
497     // Calculate the label ranges.
498     for (const InsnRange &Range : Scope->getRanges()) {
499       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
500       const MCSymbol *End = getLabelAfterInsn(Range.second);
501       Var.Ranges.push_back({Begin, End});
502     }
503 
504     if (VI.Loc->getInlinedAt()) {
505       // This variable was inlined. Associate it with the InlineSite.
506       InlineSite &Site = getInlineSite(VI.Loc);
507       Site.InlinedLocals.emplace_back(std::move(Var));
508     } else {
509       // This variable goes in the main ProcSym.
510       CurFn->Locals.emplace_back(std::move(Var));
511     }
512   }
513 }
514 
515 void CodeViewDebug::beginFunction(const MachineFunction *MF) {
516   assert(!CurFn && "Can't process two functions at once!");
517 
518   if (!Asm || !MMI->hasDebugInfo())
519     return;
520 
521   DebugHandlerBase::beginFunction(MF);
522 
523   const Function *GV = MF->getFunction();
524   assert(FnDebugInfo.count(GV) == false);
525   CurFn = &FnDebugInfo[GV];
526   CurFn->FuncId = NextFuncId++;
527   CurFn->Begin = Asm->getFunctionBegin();
528 
529   // Find the end of the function prolog.  First known non-DBG_VALUE and
530   // non-frame setup location marks the beginning of the function body.
531   // FIXME: is there a simpler a way to do this? Can we just search
532   // for the first instruction of the function, not the last of the prolog?
533   DebugLoc PrologEndLoc;
534   bool EmptyPrologue = true;
535   for (const auto &MBB : *MF) {
536     for (const auto &MI : MBB) {
537       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
538           MI.getDebugLoc()) {
539         PrologEndLoc = MI.getDebugLoc();
540         break;
541       } else if (!MI.isDebugValue()) {
542         EmptyPrologue = false;
543       }
544     }
545   }
546 
547   // Record beginning of function if we have a non-empty prologue.
548   if (PrologEndLoc && !EmptyPrologue) {
549     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
550     maybeRecordLocation(FnStartDL, MF);
551   }
552 }
553 
554 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
555   // LocalSym record, see SymbolRecord.h for more info.
556   MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
557            *LocalEnd = MMI->getContext().createTempSymbol();
558   OS.AddComment("Record length");
559   OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
560   OS.EmitLabel(LocalBegin);
561 
562   OS.AddComment("Record kind: S_LOCAL");
563   OS.EmitIntValue(unsigned(SymbolRecordKind::S_LOCAL), 2);
564 
565   uint16_t Flags = 0;
566   if (Var.DIVar->isParameter())
567     Flags |= LocalSym::IsParameter;
568 
569   OS.AddComment("TypeIndex");
570   OS.EmitIntValue(TypeIndex::Int32().getIndex(), 4);
571   OS.AddComment("Flags");
572   OS.EmitIntValue(Flags, 2);
573   emitNullTerminatedString(OS, Var.DIVar->getName());
574   OS.EmitLabel(LocalEnd);
575 
576   // DefRangeRegisterRelSym record, see SymbolRecord.h for more info.  Omit the
577   // LocalVariableAddrRange field from the record. The directive will emit that.
578   DefRangeRegisterRelSym Sym{};
579   ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
580   Sym.BaseRegister = Var.CVRegister;
581   Sym.Flags = 0; // Unclear what matters here.
582   Sym.BasePointerOffset = Var.RegisterOffset;
583   SmallString<sizeof(Sym) + sizeof(SymKind) - sizeof(LocalVariableAddrRange)>
584       BytePrefix;
585   BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
586                           sizeof(SymKind));
587   BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym),
588                           sizeof(Sym) - sizeof(LocalVariableAddrRange));
589 
590   OS.EmitCVDefRangeDirective(Var.Ranges, BytePrefix);
591 }
592 
593 void CodeViewDebug::endFunction(const MachineFunction *MF) {
594   collectVariableInfoFromMMITable();
595 
596   DebugHandlerBase::endFunction(MF);
597 
598   if (!Asm || !CurFn)  // We haven't created any debug info for this function.
599     return;
600 
601   const Function *GV = MF->getFunction();
602   assert(FnDebugInfo.count(GV));
603   assert(CurFn == &FnDebugInfo[GV]);
604 
605   // Don't emit anything if we don't have any line tables.
606   if (!CurFn->HaveLineInfo) {
607     FnDebugInfo.erase(GV);
608     CurFn = nullptr;
609     return;
610   }
611 
612   CurFn->End = Asm->getFunctionEnd();
613 
614   CurFn = nullptr;
615 }
616 
617 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
618   DebugHandlerBase::beginInstruction(MI);
619 
620   // Ignore DBG_VALUE locations and function prologue.
621   if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
622     return;
623   DebugLoc DL = MI->getDebugLoc();
624   if (DL == PrevInstLoc || !DL)
625     return;
626   maybeRecordLocation(DL, Asm->MF);
627 }
628