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