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/FieldListRecordBuilder.h"
17 #include "llvm/DebugInfo/CodeView/Line.h"
18 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
19 #include "llvm/DebugInfo/CodeView/TypeDumper.h"
20 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
21 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCSectionCOFF.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/Support/COFF.h"
26 #include "llvm/Support/ScopedPrinter.h"
27 #include "llvm/Target/TargetSubtargetInfo.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetFrameLowering.h"
30 
31 using namespace llvm;
32 using namespace llvm::codeview;
33 
34 CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
35     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
36   // If module doesn't have named metadata anchors or COFF debug section
37   // is not available, skip any debug info related stuff.
38   if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
39       !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
40     Asm = nullptr;
41     return;
42   }
43 
44   // Tell MMI that we have debug info.
45   MMI->setDebugInfoAvailability(true);
46 }
47 
48 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
49   std::string &Filepath = FileToFilepathMap[File];
50   if (!Filepath.empty())
51     return Filepath;
52 
53   StringRef Dir = File->getDirectory(), Filename = File->getFilename();
54 
55   // Clang emits directory and relative filename info into the IR, but CodeView
56   // operates on full paths.  We could change Clang to emit full paths too, but
57   // that would increase the IR size and probably not needed for other users.
58   // For now, just concatenate and canonicalize the path here.
59   if (Filename.find(':') == 1)
60     Filepath = Filename;
61   else
62     Filepath = (Dir + "\\" + Filename).str();
63 
64   // Canonicalize the path.  We have to do it textually because we may no longer
65   // have access the file in the filesystem.
66   // First, replace all slashes with backslashes.
67   std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
68 
69   // Remove all "\.\" with "\".
70   size_t Cursor = 0;
71   while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
72     Filepath.erase(Cursor, 2);
73 
74   // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
75   // path should be well-formatted, e.g. start with a drive letter, etc.
76   Cursor = 0;
77   while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
78     // Something's wrong if the path starts with "\..\", abort.
79     if (Cursor == 0)
80       break;
81 
82     size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
83     if (PrevSlash == std::string::npos)
84       // Something's wrong, abort.
85       break;
86 
87     Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
88     // The next ".." might be following the one we've just erased.
89     Cursor = PrevSlash;
90   }
91 
92   // Remove all duplicate backslashes.
93   Cursor = 0;
94   while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
95     Filepath.erase(Cursor, 1);
96 
97   return Filepath;
98 }
99 
100 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
101   unsigned NextId = FileIdMap.size() + 1;
102   auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
103   if (Insertion.second) {
104     // We have to compute the full filepath and emit a .cv_file directive.
105     StringRef FullPath = getFullFilepath(F);
106     NextId = OS.EmitCVFileDirective(NextId, FullPath);
107     assert(NextId == FileIdMap.size() && ".cv_file directive failed");
108   }
109   return Insertion.first->second;
110 }
111 
112 CodeViewDebug::InlineSite &
113 CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
114                              const DISubprogram *Inlinee) {
115   auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
116   InlineSite *Site = &SiteInsertion.first->second;
117   if (SiteInsertion.second) {
118     Site->SiteFuncId = NextFuncId++;
119     Site->Inlinee = Inlinee;
120     InlinedSubprograms.insert(Inlinee);
121     getFuncIdForSubprogram(Inlinee);
122   }
123   return *Site;
124 }
125 
126 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
127   // It's possible to ask for the FuncId of a function which doesn't have a
128   // subprogram: inlining a function with debug info into a function with none.
129   if (!SP)
130     return TypeIndex::None();
131 
132   // Check if we've already translated this subprogram.
133   auto I = TypeIndices.find(SP);
134   if (I != TypeIndices.end())
135     return I->second;
136 
137   TypeIndex ParentScope = TypeIndex(0);
138   StringRef DisplayName = SP->getDisplayName();
139   FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
140   TypeIndex TI = TypeTable.writeFuncId(FuncId);
141 
142   recordTypeIndexForDINode(SP, TI);
143   return TI;
144 }
145 
146 void CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, TypeIndex TI) {
147   auto InsertResult = TypeIndices.insert({Node, TI});
148   (void)InsertResult;
149   assert(InsertResult.second && "DINode was already assigned a type index");
150 }
151 
152 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
153                                         const DILocation *InlinedAt) {
154   if (InlinedAt) {
155     // This variable was inlined. Associate it with the InlineSite.
156     const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
157     InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
158     Site.InlinedLocals.emplace_back(Var);
159   } else {
160     // This variable goes in the main ProcSym.
161     CurFn->Locals.emplace_back(Var);
162   }
163 }
164 
165 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
166                                const DILocation *Loc) {
167   auto B = Locs.begin(), E = Locs.end();
168   if (std::find(B, E, Loc) == E)
169     Locs.push_back(Loc);
170 }
171 
172 void CodeViewDebug::maybeRecordLocation(DebugLoc DL,
173                                         const MachineFunction *MF) {
174   // Skip this instruction if it has the same location as the previous one.
175   if (DL == CurFn->LastLoc)
176     return;
177 
178   const DIScope *Scope = DL.get()->getScope();
179   if (!Scope)
180     return;
181 
182   // Skip this line if it is longer than the maximum we can record.
183   LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
184   if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
185       LI.isNeverStepInto())
186     return;
187 
188   ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
189   if (CI.getStartColumn() != DL.getCol())
190     return;
191 
192   if (!CurFn->HaveLineInfo)
193     CurFn->HaveLineInfo = true;
194   unsigned FileId = 0;
195   if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
196     FileId = CurFn->LastFileId;
197   else
198     FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
199   CurFn->LastLoc = DL;
200 
201   unsigned FuncId = CurFn->FuncId;
202   if (const DILocation *SiteLoc = DL->getInlinedAt()) {
203     const DILocation *Loc = DL.get();
204 
205     // If this location was actually inlined from somewhere else, give it the ID
206     // of the inline call site.
207     FuncId =
208         getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
209 
210     // Ensure we have links in the tree of inline call sites.
211     bool FirstLoc = true;
212     while ((SiteLoc = Loc->getInlinedAt())) {
213       InlineSite &Site =
214           getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
215       if (!FirstLoc)
216         addLocIfNotPresent(Site.ChildSites, Loc);
217       FirstLoc = false;
218       Loc = SiteLoc;
219     }
220     addLocIfNotPresent(CurFn->ChildSites, Loc);
221   }
222 
223   OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
224                         /*PrologueEnd=*/false,
225                         /*IsStmt=*/false, DL->getFilename());
226 }
227 
228 void CodeViewDebug::emitCodeViewMagicVersion() {
229   OS.EmitValueToAlignment(4);
230   OS.AddComment("Debug section magic");
231   OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
232 }
233 
234 void CodeViewDebug::endModule() {
235   if (FnDebugInfo.empty())
236     return;
237 
238   assert(Asm != nullptr);
239 
240   // The COFF .debug$S section consists of several subsections, each starting
241   // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
242   // of the payload followed by the payload itself.  The subsections are 4-byte
243   // aligned.
244 
245   // Make a subsection for all the inlined subprograms.
246   emitInlineeLinesSubsection();
247 
248   // Emit per-function debug information.
249   for (auto &P : FnDebugInfo)
250     emitDebugInfoForFunction(P.first, P.second);
251 
252   // Switch back to the generic .debug$S section after potentially processing
253   // comdat symbol sections.
254   switchToDebugSectionForSymbol(nullptr);
255 
256   // This subsection holds a file index to offset in string table table.
257   OS.AddComment("File index to string table offset subsection");
258   OS.EmitCVFileChecksumsDirective();
259 
260   // This subsection holds the string table.
261   OS.AddComment("String table");
262   OS.EmitCVStringTableDirective();
263 
264   // Emit type information last, so that any types we translate while emitting
265   // function info are included.
266   emitTypeInformation();
267 
268   clear();
269 }
270 
271 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
272   // Microsoft's linker seems to have trouble with symbol names longer than
273   // 0xffd8 bytes.
274   S = S.substr(0, 0xffd8);
275   SmallString<32> NullTerminatedString(S);
276   NullTerminatedString.push_back('\0');
277   OS.EmitBytes(NullTerminatedString);
278 }
279 
280 void CodeViewDebug::emitTypeInformation() {
281   // Do nothing if we have no debug info or if no non-trivial types were emitted
282   // to TypeTable during codegen.
283   NamedMDNode *CU_Nodes =
284       MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
285   if (!CU_Nodes)
286     return;
287   if (TypeTable.empty())
288     return;
289 
290   // Start the .debug$T section with 0x4.
291   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
292   emitCodeViewMagicVersion();
293 
294   SmallString<8> CommentPrefix;
295   if (OS.isVerboseAsm()) {
296     CommentPrefix += '\t';
297     CommentPrefix += Asm->MAI->getCommentString();
298     CommentPrefix += ' ';
299   }
300 
301   CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
302   TypeTable.ForEachRecord(
303       [&](TypeIndex Index, StringRef Record) {
304         if (OS.isVerboseAsm()) {
305           // Emit a block comment describing the type record for readability.
306           SmallString<512> CommentBlock;
307           raw_svector_ostream CommentOS(CommentBlock);
308           ScopedPrinter SP(CommentOS);
309           SP.setPrefix(CommentPrefix);
310           CVTD.setPrinter(&SP);
311           bool DumpSuccess =
312               CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
313           (void)DumpSuccess;
314           assert(DumpSuccess && "produced malformed type record");
315           // emitRawComment will insert its own tab and comment string before
316           // the first line, so strip off our first one. It also prints its own
317           // newline.
318           OS.emitRawComment(
319               CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
320         }
321         OS.EmitBinaryData(Record);
322       });
323 }
324 
325 void CodeViewDebug::emitInlineeLinesSubsection() {
326   if (InlinedSubprograms.empty())
327     return;
328 
329   // Use the generic .debug$S section.
330   switchToDebugSectionForSymbol(nullptr);
331 
332   MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
333            *InlineEnd = MMI->getContext().createTempSymbol();
334 
335   OS.AddComment("Inlinee lines subsection");
336   OS.EmitIntValue(unsigned(ModuleSubstreamKind::InlineeLines), 4);
337   OS.AddComment("Subsection size");
338   OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 4);
339   OS.EmitLabel(InlineBegin);
340 
341   // We don't provide any extra file info.
342   // FIXME: Find out if debuggers use this info.
343   OS.AddComment("Inlinee lines signature");
344   OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
345 
346   for (const DISubprogram *SP : InlinedSubprograms) {
347     assert(TypeIndices.count(SP));
348     TypeIndex InlineeIdx = TypeIndices[SP];
349 
350     OS.AddBlankLine();
351     unsigned FileId = maybeRecordFile(SP->getFile());
352     OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
353                   SP->getFilename() + Twine(':') + Twine(SP->getLine()));
354     OS.AddBlankLine();
355     // The filechecksum table uses 8 byte entries for now, and file ids start at
356     // 1.
357     unsigned FileOffset = (FileId - 1) * 8;
358     OS.AddComment("Type index of inlined function");
359     OS.EmitIntValue(InlineeIdx.getIndex(), 4);
360     OS.AddComment("Offset into filechecksum table");
361     OS.EmitIntValue(FileOffset, 4);
362     OS.AddComment("Starting line number");
363     OS.EmitIntValue(SP->getLine(), 4);
364   }
365 
366   OS.EmitLabel(InlineEnd);
367 }
368 
369 void CodeViewDebug::collectInlineSiteChildren(
370     SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
371     const InlineSite &Site) {
372   for (const DILocation *ChildSiteLoc : Site.ChildSites) {
373     auto I = FI.InlineSites.find(ChildSiteLoc);
374     const InlineSite &ChildSite = I->second;
375     Children.push_back(ChildSite.SiteFuncId);
376     collectInlineSiteChildren(Children, FI, ChildSite);
377   }
378 }
379 
380 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
381                                         const DILocation *InlinedAt,
382                                         const InlineSite &Site) {
383   MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
384            *InlineEnd = MMI->getContext().createTempSymbol();
385 
386   assert(TypeIndices.count(Site.Inlinee));
387   TypeIndex InlineeIdx = TypeIndices[Site.Inlinee];
388 
389   // SymbolRecord
390   OS.AddComment("Record length");
391   OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2);   // RecordLength
392   OS.EmitLabel(InlineBegin);
393   OS.AddComment("Record kind: S_INLINESITE");
394   OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
395 
396   OS.AddComment("PtrParent");
397   OS.EmitIntValue(0, 4);
398   OS.AddComment("PtrEnd");
399   OS.EmitIntValue(0, 4);
400   OS.AddComment("Inlinee type index");
401   OS.EmitIntValue(InlineeIdx.getIndex(), 4);
402 
403   unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
404   unsigned StartLineNum = Site.Inlinee->getLine();
405   SmallVector<unsigned, 3> SecondaryFuncIds;
406   collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
407 
408   OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
409                                     FI.Begin, FI.End, SecondaryFuncIds);
410 
411   OS.EmitLabel(InlineEnd);
412 
413   for (const LocalVariable &Var : Site.InlinedLocals)
414     emitLocalVariable(Var);
415 
416   // Recurse on child inlined call sites before closing the scope.
417   for (const DILocation *ChildSite : Site.ChildSites) {
418     auto I = FI.InlineSites.find(ChildSite);
419     assert(I != FI.InlineSites.end() &&
420            "child site not in function inline site map");
421     emitInlinedCallSite(FI, ChildSite, I->second);
422   }
423 
424   // Close the scope.
425   OS.AddComment("Record length");
426   OS.EmitIntValue(2, 2);                                  // RecordLength
427   OS.AddComment("Record kind: S_INLINESITE_END");
428   OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
429 }
430 
431 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
432   // If we have a symbol, it may be in a section that is COMDAT. If so, find the
433   // comdat key. A section may be comdat because of -ffunction-sections or
434   // because it is comdat in the IR.
435   MCSectionCOFF *GVSec =
436       GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
437   const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
438 
439   MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
440       Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
441   DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
442 
443   OS.SwitchSection(DebugSec);
444 
445   // Emit the magic version number if this is the first time we've switched to
446   // this section.
447   if (ComdatDebugSections.insert(DebugSec).second)
448     emitCodeViewMagicVersion();
449 }
450 
451 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
452                                              FunctionInfo &FI) {
453   // For each function there is a separate subsection
454   // which holds the PC to file:line table.
455   const MCSymbol *Fn = Asm->getSymbol(GV);
456   assert(Fn);
457 
458   // Switch to the to a comdat section, if appropriate.
459   switchToDebugSectionForSymbol(Fn);
460 
461   StringRef FuncName;
462   if (auto *SP = GV->getSubprogram())
463     FuncName = SP->getDisplayName();
464 
465   // If our DISubprogram name is empty, use the mangled name.
466   if (FuncName.empty())
467     FuncName = GlobalValue::getRealLinkageName(GV->getName());
468 
469   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
470   MCSymbol *SymbolsBegin = MMI->getContext().createTempSymbol(),
471            *SymbolsEnd = MMI->getContext().createTempSymbol();
472   OS.AddComment("Symbol subsection for " + Twine(FuncName));
473   OS.EmitIntValue(unsigned(ModuleSubstreamKind::Symbols), 4);
474   OS.AddComment("Subsection size");
475   OS.emitAbsoluteSymbolDiff(SymbolsEnd, SymbolsBegin, 4);
476   OS.EmitLabel(SymbolsBegin);
477   {
478     MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
479              *ProcRecordEnd = MMI->getContext().createTempSymbol();
480     OS.AddComment("Record length");
481     OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
482     OS.EmitLabel(ProcRecordBegin);
483 
484     OS.AddComment("Record kind: S_GPROC32_ID");
485     OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
486 
487     // These fields are filled in by tools like CVPACK which run after the fact.
488     OS.AddComment("PtrParent");
489     OS.EmitIntValue(0, 4);
490     OS.AddComment("PtrEnd");
491     OS.EmitIntValue(0, 4);
492     OS.AddComment("PtrNext");
493     OS.EmitIntValue(0, 4);
494     // This is the important bit that tells the debugger where the function
495     // code is located and what's its size:
496     OS.AddComment("Code size");
497     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
498     OS.AddComment("Offset after prologue");
499     OS.EmitIntValue(0, 4);
500     OS.AddComment("Offset before epilogue");
501     OS.EmitIntValue(0, 4);
502     OS.AddComment("Function type index");
503     OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
504     OS.AddComment("Function section relative address");
505     OS.EmitCOFFSecRel32(Fn);
506     OS.AddComment("Function section index");
507     OS.EmitCOFFSectionIndex(Fn);
508     OS.AddComment("Flags");
509     OS.EmitIntValue(0, 1);
510     // Emit the function display name as a null-terminated string.
511     OS.AddComment("Function name");
512     // Truncate the name so we won't overflow the record length field.
513     emitNullTerminatedSymbolName(OS, FuncName);
514     OS.EmitLabel(ProcRecordEnd);
515 
516     for (const LocalVariable &Var : FI.Locals)
517       emitLocalVariable(Var);
518 
519     // Emit inlined call site information. Only emit functions inlined directly
520     // into the parent function. We'll emit the other sites recursively as part
521     // of their parent inline site.
522     for (const DILocation *InlinedAt : FI.ChildSites) {
523       auto I = FI.InlineSites.find(InlinedAt);
524       assert(I != FI.InlineSites.end() &&
525              "child site not in function inline site map");
526       emitInlinedCallSite(FI, InlinedAt, I->second);
527     }
528 
529     // We're done with this function.
530     OS.AddComment("Record length");
531     OS.EmitIntValue(0x0002, 2);
532     OS.AddComment("Record kind: S_PROC_ID_END");
533     OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
534   }
535   OS.EmitLabel(SymbolsEnd);
536   // Every subsection must be aligned to a 4-byte boundary.
537   OS.EmitValueToAlignment(4);
538 
539   // We have an assembler directive that takes care of the whole line table.
540   OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
541 }
542 
543 CodeViewDebug::LocalVarDefRange
544 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
545   LocalVarDefRange DR;
546   DR.InMemory = -1;
547   DR.DataOffset = Offset;
548   assert(DR.DataOffset == Offset && "truncation");
549   DR.StructOffset = 0;
550   DR.CVRegister = CVRegister;
551   return DR;
552 }
553 
554 CodeViewDebug::LocalVarDefRange
555 CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
556   LocalVarDefRange DR;
557   DR.InMemory = 0;
558   DR.DataOffset = 0;
559   DR.StructOffset = 0;
560   DR.CVRegister = CVRegister;
561   return DR;
562 }
563 
564 void CodeViewDebug::collectVariableInfoFromMMITable(
565     DenseSet<InlinedVariable> &Processed) {
566   const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
567   const TargetFrameLowering *TFI = TSI.getFrameLowering();
568   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
569 
570   for (const MachineModuleInfo::VariableDbgInfo &VI :
571        MMI->getVariableDbgInfo()) {
572     if (!VI.Var)
573       continue;
574     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
575            "Expected inlined-at fields to agree");
576 
577     Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
578     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
579 
580     // If variable scope is not found then skip this variable.
581     if (!Scope)
582       continue;
583 
584     // Get the frame register used and the offset.
585     unsigned FrameReg = 0;
586     int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
587     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
588 
589     // Calculate the label ranges.
590     LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
591     for (const InsnRange &Range : Scope->getRanges()) {
592       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
593       const MCSymbol *End = getLabelAfterInsn(Range.second);
594       End = End ? End : Asm->getFunctionEnd();
595       DefRange.Ranges.emplace_back(Begin, End);
596     }
597 
598     LocalVariable Var;
599     Var.DIVar = VI.Var;
600     Var.DefRanges.emplace_back(std::move(DefRange));
601     recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
602   }
603 }
604 
605 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
606   DenseSet<InlinedVariable> Processed;
607   // Grab the variable info that was squirreled away in the MMI side-table.
608   collectVariableInfoFromMMITable(Processed);
609 
610   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
611 
612   for (const auto &I : DbgValues) {
613     InlinedVariable IV = I.first;
614     if (Processed.count(IV))
615       continue;
616     const DILocalVariable *DIVar = IV.first;
617     const DILocation *InlinedAt = IV.second;
618 
619     // Instruction ranges, specifying where IV is accessible.
620     const auto &Ranges = I.second;
621 
622     LexicalScope *Scope = nullptr;
623     if (InlinedAt)
624       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
625     else
626       Scope = LScopes.findLexicalScope(DIVar->getScope());
627     // If variable scope is not found then skip this variable.
628     if (!Scope)
629       continue;
630 
631     LocalVariable Var;
632     Var.DIVar = DIVar;
633 
634     // Calculate the definition ranges.
635     for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
636       const InsnRange &Range = *I;
637       const MachineInstr *DVInst = Range.first;
638       assert(DVInst->isDebugValue() && "Invalid History entry");
639       const DIExpression *DIExpr = DVInst->getDebugExpression();
640 
641       // Bail if there is a complex DWARF expression for now.
642       if (DIExpr && DIExpr->getNumElements() > 0)
643         continue;
644 
645       // Bail if operand 0 is not a valid register. This means the variable is a
646       // simple constant, or is described by a complex expression.
647       // FIXME: Find a way to represent constant variables, since they are
648       // relatively common.
649       unsigned Reg =
650           DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
651       if (Reg == 0)
652         continue;
653 
654       // Handle the two cases we can handle: indirect in memory and in register.
655       bool IsIndirect = DVInst->getOperand(1).isImm();
656       unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
657       {
658         LocalVarDefRange DefRange;
659         if (IsIndirect) {
660           int64_t Offset = DVInst->getOperand(1).getImm();
661           DefRange = createDefRangeMem(CVReg, Offset);
662         } else {
663           DefRange = createDefRangeReg(CVReg);
664         }
665         if (Var.DefRanges.empty() ||
666             Var.DefRanges.back().isDifferentLocation(DefRange)) {
667           Var.DefRanges.emplace_back(std::move(DefRange));
668         }
669       }
670 
671       // Compute the label range.
672       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
673       const MCSymbol *End = getLabelAfterInsn(Range.second);
674       if (!End) {
675         if (std::next(I) != E)
676           End = getLabelBeforeInsn(std::next(I)->first);
677         else
678           End = Asm->getFunctionEnd();
679       }
680 
681       // If the last range end is our begin, just extend the last range.
682       // Otherwise make a new range.
683       SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
684           Var.DefRanges.back().Ranges;
685       if (!Ranges.empty() && Ranges.back().second == Begin)
686         Ranges.back().second = End;
687       else
688         Ranges.emplace_back(Begin, End);
689 
690       // FIXME: Do more range combining.
691     }
692 
693     recordLocalVariable(std::move(Var), InlinedAt);
694   }
695 }
696 
697 void CodeViewDebug::beginFunction(const MachineFunction *MF) {
698   assert(!CurFn && "Can't process two functions at once!");
699 
700   if (!Asm || !MMI->hasDebugInfo())
701     return;
702 
703   DebugHandlerBase::beginFunction(MF);
704 
705   const Function *GV = MF->getFunction();
706   assert(FnDebugInfo.count(GV) == false);
707   CurFn = &FnDebugInfo[GV];
708   CurFn->FuncId = NextFuncId++;
709   CurFn->Begin = Asm->getFunctionBegin();
710 
711   // Find the end of the function prolog.  First known non-DBG_VALUE and
712   // non-frame setup location marks the beginning of the function body.
713   // FIXME: is there a simpler a way to do this? Can we just search
714   // for the first instruction of the function, not the last of the prolog?
715   DebugLoc PrologEndLoc;
716   bool EmptyPrologue = true;
717   for (const auto &MBB : *MF) {
718     for (const auto &MI : MBB) {
719       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
720           MI.getDebugLoc()) {
721         PrologEndLoc = MI.getDebugLoc();
722         break;
723       } else if (!MI.isDebugValue()) {
724         EmptyPrologue = false;
725       }
726     }
727   }
728 
729   // Record beginning of function if we have a non-empty prologue.
730   if (PrologEndLoc && !EmptyPrologue) {
731     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
732     maybeRecordLocation(FnStartDL, MF);
733   }
734 }
735 
736 TypeIndex CodeViewDebug::lowerType(const DIType *Ty) {
737   // Generic dispatch for lowering an unknown type.
738   switch (Ty->getTag()) {
739   case dwarf::DW_TAG_typedef:
740     return lowerTypeAlias(cast<DIDerivedType>(Ty));
741   case dwarf::DW_TAG_base_type:
742     return lowerTypeBasic(cast<DIBasicType>(Ty));
743   case dwarf::DW_TAG_pointer_type:
744   case dwarf::DW_TAG_reference_type:
745   case dwarf::DW_TAG_rvalue_reference_type:
746     return lowerTypePointer(cast<DIDerivedType>(Ty));
747   case dwarf::DW_TAG_ptr_to_member_type:
748     return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
749   case dwarf::DW_TAG_const_type:
750   case dwarf::DW_TAG_volatile_type:
751     return lowerTypeModifier(cast<DIDerivedType>(Ty));
752   case dwarf::DW_TAG_subroutine_type:
753     return lowerTypeFunction(cast<DISubroutineType>(Ty));
754   case dwarf::DW_TAG_class_type:
755   case dwarf::DW_TAG_structure_type:
756     return lowerTypeClass(cast<DICompositeType>(Ty));
757   case dwarf::DW_TAG_union_type:
758     return lowerTypeUnion(cast<DICompositeType>(Ty));
759   default:
760     // Use the null type index.
761     return TypeIndex();
762   }
763 }
764 
765 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
766   // TODO: MSVC emits a S_UDT record.
767   DITypeRef UnderlyingTypeRef = Ty->getBaseType();
768   TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
769   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
770       Ty->getName() == "HRESULT")
771     return TypeIndex(SimpleTypeKind::HResult);
772   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
773       Ty->getName() == "wchar_t")
774     return TypeIndex(SimpleTypeKind::WideCharacter);
775   return UnderlyingTypeIndex;
776 }
777 
778 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
779   TypeIndex Index;
780   dwarf::TypeKind Kind;
781   uint32_t ByteSize;
782 
783   Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
784   ByteSize = Ty->getSizeInBits() / 8;
785 
786   SimpleTypeKind STK = SimpleTypeKind::None;
787   switch (Kind) {
788   case dwarf::DW_ATE_address:
789     // FIXME: Translate
790     break;
791   case dwarf::DW_ATE_boolean:
792     switch (ByteSize) {
793     case 1:  STK = SimpleTypeKind::Boolean8;   break;
794     case 2:  STK = SimpleTypeKind::Boolean16;  break;
795     case 4:  STK = SimpleTypeKind::Boolean32;  break;
796     case 8:  STK = SimpleTypeKind::Boolean64;  break;
797     case 16: STK = SimpleTypeKind::Boolean128; break;
798     }
799     break;
800   case dwarf::DW_ATE_complex_float:
801     switch (ByteSize) {
802     case 2:  STK = SimpleTypeKind::Complex16;  break;
803     case 4:  STK = SimpleTypeKind::Complex32;  break;
804     case 8:  STK = SimpleTypeKind::Complex64;  break;
805     case 10: STK = SimpleTypeKind::Complex80;  break;
806     case 16: STK = SimpleTypeKind::Complex128; break;
807     }
808     break;
809   case dwarf::DW_ATE_float:
810     switch (ByteSize) {
811     case 2:  STK = SimpleTypeKind::Float16;  break;
812     case 4:  STK = SimpleTypeKind::Float32;  break;
813     case 6:  STK = SimpleTypeKind::Float48;  break;
814     case 8:  STK = SimpleTypeKind::Float64;  break;
815     case 10: STK = SimpleTypeKind::Float80;  break;
816     case 16: STK = SimpleTypeKind::Float128; break;
817     }
818     break;
819   case dwarf::DW_ATE_signed:
820     switch (ByteSize) {
821     case 1:  STK = SimpleTypeKind::SByte;      break;
822     case 2:  STK = SimpleTypeKind::Int16Short; break;
823     case 4:  STK = SimpleTypeKind::Int32;      break;
824     case 8:  STK = SimpleTypeKind::Int64Quad;  break;
825     case 16: STK = SimpleTypeKind::Int128Oct;  break;
826     }
827     break;
828   case dwarf::DW_ATE_unsigned:
829     switch (ByteSize) {
830     case 1:  STK = SimpleTypeKind::Byte;        break;
831     case 2:  STK = SimpleTypeKind::UInt16Short; break;
832     case 4:  STK = SimpleTypeKind::UInt32;      break;
833     case 8:  STK = SimpleTypeKind::UInt64Quad;  break;
834     case 16: STK = SimpleTypeKind::UInt128Oct;  break;
835     }
836     break;
837   case dwarf::DW_ATE_UTF:
838     switch (ByteSize) {
839     case 2: STK = SimpleTypeKind::Character16; break;
840     case 4: STK = SimpleTypeKind::Character32; break;
841     }
842     break;
843   case dwarf::DW_ATE_signed_char:
844     if (ByteSize == 1)
845       STK = SimpleTypeKind::SignedCharacter;
846     break;
847   case dwarf::DW_ATE_unsigned_char:
848     if (ByteSize == 1)
849       STK = SimpleTypeKind::UnsignedCharacter;
850     break;
851   default:
852     break;
853   }
854 
855   // Apply some fixups based on the source-level type name.
856   if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
857     STK = SimpleTypeKind::Int32Long;
858   if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
859     STK = SimpleTypeKind::UInt32Long;
860   if (STK == SimpleTypeKind::UInt16Short &&
861       (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
862     STK = SimpleTypeKind::WideCharacter;
863   if ((STK == SimpleTypeKind::SignedCharacter ||
864        STK == SimpleTypeKind::UnsignedCharacter) &&
865       Ty->getName() == "char")
866     STK = SimpleTypeKind::NarrowCharacter;
867 
868   return TypeIndex(STK);
869 }
870 
871 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
872   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
873 
874   // Pointers to simple types can use SimpleTypeMode, rather than having a
875   // dedicated pointer type record.
876   if (PointeeTI.isSimple() &&
877       PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
878       Ty->getTag() == dwarf::DW_TAG_pointer_type) {
879     SimpleTypeMode Mode = Ty->getSizeInBits() == 64
880                               ? SimpleTypeMode::NearPointer64
881                               : SimpleTypeMode::NearPointer32;
882     return TypeIndex(PointeeTI.getSimpleKind(), Mode);
883   }
884 
885   PointerKind PK =
886       Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
887   PointerMode PM = PointerMode::Pointer;
888   switch (Ty->getTag()) {
889   default: llvm_unreachable("not a pointer tag type");
890   case dwarf::DW_TAG_pointer_type:
891     PM = PointerMode::Pointer;
892     break;
893   case dwarf::DW_TAG_reference_type:
894     PM = PointerMode::LValueReference;
895     break;
896   case dwarf::DW_TAG_rvalue_reference_type:
897     PM = PointerMode::RValueReference;
898     break;
899   }
900   // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
901   // 'this' pointer, but not normal contexts. Figure out what we're supposed to
902   // do.
903   PointerOptions PO = PointerOptions::None;
904   PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
905   return TypeTable.writePointer(PR);
906 }
907 
908 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
909   assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
910   TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
911   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
912   PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
913                                                    : PointerKind::Near32;
914   PointerMode PM = isa<DISubroutineType>(Ty->getBaseType())
915                        ? PointerMode::PointerToMemberFunction
916                        : PointerMode::PointerToDataMember;
917   PointerOptions PO = PointerOptions::None; // FIXME
918   // FIXME: Thread this ABI info through metadata.
919   PointerToMemberRepresentation PMR = PointerToMemberRepresentation::Unknown;
920   MemberPointerInfo MPI(ClassTI, PMR);
921   PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8, MPI);
922   return TypeTable.writePointer(PR);
923 }
924 
925 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
926   ModifierOptions Mods = ModifierOptions::None;
927   bool IsModifier = true;
928   const DIType *BaseTy = Ty;
929   while (IsModifier && BaseTy) {
930     // FIXME: Need to add DWARF tag for __unaligned.
931     switch (BaseTy->getTag()) {
932     case dwarf::DW_TAG_const_type:
933       Mods |= ModifierOptions::Const;
934       break;
935     case dwarf::DW_TAG_volatile_type:
936       Mods |= ModifierOptions::Volatile;
937       break;
938     default:
939       IsModifier = false;
940       break;
941     }
942     if (IsModifier)
943       BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
944   }
945   TypeIndex ModifiedTI = getTypeIndex(BaseTy);
946   ModifierRecord MR(ModifiedTI, Mods);
947   return TypeTable.writeModifier(MR);
948 }
949 
950 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
951   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
952   for (DITypeRef ArgTypeRef : Ty->getTypeArray())
953     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
954 
955   TypeIndex ReturnTypeIndex = TypeIndex::Void();
956   ArrayRef<TypeIndex> ArgTypeIndices = None;
957   if (!ReturnAndArgTypeIndices.empty()) {
958     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
959     ReturnTypeIndex = ReturnAndArgTypesRef.front();
960     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
961   }
962 
963   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
964   TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
965 
966   // TODO: We should use DW_AT_calling_convention to determine what CC this
967   // procedure record should have.
968   // TODO: Some functions are member functions, we should use a more appropriate
969   // record for those.
970   ProcedureRecord Procedure(ReturnTypeIndex, CallingConvention::NearC,
971                             FunctionOptions::None, ArgTypeIndices.size(),
972                             ArgListIndex);
973   return TypeTable.writeProcedure(Procedure);
974 }
975 
976 static MemberAccess translateAccessFlags(unsigned RecordTag,
977                                          const DIType *Member) {
978   switch (Member->getFlags() & DINode::FlagAccessibility) {
979   case DINode::FlagPrivate:   return MemberAccess::Private;
980   case DINode::FlagPublic:    return MemberAccess::Public;
981   case DINode::FlagProtected: return MemberAccess::Protected;
982   case 0:
983     // If there was no explicit access control, provide the default for the tag.
984     return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
985                                                  : MemberAccess::Public;
986   }
987   llvm_unreachable("access flags are exclusive");
988 }
989 
990 static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
991   switch (Ty->getTag()) {
992   case dwarf::DW_TAG_class_type:     return TypeRecordKind::Class;
993   case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
994   }
995   llvm_unreachable("unexpected tag");
996 }
997 
998 /// Return the HasUniqueName option if it should be present in ClassOptions, or
999 /// None otherwise.
1000 static ClassOptions getRecordUniqueNameOption(const DICompositeType *Ty) {
1001   // MSVC always sets this flag now, even for local types. Clang doesn't always
1002   // appear to give every type a linkage name, which may be problematic for us.
1003   // FIXME: Investigate the consequences of not following them here.
1004   return !Ty->getIdentifier().empty() ? ClassOptions::HasUniqueName
1005                                       : ClassOptions::None;
1006 }
1007 
1008 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1009   // First, construct the forward decl.  Don't look into Ty to compute the
1010   // forward decl options, since it might not be available in all TUs.
1011   TypeRecordKind Kind = getRecordKind(Ty);
1012   ClassOptions CO =
1013       ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
1014   TypeIndex FwdDeclTI = TypeTable.writeClass(ClassRecord(
1015       Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(),
1016       TypeIndex(), TypeIndex(), 0, Ty->getName(), Ty->getIdentifier()));
1017   return FwdDeclTI;
1018 }
1019 
1020 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1021   // Construct the field list and complete type record.
1022   TypeRecordKind Kind = getRecordKind(Ty);
1023   // FIXME: Other ClassOptions, like ContainsNestedClass and NestedClass.
1024   ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1025   TypeIndex FTI;
1026   unsigned FieldCount;
1027   std::tie(FTI, FieldCount) = lowerRecordFieldList(Ty);
1028 
1029   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1030   return TypeTable.writeClass(ClassRecord(Kind, FieldCount, CO, HfaKind::None,
1031                                           WindowsRTClassKind::None, FTI,
1032                                           TypeIndex(), TypeIndex(), SizeInBytes,
1033                                           Ty->getName(), Ty->getIdentifier()));
1034   // FIXME: Make an LF_UDT_SRC_LINE record.
1035 }
1036 
1037 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1038   ClassOptions CO =
1039       ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
1040   TypeIndex FwdDeclTI =
1041       TypeTable.writeUnion(UnionRecord(0, CO, HfaKind::None, TypeIndex(), 0,
1042                                        Ty->getName(), Ty->getIdentifier()));
1043   return FwdDeclTI;
1044 }
1045 
1046 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
1047   ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1048   TypeIndex FTI;
1049   unsigned FieldCount;
1050   std::tie(FTI, FieldCount) = lowerRecordFieldList(Ty);
1051   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1052   return TypeTable.writeUnion(UnionRecord(FieldCount, CO, HfaKind::None, FTI,
1053                                           SizeInBytes, Ty->getName(),
1054                                           Ty->getIdentifier()));
1055   // FIXME: Make an LF_UDT_SRC_LINE record.
1056 }
1057 
1058 std::pair<TypeIndex, unsigned>
1059 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1060   // Manually count members. MSVC appears to count everything that generates a
1061   // field list record. Each individual overload in a method overload group
1062   // contributes to this count, even though the overload group is a single field
1063   // list record.
1064   unsigned MemberCount = 0;
1065   FieldListRecordBuilder Fields;
1066   for (const DINode *Element : Ty->getElements()) {
1067     // We assume that the frontend provides all members in source declaration
1068     // order, which is what MSVC does.
1069     if (!Element)
1070       continue;
1071     if (auto *SP = dyn_cast<DISubprogram>(Element)) {
1072       // C++ method.
1073       // FIXME: Overloaded methods are grouped together, so we'll need two
1074       // passes to group them.
1075       (void)SP;
1076     } else if (auto *Member = dyn_cast<DIDerivedType>(Element)) {
1077       if (Member->getTag() == dwarf::DW_TAG_member) {
1078         if (Member->isStaticMember()) {
1079           // Static data member.
1080           Fields.writeStaticDataMember(StaticDataMemberRecord(
1081               translateAccessFlags(Ty->getTag(), Member),
1082               getTypeIndex(Member->getBaseType()), Member->getName()));
1083           MemberCount++;
1084         } else {
1085           // Data member.
1086           // FIXME: Make a BitFieldRecord for bitfields.
1087           Fields.writeDataMember(DataMemberRecord(
1088               translateAccessFlags(Ty->getTag(), Member),
1089               getTypeIndex(Member->getBaseType()),
1090               Member->getOffsetInBits() / 8, Member->getName()));
1091           MemberCount++;
1092         }
1093       } else if (Member->getTag() == dwarf::DW_TAG_friend) {
1094         // Ignore friend members. It appears that MSVC emitted info about
1095         // friends in the past, but modern versions do not.
1096       }
1097       // FIXME: Get clang to emit nested types here and do something with
1098       // them.
1099     }
1100     // Skip other unrecognized kinds of elements.
1101   }
1102   return {TypeTable.writeFieldList(Fields), MemberCount};
1103 }
1104 
1105 TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef) {
1106   const DIType *Ty = TypeRef.resolve();
1107 
1108   // The null DIType is the void type. Don't try to hash it.
1109   if (!Ty)
1110     return TypeIndex::Void();
1111 
1112   // Check if we've already translated this type. Don't try to do a
1113   // get-or-create style insertion that caches the hash lookup across the
1114   // lowerType call. It will update the TypeIndices map.
1115   auto I = TypeIndices.find(Ty);
1116   if (I != TypeIndices.end())
1117     return I->second;
1118 
1119   TypeIndex TI = lowerType(Ty);
1120 
1121   recordTypeIndexForDINode(Ty, TI);
1122   return TI;
1123 }
1124 
1125 TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1126   const DIType *Ty = TypeRef.resolve();
1127 
1128   // The null DIType is the void type. Don't try to hash it.
1129   if (!Ty)
1130     return TypeIndex::Void();
1131 
1132   // If this is a non-record type, the complete type index is the same as the
1133   // normal type index. Just call getTypeIndex.
1134   switch (Ty->getTag()) {
1135   case dwarf::DW_TAG_class_type:
1136   case dwarf::DW_TAG_structure_type:
1137   case dwarf::DW_TAG_union_type:
1138     break;
1139   default:
1140     return getTypeIndex(Ty);
1141   }
1142 
1143   // Check if we've already translated the complete record type.  Lowering a
1144   // complete type should never trigger lowering another complete type, so we
1145   // can reuse the hash table lookup result.
1146   const auto *CTy = cast<DICompositeType>(Ty);
1147   auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1148   if (!InsertResult.second)
1149     return InsertResult.first->second;
1150 
1151   // Make sure the forward declaration is emitted first. It's unclear if this
1152   // is necessary, but MSVC does it, and we should follow suit until we can show
1153   // otherwise.
1154   TypeIndex FwdDeclTI = getTypeIndex(CTy);
1155 
1156   // Just use the forward decl if we don't have complete type info. This might
1157   // happen if the frontend is using modules and expects the complete definition
1158   // to be emitted elsewhere.
1159   if (CTy->isForwardDecl())
1160     return FwdDeclTI;
1161 
1162   TypeIndex TI;
1163   switch (CTy->getTag()) {
1164   case dwarf::DW_TAG_class_type:
1165   case dwarf::DW_TAG_structure_type:
1166     TI = lowerCompleteTypeClass(CTy);
1167     break;
1168   case dwarf::DW_TAG_union_type:
1169     TI = lowerCompleteTypeUnion(CTy);
1170     break;
1171   default:
1172     llvm_unreachable("not a record");
1173   }
1174 
1175   InsertResult.first->second = TI;
1176   return TI;
1177 }
1178 
1179 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
1180   // LocalSym record, see SymbolRecord.h for more info.
1181   MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
1182            *LocalEnd = MMI->getContext().createTempSymbol();
1183   OS.AddComment("Record length");
1184   OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
1185   OS.EmitLabel(LocalBegin);
1186 
1187   OS.AddComment("Record kind: S_LOCAL");
1188   OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
1189 
1190   LocalSymFlags Flags = LocalSymFlags::None;
1191   if (Var.DIVar->isParameter())
1192     Flags |= LocalSymFlags::IsParameter;
1193   if (Var.DefRanges.empty())
1194     Flags |= LocalSymFlags::IsOptimizedOut;
1195 
1196   OS.AddComment("TypeIndex");
1197   TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
1198   OS.EmitIntValue(TI.getIndex(), 4);
1199   OS.AddComment("Flags");
1200   OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
1201   // Truncate the name so we won't overflow the record length field.
1202   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
1203   OS.EmitLabel(LocalEnd);
1204 
1205   // Calculate the on disk prefix of the appropriate def range record. The
1206   // records and on disk formats are described in SymbolRecords.h. BytePrefix
1207   // should be big enough to hold all forms without memory allocation.
1208   SmallString<20> BytePrefix;
1209   for (const LocalVarDefRange &DefRange : Var.DefRanges) {
1210     BytePrefix.clear();
1211     // FIXME: Handle bitpieces.
1212     if (DefRange.StructOffset != 0)
1213       continue;
1214 
1215     if (DefRange.InMemory) {
1216       DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
1217                                  0, 0, ArrayRef<LocalVariableAddrGap>());
1218       ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
1219       BytePrefix +=
1220           StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
1221       BytePrefix +=
1222           StringRef(reinterpret_cast<const char *>(&Sym.Header),
1223                     sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
1224     } else {
1225       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
1226       // Unclear what matters here.
1227       DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
1228                               ArrayRef<LocalVariableAddrGap>());
1229       ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
1230       BytePrefix +=
1231           StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
1232       BytePrefix +=
1233           StringRef(reinterpret_cast<const char *>(&Sym.Header),
1234                     sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
1235     }
1236     OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
1237   }
1238 }
1239 
1240 void CodeViewDebug::endFunction(const MachineFunction *MF) {
1241   if (!Asm || !CurFn)  // We haven't created any debug info for this function.
1242     return;
1243 
1244   const Function *GV = MF->getFunction();
1245   assert(FnDebugInfo.count(GV));
1246   assert(CurFn == &FnDebugInfo[GV]);
1247 
1248   collectVariableInfo(GV->getSubprogram());
1249 
1250   DebugHandlerBase::endFunction(MF);
1251 
1252   // Don't emit anything if we don't have any line tables.
1253   if (!CurFn->HaveLineInfo) {
1254     FnDebugInfo.erase(GV);
1255     CurFn = nullptr;
1256     return;
1257   }
1258 
1259   CurFn->End = Asm->getFunctionEnd();
1260 
1261   CurFn = nullptr;
1262 }
1263 
1264 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
1265   DebugHandlerBase::beginInstruction(MI);
1266 
1267   // Ignore DBG_VALUE locations and function prologue.
1268   if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
1269     return;
1270   DebugLoc DL = MI->getDebugLoc();
1271   if (DL == PrevInstLoc || !DL)
1272     return;
1273   maybeRecordLocation(DL, Asm->MF);
1274 }
1275