xref: /llvm-project/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp (revision ff976c99c79d7a00f1c836a57c3e7499316553c4)
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/ADT/TinyPtrVector.h"
16 #include "llvm/DebugInfo/CodeView/CodeView.h"
17 #include "llvm/DebugInfo/CodeView/FieldListRecordBuilder.h"
18 #include "llvm/DebugInfo/CodeView/Line.h"
19 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
20 #include "llvm/DebugInfo/CodeView/TypeDumper.h"
21 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
22 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCSectionCOFF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/Support/COFF.h"
27 #include "llvm/Support/ScopedPrinter.h"
28 #include "llvm/Target/TargetFrameLowering.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Target/TargetSubtargetInfo.h"
31 
32 using namespace llvm;
33 using namespace llvm::codeview;
34 
35 CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
36     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
37   // If module doesn't have named metadata anchors or COFF debug section
38   // is not available, skip any debug info related stuff.
39   if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
40       !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
41     Asm = nullptr;
42     return;
43   }
44 
45   // Tell MMI that we have debug info.
46   MMI->setDebugInfoAvailability(true);
47 }
48 
49 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
50   std::string &Filepath = FileToFilepathMap[File];
51   if (!Filepath.empty())
52     return Filepath;
53 
54   StringRef Dir = File->getDirectory(), Filename = File->getFilename();
55 
56   // Clang emits directory and relative filename info into the IR, but CodeView
57   // operates on full paths.  We could change Clang to emit full paths too, but
58   // that would increase the IR size and probably not needed for other users.
59   // For now, just concatenate and canonicalize the path here.
60   if (Filename.find(':') == 1)
61     Filepath = Filename;
62   else
63     Filepath = (Dir + "\\" + Filename).str();
64 
65   // Canonicalize the path.  We have to do it textually because we may no longer
66   // have access the file in the filesystem.
67   // First, replace all slashes with backslashes.
68   std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
69 
70   // Remove all "\.\" with "\".
71   size_t Cursor = 0;
72   while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
73     Filepath.erase(Cursor, 2);
74 
75   // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
76   // path should be well-formatted, e.g. start with a drive letter, etc.
77   Cursor = 0;
78   while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
79     // Something's wrong if the path starts with "\..\", abort.
80     if (Cursor == 0)
81       break;
82 
83     size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
84     if (PrevSlash == std::string::npos)
85       // Something's wrong, abort.
86       break;
87 
88     Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
89     // The next ".." might be following the one we've just erased.
90     Cursor = PrevSlash;
91   }
92 
93   // Remove all duplicate backslashes.
94   Cursor = 0;
95   while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
96     Filepath.erase(Cursor, 1);
97 
98   return Filepath;
99 }
100 
101 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
102   unsigned NextId = FileIdMap.size() + 1;
103   auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
104   if (Insertion.second) {
105     // We have to compute the full filepath and emit a .cv_file directive.
106     StringRef FullPath = getFullFilepath(F);
107     NextId = OS.EmitCVFileDirective(NextId, FullPath);
108     assert(NextId == FileIdMap.size() && ".cv_file directive failed");
109   }
110   return Insertion.first->second;
111 }
112 
113 CodeViewDebug::InlineSite &
114 CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
115                              const DISubprogram *Inlinee) {
116   auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
117   InlineSite *Site = &SiteInsertion.first->second;
118   if (SiteInsertion.second) {
119     Site->SiteFuncId = NextFuncId++;
120     Site->Inlinee = Inlinee;
121     InlinedSubprograms.insert(Inlinee);
122     getFuncIdForSubprogram(Inlinee);
123   }
124   return *Site;
125 }
126 
127 static const DISubprogram *getQualifiedNameComponents(
128     const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
129   const DISubprogram *ClosestSubprogram = nullptr;
130   while (Scope != nullptr) {
131     if (ClosestSubprogram == nullptr)
132       ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
133     StringRef ScopeName = Scope->getName();
134     if (!ScopeName.empty())
135       QualifiedNameComponents.push_back(ScopeName);
136     Scope = Scope->getScope().resolve();
137   }
138   return ClosestSubprogram;
139 }
140 
141 static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
142                                     StringRef TypeName) {
143   std::string FullyQualifiedName;
144   for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
145     FullyQualifiedName.append(QualifiedNameComponent);
146     FullyQualifiedName.append("::");
147   }
148   FullyQualifiedName.append(TypeName);
149   return FullyQualifiedName;
150 }
151 
152 static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
153   SmallVector<StringRef, 5> QualifiedNameComponents;
154   getQualifiedNameComponents(Scope, QualifiedNameComponents);
155   return getQualifiedName(QualifiedNameComponents, Name);
156 }
157 
158 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
159   // No scope means global scope and that uses the zero index.
160   if (!Scope || isa<DIFile>(Scope))
161     return TypeIndex();
162 
163   assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
164 
165   // Check if we've already translated this scope.
166   auto I = TypeIndices.find({Scope, nullptr});
167   if (I != TypeIndices.end())
168     return I->second;
169 
170   // Build the fully qualified name of the scope.
171   std::string ScopeName =
172       getFullyQualifiedName(Scope->getScope().resolve(), Scope->getName());
173   TypeIndex TI =
174       TypeTable.writeStringId(StringIdRecord(TypeIndex(), ScopeName));
175   return recordTypeIndexForDINode(Scope, TI);
176 }
177 
178 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
179   // It's possible to ask for the FuncId of a function which doesn't have a
180   // subprogram: inlining a function with debug info into a function with none.
181   if (!SP)
182     return TypeIndex::None();
183 
184   // Check if we've already translated this subprogram.
185   auto I = TypeIndices.find({SP, nullptr});
186   if (I != TypeIndices.end())
187     return I->second;
188 
189   // The display name includes function template arguments. Drop them to match
190   // MSVC.
191   StringRef DisplayName = SP->getDisplayName().split('<').first;
192 
193   const DIScope *Scope = SP->getScope().resolve();
194   TypeIndex TI;
195   if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
196     // If the scope is a DICompositeType, then this must be a method. Member
197     // function types take some special handling, and require access to the
198     // subprogram.
199     TypeIndex ClassType = getTypeIndex(Class);
200     MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
201                                DisplayName);
202     TI = TypeTable.writeMemberFuncId(MFuncId);
203   } else {
204     // Otherwise, this must be a free function.
205     TypeIndex ParentScope = getScopeIndex(Scope);
206     FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
207     TI = TypeTable.writeFuncId(FuncId);
208   }
209 
210   return recordTypeIndexForDINode(SP, TI);
211 }
212 
213 TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
214                                                const DICompositeType *Class) {
215   // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
216   // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
217   auto I = TypeIndices.find({SP, nullptr});
218   if (I != TypeIndices.end())
219     return I->second;
220 
221   // FIXME: Get the ThisAdjustment off of SP when it is available.
222   TypeIndex TI =
223       lowerTypeMemberFunction(SP->getType(), Class, /*ThisAdjustment=*/0);
224 
225   return recordTypeIndexForDINode(SP, TI, Class);
226 }
227 
228 TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, TypeIndex TI,
229                                              const DIType *ClassTy) {
230   auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
231   (void)InsertResult;
232   assert(InsertResult.second && "DINode was already assigned a type index");
233   return TI;
234 }
235 
236 unsigned CodeViewDebug::getPointerSizeInBytes() {
237   return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
238 }
239 
240 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
241                                         const DILocation *InlinedAt) {
242   if (InlinedAt) {
243     // This variable was inlined. Associate it with the InlineSite.
244     const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
245     InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
246     Site.InlinedLocals.emplace_back(Var);
247   } else {
248     // This variable goes in the main ProcSym.
249     CurFn->Locals.emplace_back(Var);
250   }
251 }
252 
253 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
254                                const DILocation *Loc) {
255   auto B = Locs.begin(), E = Locs.end();
256   if (std::find(B, E, Loc) == E)
257     Locs.push_back(Loc);
258 }
259 
260 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
261                                         const MachineFunction *MF) {
262   // Skip this instruction if it has the same location as the previous one.
263   if (DL == CurFn->LastLoc)
264     return;
265 
266   const DIScope *Scope = DL.get()->getScope();
267   if (!Scope)
268     return;
269 
270   // Skip this line if it is longer than the maximum we can record.
271   LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
272   if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
273       LI.isNeverStepInto())
274     return;
275 
276   ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
277   if (CI.getStartColumn() != DL.getCol())
278     return;
279 
280   if (!CurFn->HaveLineInfo)
281     CurFn->HaveLineInfo = true;
282   unsigned FileId = 0;
283   if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
284     FileId = CurFn->LastFileId;
285   else
286     FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
287   CurFn->LastLoc = DL;
288 
289   unsigned FuncId = CurFn->FuncId;
290   if (const DILocation *SiteLoc = DL->getInlinedAt()) {
291     const DILocation *Loc = DL.get();
292 
293     // If this location was actually inlined from somewhere else, give it the ID
294     // of the inline call site.
295     FuncId =
296         getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
297 
298     // Ensure we have links in the tree of inline call sites.
299     bool FirstLoc = true;
300     while ((SiteLoc = Loc->getInlinedAt())) {
301       InlineSite &Site =
302           getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
303       if (!FirstLoc)
304         addLocIfNotPresent(Site.ChildSites, Loc);
305       FirstLoc = false;
306       Loc = SiteLoc;
307     }
308     addLocIfNotPresent(CurFn->ChildSites, Loc);
309   }
310 
311   OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
312                         /*PrologueEnd=*/false,
313                         /*IsStmt=*/false, DL->getFilename());
314 }
315 
316 void CodeViewDebug::emitCodeViewMagicVersion() {
317   OS.EmitValueToAlignment(4);
318   OS.AddComment("Debug section magic");
319   OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
320 }
321 
322 void CodeViewDebug::endModule() {
323   if (!Asm || !MMI->hasDebugInfo())
324     return;
325 
326   assert(Asm != nullptr);
327 
328   // The COFF .debug$S section consists of several subsections, each starting
329   // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
330   // of the payload followed by the payload itself.  The subsections are 4-byte
331   // aligned.
332 
333   // Use the generic .debug$S section, and make a subsection for all the inlined
334   // subprograms.
335   switchToDebugSectionForSymbol(nullptr);
336   emitInlineeLinesSubsection();
337 
338   // Emit per-function debug information.
339   for (auto &P : FnDebugInfo)
340     if (!P.first->isDeclarationForLinker())
341       emitDebugInfoForFunction(P.first, P.second);
342 
343   // Emit global variable debug information.
344   setCurrentSubprogram(nullptr);
345   emitDebugInfoForGlobals();
346 
347   // Emit retained types.
348   emitDebugInfoForRetainedTypes();
349 
350   // Switch back to the generic .debug$S section after potentially processing
351   // comdat symbol sections.
352   switchToDebugSectionForSymbol(nullptr);
353 
354   // Emit UDT records for any types used by global variables.
355   if (!GlobalUDTs.empty()) {
356     MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
357     emitDebugInfoForUDTs(GlobalUDTs);
358     endCVSubsection(SymbolsEnd);
359   }
360 
361   // This subsection holds a file index to offset in string table table.
362   OS.AddComment("File index to string table offset subsection");
363   OS.EmitCVFileChecksumsDirective();
364 
365   // This subsection holds the string table.
366   OS.AddComment("String table");
367   OS.EmitCVStringTableDirective();
368 
369   // Emit type information last, so that any types we translate while emitting
370   // function info are included.
371   emitTypeInformation();
372 
373   clear();
374 }
375 
376 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
377   // Microsoft's linker seems to have trouble with symbol names longer than
378   // 0xffd8 bytes.
379   S = S.substr(0, 0xffd8);
380   SmallString<32> NullTerminatedString(S);
381   NullTerminatedString.push_back('\0');
382   OS.EmitBytes(NullTerminatedString);
383 }
384 
385 void CodeViewDebug::emitTypeInformation() {
386   // Do nothing if we have no debug info or if no non-trivial types were emitted
387   // to TypeTable during codegen.
388   NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
389   if (!CU_Nodes)
390     return;
391   if (TypeTable.empty())
392     return;
393 
394   // Start the .debug$T section with 0x4.
395   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
396   emitCodeViewMagicVersion();
397 
398   SmallString<8> CommentPrefix;
399   if (OS.isVerboseAsm()) {
400     CommentPrefix += '\t';
401     CommentPrefix += Asm->MAI->getCommentString();
402     CommentPrefix += ' ';
403   }
404 
405   CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
406   TypeTable.ForEachRecord(
407       [&](TypeIndex Index, StringRef Record) {
408         if (OS.isVerboseAsm()) {
409           // Emit a block comment describing the type record for readability.
410           SmallString<512> CommentBlock;
411           raw_svector_ostream CommentOS(CommentBlock);
412           ScopedPrinter SP(CommentOS);
413           SP.setPrefix(CommentPrefix);
414           CVTD.setPrinter(&SP);
415           Error EC = CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
416           assert(!EC && "produced malformed type record");
417           consumeError(std::move(EC));
418           // emitRawComment will insert its own tab and comment string before
419           // the first line, so strip off our first one. It also prints its own
420           // newline.
421           OS.emitRawComment(
422               CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
423         }
424         OS.EmitBinaryData(Record);
425       });
426 }
427 
428 void CodeViewDebug::emitInlineeLinesSubsection() {
429   if (InlinedSubprograms.empty())
430     return;
431 
432   OS.AddComment("Inlinee lines subsection");
433   MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
434 
435   // We don't provide any extra file info.
436   // FIXME: Find out if debuggers use this info.
437   OS.AddComment("Inlinee lines signature");
438   OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
439 
440   for (const DISubprogram *SP : InlinedSubprograms) {
441     assert(TypeIndices.count({SP, nullptr}));
442     TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
443 
444     OS.AddBlankLine();
445     unsigned FileId = maybeRecordFile(SP->getFile());
446     OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
447                   SP->getFilename() + Twine(':') + Twine(SP->getLine()));
448     OS.AddBlankLine();
449     // The filechecksum table uses 8 byte entries for now, and file ids start at
450     // 1.
451     unsigned FileOffset = (FileId - 1) * 8;
452     OS.AddComment("Type index of inlined function");
453     OS.EmitIntValue(InlineeIdx.getIndex(), 4);
454     OS.AddComment("Offset into filechecksum table");
455     OS.EmitIntValue(FileOffset, 4);
456     OS.AddComment("Starting line number");
457     OS.EmitIntValue(SP->getLine(), 4);
458   }
459 
460   endCVSubsection(InlineEnd);
461 }
462 
463 void CodeViewDebug::collectInlineSiteChildren(
464     SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
465     const InlineSite &Site) {
466   for (const DILocation *ChildSiteLoc : Site.ChildSites) {
467     auto I = FI.InlineSites.find(ChildSiteLoc);
468     const InlineSite &ChildSite = I->second;
469     Children.push_back(ChildSite.SiteFuncId);
470     collectInlineSiteChildren(Children, FI, ChildSite);
471   }
472 }
473 
474 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
475                                         const DILocation *InlinedAt,
476                                         const InlineSite &Site) {
477   MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
478            *InlineEnd = MMI->getContext().createTempSymbol();
479 
480   assert(TypeIndices.count({Site.Inlinee, nullptr}));
481   TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
482 
483   // SymbolRecord
484   OS.AddComment("Record length");
485   OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2);   // RecordLength
486   OS.EmitLabel(InlineBegin);
487   OS.AddComment("Record kind: S_INLINESITE");
488   OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
489 
490   OS.AddComment("PtrParent");
491   OS.EmitIntValue(0, 4);
492   OS.AddComment("PtrEnd");
493   OS.EmitIntValue(0, 4);
494   OS.AddComment("Inlinee type index");
495   OS.EmitIntValue(InlineeIdx.getIndex(), 4);
496 
497   unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
498   unsigned StartLineNum = Site.Inlinee->getLine();
499   SmallVector<unsigned, 3> SecondaryFuncIds;
500   collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
501 
502   OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
503                                     FI.Begin, FI.End, SecondaryFuncIds);
504 
505   OS.EmitLabel(InlineEnd);
506 
507   emitLocalVariableList(Site.InlinedLocals);
508 
509   // Recurse on child inlined call sites before closing the scope.
510   for (const DILocation *ChildSite : Site.ChildSites) {
511     auto I = FI.InlineSites.find(ChildSite);
512     assert(I != FI.InlineSites.end() &&
513            "child site not in function inline site map");
514     emitInlinedCallSite(FI, ChildSite, I->second);
515   }
516 
517   // Close the scope.
518   OS.AddComment("Record length");
519   OS.EmitIntValue(2, 2);                                  // RecordLength
520   OS.AddComment("Record kind: S_INLINESITE_END");
521   OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
522 }
523 
524 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
525   // If we have a symbol, it may be in a section that is COMDAT. If so, find the
526   // comdat key. A section may be comdat because of -ffunction-sections or
527   // because it is comdat in the IR.
528   MCSectionCOFF *GVSec =
529       GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
530   const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
531 
532   MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
533       Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
534   DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
535 
536   OS.SwitchSection(DebugSec);
537 
538   // Emit the magic version number if this is the first time we've switched to
539   // this section.
540   if (ComdatDebugSections.insert(DebugSec).second)
541     emitCodeViewMagicVersion();
542 }
543 
544 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
545                                              FunctionInfo &FI) {
546   // For each function there is a separate subsection
547   // which holds the PC to file:line table.
548   const MCSymbol *Fn = Asm->getSymbol(GV);
549   assert(Fn);
550 
551   // Switch to the to a comdat section, if appropriate.
552   switchToDebugSectionForSymbol(Fn);
553 
554   std::string FuncName;
555   auto *SP = GV->getSubprogram();
556   setCurrentSubprogram(SP);
557 
558   // If we have a display name, build the fully qualified name by walking the
559   // chain of scopes.
560   if (SP != nullptr && !SP->getDisplayName().empty())
561     FuncName =
562         getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName());
563 
564   // If our DISubprogram name is empty, use the mangled name.
565   if (FuncName.empty())
566     FuncName = GlobalValue::getRealLinkageName(GV->getName());
567 
568   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
569   OS.AddComment("Symbol subsection for " + Twine(FuncName));
570   MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
571   {
572     MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
573              *ProcRecordEnd = MMI->getContext().createTempSymbol();
574     OS.AddComment("Record length");
575     OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
576     OS.EmitLabel(ProcRecordBegin);
577 
578     OS.AddComment("Record kind: S_GPROC32_ID");
579     OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
580 
581     // These fields are filled in by tools like CVPACK which run after the fact.
582     OS.AddComment("PtrParent");
583     OS.EmitIntValue(0, 4);
584     OS.AddComment("PtrEnd");
585     OS.EmitIntValue(0, 4);
586     OS.AddComment("PtrNext");
587     OS.EmitIntValue(0, 4);
588     // This is the important bit that tells the debugger where the function
589     // code is located and what's its size:
590     OS.AddComment("Code size");
591     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
592     OS.AddComment("Offset after prologue");
593     OS.EmitIntValue(0, 4);
594     OS.AddComment("Offset before epilogue");
595     OS.EmitIntValue(0, 4);
596     OS.AddComment("Function type index");
597     OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
598     OS.AddComment("Function section relative address");
599     OS.EmitCOFFSecRel32(Fn);
600     OS.AddComment("Function section index");
601     OS.EmitCOFFSectionIndex(Fn);
602     OS.AddComment("Flags");
603     OS.EmitIntValue(0, 1);
604     // Emit the function display name as a null-terminated string.
605     OS.AddComment("Function name");
606     // Truncate the name so we won't overflow the record length field.
607     emitNullTerminatedSymbolName(OS, FuncName);
608     OS.EmitLabel(ProcRecordEnd);
609 
610     emitLocalVariableList(FI.Locals);
611 
612     // Emit inlined call site information. Only emit functions inlined directly
613     // into the parent function. We'll emit the other sites recursively as part
614     // of their parent inline site.
615     for (const DILocation *InlinedAt : FI.ChildSites) {
616       auto I = FI.InlineSites.find(InlinedAt);
617       assert(I != FI.InlineSites.end() &&
618              "child site not in function inline site map");
619       emitInlinedCallSite(FI, InlinedAt, I->second);
620     }
621 
622     if (SP != nullptr)
623       emitDebugInfoForUDTs(LocalUDTs);
624 
625     // We're done with this function.
626     OS.AddComment("Record length");
627     OS.EmitIntValue(0x0002, 2);
628     OS.AddComment("Record kind: S_PROC_ID_END");
629     OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
630   }
631   endCVSubsection(SymbolsEnd);
632 
633   // We have an assembler directive that takes care of the whole line table.
634   OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
635 }
636 
637 CodeViewDebug::LocalVarDefRange
638 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
639   LocalVarDefRange DR;
640   DR.InMemory = -1;
641   DR.DataOffset = Offset;
642   assert(DR.DataOffset == Offset && "truncation");
643   DR.StructOffset = 0;
644   DR.CVRegister = CVRegister;
645   return DR;
646 }
647 
648 CodeViewDebug::LocalVarDefRange
649 CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
650   LocalVarDefRange DR;
651   DR.InMemory = 0;
652   DR.DataOffset = 0;
653   DR.StructOffset = 0;
654   DR.CVRegister = CVRegister;
655   return DR;
656 }
657 
658 void CodeViewDebug::collectVariableInfoFromMMITable(
659     DenseSet<InlinedVariable> &Processed) {
660   const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
661   const TargetFrameLowering *TFI = TSI.getFrameLowering();
662   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
663 
664   for (const MachineModuleInfo::VariableDbgInfo &VI :
665        MMI->getVariableDbgInfo()) {
666     if (!VI.Var)
667       continue;
668     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
669            "Expected inlined-at fields to agree");
670 
671     Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
672     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
673 
674     // If variable scope is not found then skip this variable.
675     if (!Scope)
676       continue;
677 
678     // Get the frame register used and the offset.
679     unsigned FrameReg = 0;
680     int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
681     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
682 
683     // Calculate the label ranges.
684     LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
685     for (const InsnRange &Range : Scope->getRanges()) {
686       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
687       const MCSymbol *End = getLabelAfterInsn(Range.second);
688       End = End ? End : Asm->getFunctionEnd();
689       DefRange.Ranges.emplace_back(Begin, End);
690     }
691 
692     LocalVariable Var;
693     Var.DIVar = VI.Var;
694     Var.DefRanges.emplace_back(std::move(DefRange));
695     recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
696   }
697 }
698 
699 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
700   DenseSet<InlinedVariable> Processed;
701   // Grab the variable info that was squirreled away in the MMI side-table.
702   collectVariableInfoFromMMITable(Processed);
703 
704   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
705 
706   for (const auto &I : DbgValues) {
707     InlinedVariable IV = I.first;
708     if (Processed.count(IV))
709       continue;
710     const DILocalVariable *DIVar = IV.first;
711     const DILocation *InlinedAt = IV.second;
712 
713     // Instruction ranges, specifying where IV is accessible.
714     const auto &Ranges = I.second;
715 
716     LexicalScope *Scope = nullptr;
717     if (InlinedAt)
718       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
719     else
720       Scope = LScopes.findLexicalScope(DIVar->getScope());
721     // If variable scope is not found then skip this variable.
722     if (!Scope)
723       continue;
724 
725     LocalVariable Var;
726     Var.DIVar = DIVar;
727 
728     // Calculate the definition ranges.
729     for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
730       const InsnRange &Range = *I;
731       const MachineInstr *DVInst = Range.first;
732       assert(DVInst->isDebugValue() && "Invalid History entry");
733       const DIExpression *DIExpr = DVInst->getDebugExpression();
734 
735       // Bail if there is a complex DWARF expression for now.
736       if (DIExpr && DIExpr->getNumElements() > 0)
737         continue;
738 
739       // Bail if operand 0 is not a valid register. This means the variable is a
740       // simple constant, or is described by a complex expression.
741       // FIXME: Find a way to represent constant variables, since they are
742       // relatively common.
743       unsigned Reg =
744           DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
745       if (Reg == 0)
746         continue;
747 
748       // Handle the two cases we can handle: indirect in memory and in register.
749       bool IsIndirect = DVInst->getOperand(1).isImm();
750       unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
751       {
752         LocalVarDefRange DefRange;
753         if (IsIndirect) {
754           int64_t Offset = DVInst->getOperand(1).getImm();
755           DefRange = createDefRangeMem(CVReg, Offset);
756         } else {
757           DefRange = createDefRangeReg(CVReg);
758         }
759         if (Var.DefRanges.empty() ||
760             Var.DefRanges.back().isDifferentLocation(DefRange)) {
761           Var.DefRanges.emplace_back(std::move(DefRange));
762         }
763       }
764 
765       // Compute the label range.
766       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
767       const MCSymbol *End = getLabelAfterInsn(Range.second);
768       if (!End) {
769         if (std::next(I) != E)
770           End = getLabelBeforeInsn(std::next(I)->first);
771         else
772           End = Asm->getFunctionEnd();
773       }
774 
775       // If the last range end is our begin, just extend the last range.
776       // Otherwise make a new range.
777       SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
778           Var.DefRanges.back().Ranges;
779       if (!Ranges.empty() && Ranges.back().second == Begin)
780         Ranges.back().second = End;
781       else
782         Ranges.emplace_back(Begin, End);
783 
784       // FIXME: Do more range combining.
785     }
786 
787     recordLocalVariable(std::move(Var), InlinedAt);
788   }
789 }
790 
791 void CodeViewDebug::beginFunction(const MachineFunction *MF) {
792   assert(!CurFn && "Can't process two functions at once!");
793 
794   if (!Asm || !MMI->hasDebugInfo())
795     return;
796 
797   DebugHandlerBase::beginFunction(MF);
798 
799   const Function *GV = MF->getFunction();
800   assert(FnDebugInfo.count(GV) == false);
801   CurFn = &FnDebugInfo[GV];
802   CurFn->FuncId = NextFuncId++;
803   CurFn->Begin = Asm->getFunctionBegin();
804 
805   // Find the end of the function prolog.  First known non-DBG_VALUE and
806   // non-frame setup location marks the beginning of the function body.
807   // FIXME: is there a simpler a way to do this? Can we just search
808   // for the first instruction of the function, not the last of the prolog?
809   DebugLoc PrologEndLoc;
810   bool EmptyPrologue = true;
811   for (const auto &MBB : *MF) {
812     for (const auto &MI : MBB) {
813       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
814           MI.getDebugLoc()) {
815         PrologEndLoc = MI.getDebugLoc();
816         break;
817       } else if (!MI.isDebugValue()) {
818         EmptyPrologue = false;
819       }
820     }
821   }
822 
823   // Record beginning of function if we have a non-empty prologue.
824   if (PrologEndLoc && !EmptyPrologue) {
825     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
826     maybeRecordLocation(FnStartDL, MF);
827   }
828 }
829 
830 void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
831   SmallVector<StringRef, 5> QualifiedNameComponents;
832   const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
833       Ty->getScope().resolve(), QualifiedNameComponents);
834 
835   std::string FullyQualifiedName =
836       getQualifiedName(QualifiedNameComponents, Ty->getName());
837 
838   if (ClosestSubprogram == nullptr)
839     GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
840   else if (ClosestSubprogram == CurrentSubprogram)
841     LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
842 
843   // TODO: What if the ClosestSubprogram is neither null or the current
844   // subprogram?  Currently, the UDT just gets dropped on the floor.
845   //
846   // The current behavior is not desirable.  To get maximal fidelity, we would
847   // need to perform all type translation before beginning emission of .debug$S
848   // and then make LocalUDTs a member of FunctionInfo
849 }
850 
851 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
852   // Generic dispatch for lowering an unknown type.
853   switch (Ty->getTag()) {
854   case dwarf::DW_TAG_array_type:
855     return lowerTypeArray(cast<DICompositeType>(Ty));
856   case dwarf::DW_TAG_typedef:
857     return lowerTypeAlias(cast<DIDerivedType>(Ty));
858   case dwarf::DW_TAG_base_type:
859     return lowerTypeBasic(cast<DIBasicType>(Ty));
860   case dwarf::DW_TAG_pointer_type:
861   case dwarf::DW_TAG_reference_type:
862   case dwarf::DW_TAG_rvalue_reference_type:
863     return lowerTypePointer(cast<DIDerivedType>(Ty));
864   case dwarf::DW_TAG_ptr_to_member_type:
865     return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
866   case dwarf::DW_TAG_const_type:
867   case dwarf::DW_TAG_volatile_type:
868     return lowerTypeModifier(cast<DIDerivedType>(Ty));
869   case dwarf::DW_TAG_subroutine_type:
870     if (ClassTy) {
871       // The member function type of a member function pointer has no
872       // ThisAdjustment.
873       return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
874                                      /*ThisAdjustment=*/0);
875     }
876     return lowerTypeFunction(cast<DISubroutineType>(Ty));
877   case dwarf::DW_TAG_enumeration_type:
878     return lowerTypeEnum(cast<DICompositeType>(Ty));
879   case dwarf::DW_TAG_class_type:
880   case dwarf::DW_TAG_structure_type:
881     return lowerTypeClass(cast<DICompositeType>(Ty));
882   case dwarf::DW_TAG_union_type:
883     return lowerTypeUnion(cast<DICompositeType>(Ty));
884   default:
885     // Use the null type index.
886     return TypeIndex();
887   }
888 }
889 
890 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
891   DITypeRef UnderlyingTypeRef = Ty->getBaseType();
892   TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
893   StringRef TypeName = Ty->getName();
894 
895   addToUDTs(Ty, UnderlyingTypeIndex);
896 
897   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
898       TypeName == "HRESULT")
899     return TypeIndex(SimpleTypeKind::HResult);
900   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
901       TypeName == "wchar_t")
902     return TypeIndex(SimpleTypeKind::WideCharacter);
903 
904   return UnderlyingTypeIndex;
905 }
906 
907 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
908   DITypeRef ElementTypeRef = Ty->getBaseType();
909   TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
910   // IndexType is size_t, which depends on the bitness of the target.
911   TypeIndex IndexType = Asm->MAI->getPointerSize() == 8
912                             ? TypeIndex(SimpleTypeKind::UInt64Quad)
913                             : TypeIndex(SimpleTypeKind::UInt32Long);
914   uint64_t Size = Ty->getSizeInBits() / 8;
915   assert(ElementTypeRef.resolve());
916   uint64_t ElementSize = ElementTypeRef.resolve()->getSizeInBits() / 8;
917 
918   bool UndefinedSubrange = false;
919 
920   // FIXME:
921   // There is a bug in the front-end where an array of a structure, which was
922   // declared as incomplete structure first, ends up not getting a size assigned
923   // to it. (PR28303)
924   // Example:
925   //   struct A(*p)[3];
926   //   struct A { int f; } a[3];
927   //
928   // This needs to be fixed in the front-end, but in the meantime we don't want
929   // to trigger an assertion because of this.
930   if (Ty->getSizeInBits() == 0) {
931     UndefinedSubrange = true;
932   }
933 
934   // Add subranges to array type.
935   DINodeArray Elements = Ty->getElements();
936   for (int i = Elements.size() - 1; i >= 0; --i) {
937     const DINode *Element = Elements[i];
938     assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
939 
940     const DISubrange *Subrange = cast<DISubrange>(Element);
941     assert(Subrange->getLowerBound() == 0 &&
942            "codeview doesn't support subranges with lower bounds");
943     int64_t Count = Subrange->getCount();
944 
945     // Variable Length Array (VLA) has Count equal to '-1'.
946     // Replace with Count '1', assume it is the minimum VLA length.
947     // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
948     if (Count == -1) {
949       Count = 1;
950       UndefinedSubrange = true;
951     }
952 
953     StringRef Name = (i == 0) ? Ty->getName() : "";
954     // Update the element size and element type index for subsequent subranges.
955     ElementSize *= Count;
956     ElementTypeIndex = TypeTable.writeArray(
957         ArrayRecord(ElementTypeIndex, IndexType, ElementSize, Name));
958   }
959 
960   (void)UndefinedSubrange;
961   assert(UndefinedSubrange || ElementSize == Size);
962 
963   return ElementTypeIndex;
964 }
965 
966 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
967   TypeIndex Index;
968   dwarf::TypeKind Kind;
969   uint32_t ByteSize;
970 
971   Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
972   ByteSize = Ty->getSizeInBits() / 8;
973 
974   SimpleTypeKind STK = SimpleTypeKind::None;
975   switch (Kind) {
976   case dwarf::DW_ATE_address:
977     // FIXME: Translate
978     break;
979   case dwarf::DW_ATE_boolean:
980     switch (ByteSize) {
981     case 1:  STK = SimpleTypeKind::Boolean8;   break;
982     case 2:  STK = SimpleTypeKind::Boolean16;  break;
983     case 4:  STK = SimpleTypeKind::Boolean32;  break;
984     case 8:  STK = SimpleTypeKind::Boolean64;  break;
985     case 16: STK = SimpleTypeKind::Boolean128; break;
986     }
987     break;
988   case dwarf::DW_ATE_complex_float:
989     switch (ByteSize) {
990     case 2:  STK = SimpleTypeKind::Complex16;  break;
991     case 4:  STK = SimpleTypeKind::Complex32;  break;
992     case 8:  STK = SimpleTypeKind::Complex64;  break;
993     case 10: STK = SimpleTypeKind::Complex80;  break;
994     case 16: STK = SimpleTypeKind::Complex128; break;
995     }
996     break;
997   case dwarf::DW_ATE_float:
998     switch (ByteSize) {
999     case 2:  STK = SimpleTypeKind::Float16;  break;
1000     case 4:  STK = SimpleTypeKind::Float32;  break;
1001     case 6:  STK = SimpleTypeKind::Float48;  break;
1002     case 8:  STK = SimpleTypeKind::Float64;  break;
1003     case 10: STK = SimpleTypeKind::Float80;  break;
1004     case 16: STK = SimpleTypeKind::Float128; break;
1005     }
1006     break;
1007   case dwarf::DW_ATE_signed:
1008     switch (ByteSize) {
1009     case 1:  STK = SimpleTypeKind::SByte;      break;
1010     case 2:  STK = SimpleTypeKind::Int16Short; break;
1011     case 4:  STK = SimpleTypeKind::Int32;      break;
1012     case 8:  STK = SimpleTypeKind::Int64Quad;  break;
1013     case 16: STK = SimpleTypeKind::Int128Oct;  break;
1014     }
1015     break;
1016   case dwarf::DW_ATE_unsigned:
1017     switch (ByteSize) {
1018     case 1:  STK = SimpleTypeKind::Byte;        break;
1019     case 2:  STK = SimpleTypeKind::UInt16Short; break;
1020     case 4:  STK = SimpleTypeKind::UInt32;      break;
1021     case 8:  STK = SimpleTypeKind::UInt64Quad;  break;
1022     case 16: STK = SimpleTypeKind::UInt128Oct;  break;
1023     }
1024     break;
1025   case dwarf::DW_ATE_UTF:
1026     switch (ByteSize) {
1027     case 2: STK = SimpleTypeKind::Character16; break;
1028     case 4: STK = SimpleTypeKind::Character32; break;
1029     }
1030     break;
1031   case dwarf::DW_ATE_signed_char:
1032     if (ByteSize == 1)
1033       STK = SimpleTypeKind::SignedCharacter;
1034     break;
1035   case dwarf::DW_ATE_unsigned_char:
1036     if (ByteSize == 1)
1037       STK = SimpleTypeKind::UnsignedCharacter;
1038     break;
1039   default:
1040     break;
1041   }
1042 
1043   // Apply some fixups based on the source-level type name.
1044   if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1045     STK = SimpleTypeKind::Int32Long;
1046   if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1047     STK = SimpleTypeKind::UInt32Long;
1048   if (STK == SimpleTypeKind::UInt16Short &&
1049       (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1050     STK = SimpleTypeKind::WideCharacter;
1051   if ((STK == SimpleTypeKind::SignedCharacter ||
1052        STK == SimpleTypeKind::UnsignedCharacter) &&
1053       Ty->getName() == "char")
1054     STK = SimpleTypeKind::NarrowCharacter;
1055 
1056   return TypeIndex(STK);
1057 }
1058 
1059 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1060   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1061 
1062   // While processing the type being pointed to it is possible we already
1063   // created this pointer type.  If so, we check here and return the existing
1064   // pointer type.
1065   auto I = TypeIndices.find({Ty, nullptr});
1066   if (I != TypeIndices.end())
1067     return I->second;
1068 
1069   // Pointers to simple types can use SimpleTypeMode, rather than having a
1070   // dedicated pointer type record.
1071   if (PointeeTI.isSimple() &&
1072       PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1073       Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1074     SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1075                               ? SimpleTypeMode::NearPointer64
1076                               : SimpleTypeMode::NearPointer32;
1077     return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1078   }
1079 
1080   PointerKind PK =
1081       Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1082   PointerMode PM = PointerMode::Pointer;
1083   switch (Ty->getTag()) {
1084   default: llvm_unreachable("not a pointer tag type");
1085   case dwarf::DW_TAG_pointer_type:
1086     PM = PointerMode::Pointer;
1087     break;
1088   case dwarf::DW_TAG_reference_type:
1089     PM = PointerMode::LValueReference;
1090     break;
1091   case dwarf::DW_TAG_rvalue_reference_type:
1092     PM = PointerMode::RValueReference;
1093     break;
1094   }
1095   // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1096   // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1097   // do.
1098   PointerOptions PO = PointerOptions::None;
1099   PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1100   return TypeTable.writePointer(PR);
1101 }
1102 
1103 static PointerToMemberRepresentation
1104 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1105   // SizeInBytes being zero generally implies that the member pointer type was
1106   // incomplete, which can happen if it is part of a function prototype. In this
1107   // case, use the unknown model instead of the general model.
1108   if (IsPMF) {
1109     switch (Flags & DINode::FlagPtrToMemberRep) {
1110     case 0:
1111       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1112                               : PointerToMemberRepresentation::GeneralFunction;
1113     case DINode::FlagSingleInheritance:
1114       return PointerToMemberRepresentation::SingleInheritanceFunction;
1115     case DINode::FlagMultipleInheritance:
1116       return PointerToMemberRepresentation::MultipleInheritanceFunction;
1117     case DINode::FlagVirtualInheritance:
1118       return PointerToMemberRepresentation::VirtualInheritanceFunction;
1119     }
1120   } else {
1121     switch (Flags & DINode::FlagPtrToMemberRep) {
1122     case 0:
1123       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1124                               : PointerToMemberRepresentation::GeneralData;
1125     case DINode::FlagSingleInheritance:
1126       return PointerToMemberRepresentation::SingleInheritanceData;
1127     case DINode::FlagMultipleInheritance:
1128       return PointerToMemberRepresentation::MultipleInheritanceData;
1129     case DINode::FlagVirtualInheritance:
1130       return PointerToMemberRepresentation::VirtualInheritanceData;
1131     }
1132   }
1133   llvm_unreachable("invalid ptr to member representation");
1134 }
1135 
1136 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1137   assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1138   TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1139   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
1140   PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
1141                                                    : PointerKind::Near32;
1142   bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1143   PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1144                          : PointerMode::PointerToDataMember;
1145   PointerOptions PO = PointerOptions::None; // FIXME
1146   assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1147   uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1148   MemberPointerInfo MPI(
1149       ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
1150   PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
1151   return TypeTable.writePointer(PR);
1152 }
1153 
1154 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1155 /// have a translation, use the NearC convention.
1156 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1157   switch (DwarfCC) {
1158   case dwarf::DW_CC_normal:             return CallingConvention::NearC;
1159   case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1160   case dwarf::DW_CC_BORLAND_thiscall:   return CallingConvention::ThisCall;
1161   case dwarf::DW_CC_BORLAND_stdcall:    return CallingConvention::NearStdCall;
1162   case dwarf::DW_CC_BORLAND_pascal:     return CallingConvention::NearPascal;
1163   case dwarf::DW_CC_LLVM_vectorcall:    return CallingConvention::NearVector;
1164   }
1165   return CallingConvention::NearC;
1166 }
1167 
1168 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1169   ModifierOptions Mods = ModifierOptions::None;
1170   bool IsModifier = true;
1171   const DIType *BaseTy = Ty;
1172   while (IsModifier && BaseTy) {
1173     // FIXME: Need to add DWARF tag for __unaligned.
1174     switch (BaseTy->getTag()) {
1175     case dwarf::DW_TAG_const_type:
1176       Mods |= ModifierOptions::Const;
1177       break;
1178     case dwarf::DW_TAG_volatile_type:
1179       Mods |= ModifierOptions::Volatile;
1180       break;
1181     default:
1182       IsModifier = false;
1183       break;
1184     }
1185     if (IsModifier)
1186       BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1187   }
1188   TypeIndex ModifiedTI = getTypeIndex(BaseTy);
1189 
1190   // While processing the type being pointed to, it is possible we already
1191   // created this modifier type.  If so, we check here and return the existing
1192   // modifier type.
1193   auto I = TypeIndices.find({Ty, nullptr});
1194   if (I != TypeIndices.end())
1195     return I->second;
1196 
1197   ModifierRecord MR(ModifiedTI, Mods);
1198   return TypeTable.writeModifier(MR);
1199 }
1200 
1201 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1202   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1203   for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1204     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1205 
1206   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1207   ArrayRef<TypeIndex> ArgTypeIndices = None;
1208   if (!ReturnAndArgTypeIndices.empty()) {
1209     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1210     ReturnTypeIndex = ReturnAndArgTypesRef.front();
1211     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1212   }
1213 
1214   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1215   TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
1216 
1217   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1218 
1219   ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1220                             ArgTypeIndices.size(), ArgListIndex);
1221   return TypeTable.writeProcedure(Procedure);
1222 }
1223 
1224 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
1225                                                  const DIType *ClassTy,
1226                                                  int ThisAdjustment) {
1227   // Lower the containing class type.
1228   TypeIndex ClassType = getTypeIndex(ClassTy);
1229 
1230   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1231   for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1232     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1233 
1234   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1235   ArrayRef<TypeIndex> ArgTypeIndices = None;
1236   if (!ReturnAndArgTypeIndices.empty()) {
1237     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1238     ReturnTypeIndex = ReturnAndArgTypesRef.front();
1239     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1240   }
1241   TypeIndex ThisTypeIndex = TypeIndex::Void();
1242   if (!ArgTypeIndices.empty()) {
1243     ThisTypeIndex = ArgTypeIndices.front();
1244     ArgTypeIndices = ArgTypeIndices.drop_front();
1245   }
1246 
1247   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1248   TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
1249 
1250   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1251 
1252   // TODO: Need to use the correct values for:
1253   //       FunctionOptions
1254   //       ThisPointerAdjustment.
1255   TypeIndex TI = TypeTable.writeMemberFunction(MemberFunctionRecord(
1256       ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FunctionOptions::None,
1257       ArgTypeIndices.size(), ArgListIndex, ThisAdjustment));
1258 
1259   return TI;
1260 }
1261 
1262 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1263   switch (Flags & DINode::FlagAccessibility) {
1264   case DINode::FlagPrivate:   return MemberAccess::Private;
1265   case DINode::FlagPublic:    return MemberAccess::Public;
1266   case DINode::FlagProtected: return MemberAccess::Protected;
1267   case 0:
1268     // If there was no explicit access control, provide the default for the tag.
1269     return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1270                                                  : MemberAccess::Public;
1271   }
1272   llvm_unreachable("access flags are exclusive");
1273 }
1274 
1275 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1276   if (SP->isArtificial())
1277     return MethodOptions::CompilerGenerated;
1278 
1279   // FIXME: Handle other MethodOptions.
1280 
1281   return MethodOptions::None;
1282 }
1283 
1284 static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1285                                            bool Introduced) {
1286   switch (SP->getVirtuality()) {
1287   case dwarf::DW_VIRTUALITY_none:
1288     break;
1289   case dwarf::DW_VIRTUALITY_virtual:
1290     return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1291   case dwarf::DW_VIRTUALITY_pure_virtual:
1292     return Introduced ? MethodKind::PureIntroducingVirtual
1293                       : MethodKind::PureVirtual;
1294   default:
1295     llvm_unreachable("unhandled virtuality case");
1296   }
1297 
1298   // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1299 
1300   return MethodKind::Vanilla;
1301 }
1302 
1303 static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1304   switch (Ty->getTag()) {
1305   case dwarf::DW_TAG_class_type:     return TypeRecordKind::Class;
1306   case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1307   }
1308   llvm_unreachable("unexpected tag");
1309 }
1310 
1311 /// Return the HasUniqueName option if it should be present in ClassOptions, or
1312 /// None otherwise.
1313 static ClassOptions getRecordUniqueNameOption(const DICompositeType *Ty) {
1314   // MSVC always sets this flag now, even for local types. Clang doesn't always
1315   // appear to give every type a linkage name, which may be problematic for us.
1316   // FIXME: Investigate the consequences of not following them here.
1317   return !Ty->getIdentifier().empty() ? ClassOptions::HasUniqueName
1318                                       : ClassOptions::None;
1319 }
1320 
1321 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
1322   ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1323   TypeIndex FTI;
1324   unsigned EnumeratorCount = 0;
1325 
1326   if (Ty->isForwardDecl()) {
1327     CO |= ClassOptions::ForwardReference;
1328   } else {
1329     FieldListRecordBuilder Fields;
1330     for (const DINode *Element : Ty->getElements()) {
1331       // We assume that the frontend provides all members in source declaration
1332       // order, which is what MSVC does.
1333       if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
1334         Fields.writeEnumerator(EnumeratorRecord(
1335             MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()),
1336             Enumerator->getName()));
1337         EnumeratorCount++;
1338       }
1339     }
1340     FTI = TypeTable.writeFieldList(Fields);
1341   }
1342 
1343   std::string FullName =
1344       getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
1345 
1346   return TypeTable.writeEnum(EnumRecord(EnumeratorCount, CO, FTI, FullName,
1347                                         Ty->getIdentifier(),
1348                                         getTypeIndex(Ty->getBaseType())));
1349 }
1350 
1351 //===----------------------------------------------------------------------===//
1352 // ClassInfo
1353 //===----------------------------------------------------------------------===//
1354 
1355 struct llvm::ClassInfo {
1356   struct MemberInfo {
1357     const DIDerivedType *MemberTypeNode;
1358     unsigned BaseOffset;
1359   };
1360   // [MemberInfo]
1361   typedef std::vector<MemberInfo> MemberList;
1362 
1363   typedef TinyPtrVector<const DISubprogram *> MethodsList;
1364   // MethodName -> MethodsList
1365   typedef MapVector<MDString *, MethodsList> MethodsMap;
1366 
1367   /// Base classes.
1368   std::vector<const DIDerivedType *> Inheritance;
1369 
1370   /// Direct members.
1371   MemberList Members;
1372   // Direct overloaded methods gathered by name.
1373   MethodsMap Methods;
1374 };
1375 
1376 void CodeViewDebug::clear() {
1377   assert(CurFn == nullptr);
1378   FileIdMap.clear();
1379   FnDebugInfo.clear();
1380   FileToFilepathMap.clear();
1381   LocalUDTs.clear();
1382   GlobalUDTs.clear();
1383   TypeIndices.clear();
1384   CompleteTypeIndices.clear();
1385 }
1386 
1387 void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1388                                       const DIDerivedType *DDTy) {
1389   if (!DDTy->getName().empty()) {
1390     Info.Members.push_back({DDTy, 0});
1391     return;
1392   }
1393   // An unnamed member must represent a nested struct or union. Add all the
1394   // indirect fields to the current record.
1395   assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
1396   unsigned Offset = DDTy->getOffsetInBits() / 8;
1397   const DIType *Ty = DDTy->getBaseType().resolve();
1398   const DICompositeType *DCTy = cast<DICompositeType>(Ty);
1399   ClassInfo NestedInfo = collectClassInfo(DCTy);
1400   for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
1401     Info.Members.push_back(
1402         {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
1403 }
1404 
1405 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1406   ClassInfo Info;
1407   // Add elements to structure type.
1408   DINodeArray Elements = Ty->getElements();
1409   for (auto *Element : Elements) {
1410     // We assume that the frontend provides all members in source declaration
1411     // order, which is what MSVC does.
1412     if (!Element)
1413       continue;
1414     if (auto *SP = dyn_cast<DISubprogram>(Element)) {
1415       Info.Methods[SP->getRawName()].push_back(SP);
1416     } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
1417       if (DDTy->getTag() == dwarf::DW_TAG_member) {
1418         collectMemberInfo(Info, DDTy);
1419       } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1420         Info.Inheritance.push_back(DDTy);
1421       } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1422         // Ignore friend members. It appears that MSVC emitted info about
1423         // friends in the past, but modern versions do not.
1424       }
1425       // FIXME: Get Clang to emit function virtual table here and handle it.
1426       // FIXME: Get clang to emit nested types here and do something with
1427       // them.
1428     }
1429     // Skip other unrecognized kinds of elements.
1430   }
1431   return Info;
1432 }
1433 
1434 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1435   // First, construct the forward decl.  Don't look into Ty to compute the
1436   // forward decl options, since it might not be available in all TUs.
1437   TypeRecordKind Kind = getRecordKind(Ty);
1438   ClassOptions CO =
1439       ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
1440   std::string FullName =
1441       getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
1442   TypeIndex FwdDeclTI = TypeTable.writeClass(ClassRecord(
1443       Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(),
1444       TypeIndex(), TypeIndex(), 0, FullName, Ty->getIdentifier()));
1445   if (!Ty->isForwardDecl())
1446     DeferredCompleteTypes.push_back(Ty);
1447   return FwdDeclTI;
1448 }
1449 
1450 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1451   // Construct the field list and complete type record.
1452   TypeRecordKind Kind = getRecordKind(Ty);
1453   // FIXME: Other ClassOptions, like ContainsNestedClass and NestedClass.
1454   ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1455   TypeIndex FieldTI;
1456   TypeIndex VShapeTI;
1457   unsigned FieldCount;
1458   std::tie(FieldTI, VShapeTI, FieldCount) = lowerRecordFieldList(Ty);
1459 
1460   std::string FullName =
1461       getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
1462 
1463   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1464 
1465   TypeIndex ClassTI = TypeTable.writeClass(ClassRecord(
1466       Kind, FieldCount, CO, HfaKind::None, WindowsRTClassKind::None, FieldTI,
1467       TypeIndex(), VShapeTI, SizeInBytes, FullName, Ty->getIdentifier()));
1468 
1469   TypeTable.writeUdtSourceLine(UdtSourceLineRecord(
1470       ClassTI, TypeTable.writeStringId(StringIdRecord(
1471                    TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1472       Ty->getLine()));
1473 
1474   addToUDTs(Ty, ClassTI);
1475 
1476   return ClassTI;
1477 }
1478 
1479 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1480   ClassOptions CO =
1481       ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
1482   std::string FullName =
1483       getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
1484   TypeIndex FwdDeclTI =
1485       TypeTable.writeUnion(UnionRecord(0, CO, HfaKind::None, TypeIndex(), 0,
1486                                        FullName, Ty->getIdentifier()));
1487   if (!Ty->isForwardDecl())
1488     DeferredCompleteTypes.push_back(Ty);
1489   return FwdDeclTI;
1490 }
1491 
1492 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
1493   ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1494   TypeIndex FieldTI;
1495   unsigned FieldCount;
1496   std::tie(FieldTI, std::ignore, FieldCount) = lowerRecordFieldList(Ty);
1497   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1498   std::string FullName =
1499       getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
1500 
1501   TypeIndex UnionTI = TypeTable.writeUnion(
1502       UnionRecord(FieldCount, CO, HfaKind::None, FieldTI, SizeInBytes, FullName,
1503                   Ty->getIdentifier()));
1504 
1505   TypeTable.writeUdtSourceLine(UdtSourceLineRecord(
1506       UnionTI, TypeTable.writeStringId(StringIdRecord(
1507                    TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1508       Ty->getLine()));
1509 
1510   addToUDTs(Ty, UnionTI);
1511 
1512   return UnionTI;
1513 }
1514 
1515 std::tuple<TypeIndex, TypeIndex, unsigned>
1516 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1517   // Manually count members. MSVC appears to count everything that generates a
1518   // field list record. Each individual overload in a method overload group
1519   // contributes to this count, even though the overload group is a single field
1520   // list record.
1521   unsigned MemberCount = 0;
1522   ClassInfo Info = collectClassInfo(Ty);
1523   FieldListRecordBuilder Fields;
1524 
1525   // Create base classes.
1526   for (const DIDerivedType *I : Info.Inheritance) {
1527     if (I->getFlags() & DINode::FlagVirtual) {
1528       // Virtual base.
1529       // FIXME: Emit VBPtrOffset when the frontend provides it.
1530       unsigned VBPtrOffset = 0;
1531       // FIXME: Despite the accessor name, the offset is really in bytes.
1532       unsigned VBTableIndex = I->getOffsetInBits() / 4;
1533       Fields.writeVirtualBaseClass(VirtualBaseClassRecord(
1534           translateAccessFlags(Ty->getTag(), I->getFlags()),
1535           getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
1536           VBTableIndex));
1537     } else {
1538       assert(I->getOffsetInBits() % 8 == 0 &&
1539              "bases must be on byte boundaries");
1540       Fields.writeBaseClass(BaseClassRecord(
1541           translateAccessFlags(Ty->getTag(), I->getFlags()),
1542           getTypeIndex(I->getBaseType()), I->getOffsetInBits() / 8));
1543     }
1544   }
1545 
1546   // Create members.
1547   for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1548     const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1549     TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
1550 
1551     if (Member->isStaticMember()) {
1552       Fields.writeStaticDataMember(StaticDataMemberRecord(
1553           translateAccessFlags(Ty->getTag(), Member->getFlags()),
1554           MemberBaseType, Member->getName()));
1555       MemberCount++;
1556       continue;
1557     }
1558 
1559     uint64_t OffsetInBytes = MemberInfo.BaseOffset;
1560 
1561     // FIXME: Handle bitfield type memeber.
1562     OffsetInBytes += Member->getOffsetInBits() / 8;
1563 
1564     Fields.writeDataMember(
1565         DataMemberRecord(translateAccessFlags(Ty->getTag(), Member->getFlags()),
1566                          MemberBaseType, OffsetInBytes, Member->getName()));
1567     MemberCount++;
1568   }
1569 
1570   // Create methods
1571   for (auto &MethodItr : Info.Methods) {
1572     StringRef Name = MethodItr.first->getString();
1573 
1574     std::vector<OneMethodRecord> Methods;
1575     for (const DISubprogram *SP : MethodItr.second) {
1576       TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1577       bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
1578 
1579       unsigned VFTableOffset = -1;
1580       if (Introduced)
1581         VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1582 
1583       Methods.push_back(
1584           OneMethodRecord(MethodType, translateMethodKindFlags(SP, Introduced),
1585                           translateMethodOptionFlags(SP),
1586                           translateAccessFlags(Ty->getTag(), SP->getFlags()),
1587                           VFTableOffset, Name));
1588       MemberCount++;
1589     }
1590     assert(Methods.size() > 0 && "Empty methods map entry");
1591     if (Methods.size() == 1)
1592       Fields.writeOneMethod(Methods[0]);
1593     else {
1594       TypeIndex MethodList =
1595           TypeTable.writeMethodOverloadList(MethodOverloadListRecord(Methods));
1596       Fields.writeOverloadedMethod(
1597           OverloadedMethodRecord(Methods.size(), MethodList, Name));
1598     }
1599   }
1600   TypeIndex FieldTI = TypeTable.writeFieldList(Fields);
1601   return std::make_tuple(FieldTI, TypeIndex(), MemberCount);
1602 }
1603 
1604 TypeIndex CodeViewDebug::getVBPTypeIndex() {
1605   if (!VBPType.getIndex()) {
1606     // Make a 'const int *' type.
1607     ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
1608     TypeIndex ModifiedTI = TypeTable.writeModifier(MR);
1609 
1610     PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1611                                                   : PointerKind::Near32;
1612     PointerMode PM = PointerMode::Pointer;
1613     PointerOptions PO = PointerOptions::None;
1614     PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1615 
1616     VBPType = TypeTable.writePointer(PR);
1617   }
1618 
1619   return VBPType;
1620 }
1621 
1622 struct CodeViewDebug::TypeLoweringScope {
1623   TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
1624   ~TypeLoweringScope() {
1625     // Don't decrement TypeEmissionLevel until after emitting deferred types, so
1626     // inner TypeLoweringScopes don't attempt to emit deferred types.
1627     if (CVD.TypeEmissionLevel == 1)
1628       CVD.emitDeferredCompleteTypes();
1629     --CVD.TypeEmissionLevel;
1630   }
1631   CodeViewDebug &CVD;
1632 };
1633 
1634 TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
1635   const DIType *Ty = TypeRef.resolve();
1636   const DIType *ClassTy = ClassTyRef.resolve();
1637 
1638   // The null DIType is the void type. Don't try to hash it.
1639   if (!Ty)
1640     return TypeIndex::Void();
1641 
1642   // Check if we've already translated this type. Don't try to do a
1643   // get-or-create style insertion that caches the hash lookup across the
1644   // lowerType call. It will update the TypeIndices map.
1645   auto I = TypeIndices.find({Ty, ClassTy});
1646   if (I != TypeIndices.end())
1647     return I->second;
1648 
1649   TypeIndex TI;
1650   {
1651     TypeLoweringScope S(*this);
1652     TI = lowerType(Ty, ClassTy);
1653     recordTypeIndexForDINode(Ty, TI, ClassTy);
1654   }
1655 
1656   return TI;
1657 }
1658 
1659 TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1660   const DIType *Ty = TypeRef.resolve();
1661 
1662   // The null DIType is the void type. Don't try to hash it.
1663   if (!Ty)
1664     return TypeIndex::Void();
1665 
1666   // If this is a non-record type, the complete type index is the same as the
1667   // normal type index. Just call getTypeIndex.
1668   switch (Ty->getTag()) {
1669   case dwarf::DW_TAG_class_type:
1670   case dwarf::DW_TAG_structure_type:
1671   case dwarf::DW_TAG_union_type:
1672     break;
1673   default:
1674     return getTypeIndex(Ty);
1675   }
1676 
1677   // Check if we've already translated the complete record type.  Lowering a
1678   // complete type should never trigger lowering another complete type, so we
1679   // can reuse the hash table lookup result.
1680   const auto *CTy = cast<DICompositeType>(Ty);
1681   auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1682   if (!InsertResult.second)
1683     return InsertResult.first->second;
1684 
1685   TypeLoweringScope S(*this);
1686 
1687   // Make sure the forward declaration is emitted first. It's unclear if this
1688   // is necessary, but MSVC does it, and we should follow suit until we can show
1689   // otherwise.
1690   TypeIndex FwdDeclTI = getTypeIndex(CTy);
1691 
1692   // Just use the forward decl if we don't have complete type info. This might
1693   // happen if the frontend is using modules and expects the complete definition
1694   // to be emitted elsewhere.
1695   if (CTy->isForwardDecl())
1696     return FwdDeclTI;
1697 
1698   TypeIndex TI;
1699   switch (CTy->getTag()) {
1700   case dwarf::DW_TAG_class_type:
1701   case dwarf::DW_TAG_structure_type:
1702     TI = lowerCompleteTypeClass(CTy);
1703     break;
1704   case dwarf::DW_TAG_union_type:
1705     TI = lowerCompleteTypeUnion(CTy);
1706     break;
1707   default:
1708     llvm_unreachable("not a record");
1709   }
1710 
1711   InsertResult.first->second = TI;
1712   return TI;
1713 }
1714 
1715 /// Emit all the deferred complete record types. Try to do this in FIFO order,
1716 /// and do this until fixpoint, as each complete record type typically references
1717 /// many other record types.
1718 void CodeViewDebug::emitDeferredCompleteTypes() {
1719   SmallVector<const DICompositeType *, 4> TypesToEmit;
1720   while (!DeferredCompleteTypes.empty()) {
1721     std::swap(DeferredCompleteTypes, TypesToEmit);
1722     for (const DICompositeType *RecordTy : TypesToEmit)
1723       getCompleteTypeIndex(RecordTy);
1724     TypesToEmit.clear();
1725   }
1726 }
1727 
1728 void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
1729   // Get the sorted list of parameters and emit them first.
1730   SmallVector<const LocalVariable *, 6> Params;
1731   for (const LocalVariable &L : Locals)
1732     if (L.DIVar->isParameter())
1733       Params.push_back(&L);
1734   std::sort(Params.begin(), Params.end(),
1735             [](const LocalVariable *L, const LocalVariable *R) {
1736               return L->DIVar->getArg() < R->DIVar->getArg();
1737             });
1738   for (const LocalVariable *L : Params)
1739     emitLocalVariable(*L);
1740 
1741   // Next emit all non-parameters in the order that we found them.
1742   for (const LocalVariable &L : Locals)
1743     if (!L.DIVar->isParameter())
1744       emitLocalVariable(L);
1745 }
1746 
1747 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
1748   // LocalSym record, see SymbolRecord.h for more info.
1749   MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
1750            *LocalEnd = MMI->getContext().createTempSymbol();
1751   OS.AddComment("Record length");
1752   OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
1753   OS.EmitLabel(LocalBegin);
1754 
1755   OS.AddComment("Record kind: S_LOCAL");
1756   OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
1757 
1758   LocalSymFlags Flags = LocalSymFlags::None;
1759   if (Var.DIVar->isParameter())
1760     Flags |= LocalSymFlags::IsParameter;
1761   if (Var.DefRanges.empty())
1762     Flags |= LocalSymFlags::IsOptimizedOut;
1763 
1764   OS.AddComment("TypeIndex");
1765   TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
1766   OS.EmitIntValue(TI.getIndex(), 4);
1767   OS.AddComment("Flags");
1768   OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
1769   // Truncate the name so we won't overflow the record length field.
1770   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
1771   OS.EmitLabel(LocalEnd);
1772 
1773   // Calculate the on disk prefix of the appropriate def range record. The
1774   // records and on disk formats are described in SymbolRecords.h. BytePrefix
1775   // should be big enough to hold all forms without memory allocation.
1776   SmallString<20> BytePrefix;
1777   for (const LocalVarDefRange &DefRange : Var.DefRanges) {
1778     BytePrefix.clear();
1779     // FIXME: Handle bitpieces.
1780     if (DefRange.StructOffset != 0)
1781       continue;
1782 
1783     if (DefRange.InMemory) {
1784       DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
1785                                  0, 0, ArrayRef<LocalVariableAddrGap>());
1786       ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
1787       BytePrefix +=
1788           StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
1789       BytePrefix +=
1790           StringRef(reinterpret_cast<const char *>(&Sym.Header),
1791                     sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
1792     } else {
1793       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
1794       // Unclear what matters here.
1795       DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
1796                               ArrayRef<LocalVariableAddrGap>());
1797       ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
1798       BytePrefix +=
1799           StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
1800       BytePrefix +=
1801           StringRef(reinterpret_cast<const char *>(&Sym.Header),
1802                     sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
1803     }
1804     OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
1805   }
1806 }
1807 
1808 void CodeViewDebug::endFunction(const MachineFunction *MF) {
1809   if (!Asm || !CurFn)  // We haven't created any debug info for this function.
1810     return;
1811 
1812   const Function *GV = MF->getFunction();
1813   assert(FnDebugInfo.count(GV));
1814   assert(CurFn == &FnDebugInfo[GV]);
1815 
1816   collectVariableInfo(GV->getSubprogram());
1817 
1818   DebugHandlerBase::endFunction(MF);
1819 
1820   // Don't emit anything if we don't have any line tables.
1821   if (!CurFn->HaveLineInfo) {
1822     FnDebugInfo.erase(GV);
1823     CurFn = nullptr;
1824     return;
1825   }
1826 
1827   CurFn->End = Asm->getFunctionEnd();
1828 
1829   CurFn = nullptr;
1830 }
1831 
1832 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
1833   DebugHandlerBase::beginInstruction(MI);
1834 
1835   // Ignore DBG_VALUE locations and function prologue.
1836   if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
1837     return;
1838   DebugLoc DL = MI->getDebugLoc();
1839   if (DL == PrevInstLoc || !DL)
1840     return;
1841   maybeRecordLocation(DL, Asm->MF);
1842 }
1843 
1844 MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
1845   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
1846            *EndLabel = MMI->getContext().createTempSymbol();
1847   OS.EmitIntValue(unsigned(Kind), 4);
1848   OS.AddComment("Subsection size");
1849   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
1850   OS.EmitLabel(BeginLabel);
1851   return EndLabel;
1852 }
1853 
1854 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
1855   OS.EmitLabel(EndLabel);
1856   // Every subsection must be aligned to a 4-byte boundary.
1857   OS.EmitValueToAlignment(4);
1858 }
1859 
1860 void CodeViewDebug::emitDebugInfoForUDTs(
1861     ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
1862   for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
1863     MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
1864              *UDTRecordEnd = MMI->getContext().createTempSymbol();
1865     OS.AddComment("Record length");
1866     OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
1867     OS.EmitLabel(UDTRecordBegin);
1868 
1869     OS.AddComment("Record kind: S_UDT");
1870     OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
1871 
1872     OS.AddComment("Type");
1873     OS.EmitIntValue(UDT.second.getIndex(), 4);
1874 
1875     emitNullTerminatedSymbolName(OS, UDT.first);
1876     OS.EmitLabel(UDTRecordEnd);
1877   }
1878 }
1879 
1880 void CodeViewDebug::emitDebugInfoForGlobals() {
1881   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
1882   for (const MDNode *Node : CUs->operands()) {
1883     const auto *CU = cast<DICompileUnit>(Node);
1884 
1885     // First, emit all globals that are not in a comdat in a single symbol
1886     // substream. MSVC doesn't like it if the substream is empty, so only open
1887     // it if we have at least one global to emit.
1888     switchToDebugSectionForSymbol(nullptr);
1889     MCSymbol *EndLabel = nullptr;
1890     for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
1891       if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
1892         if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
1893           if (!EndLabel) {
1894             OS.AddComment("Symbol subsection for globals");
1895             EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
1896           }
1897           emitDebugInfoForGlobal(G, Asm->getSymbol(GV));
1898         }
1899       }
1900     }
1901     if (EndLabel)
1902       endCVSubsection(EndLabel);
1903 
1904     // Second, emit each global that is in a comdat into its own .debug$S
1905     // section along with its own symbol substream.
1906     for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
1907       if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
1908         if (GV->hasComdat()) {
1909           MCSymbol *GVSym = Asm->getSymbol(GV);
1910           OS.AddComment("Symbol subsection for " +
1911                         Twine(GlobalValue::getRealLinkageName(GV->getName())));
1912           switchToDebugSectionForSymbol(GVSym);
1913           EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
1914           emitDebugInfoForGlobal(G, GVSym);
1915           endCVSubsection(EndLabel);
1916         }
1917       }
1918     }
1919   }
1920 }
1921 
1922 void CodeViewDebug::emitDebugInfoForRetainedTypes() {
1923   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
1924   for (const MDNode *Node : CUs->operands()) {
1925     for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
1926       if (DIType *RT = dyn_cast<DIType>(Ty)) {
1927         getTypeIndex(RT);
1928         // FIXME: Add to global/local DTU list.
1929       }
1930     }
1931   }
1932 }
1933 
1934 void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
1935                                            MCSymbol *GVSym) {
1936   // DataSym record, see SymbolRecord.h for more info.
1937   // FIXME: Thread local data, etc
1938   MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
1939            *DataEnd = MMI->getContext().createTempSymbol();
1940   OS.AddComment("Record length");
1941   OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
1942   OS.EmitLabel(DataBegin);
1943   OS.AddComment("Record kind: S_GDATA32");
1944   OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
1945   OS.AddComment("Type");
1946   OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
1947   OS.AddComment("DataOffset");
1948   OS.EmitCOFFSecRel32(GVSym);
1949   OS.AddComment("Segment");
1950   OS.EmitCOFFSectionIndex(GVSym);
1951   OS.AddComment("Name");
1952   emitNullTerminatedSymbolName(OS, DIGV->getName());
1953   OS.EmitLabel(DataEnd);
1954 }
1955