blob: 8dde4a1031b05f6f6625c9accaad02e85a3b9cdb [file] [log] [blame]
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001//===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp --*- C++ -*--===//
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002//
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//
Reid Kleckner70f5bc92016-01-14 19:25:04 +000010// This file contains support for writing Microsoft CodeView debug info.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000011//
12//===----------------------------------------------------------------------===//
13
Reid Kleckner70f5bc92016-01-14 19:25:04 +000014#include "CodeViewDebug.h"
Reid Kleckner156a7232016-06-22 18:31:14 +000015#include "llvm/ADT/TinyPtrVector.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000016#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000017#include "llvm/DebugInfo/CodeView/CodeView.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000018#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000019#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000020#include "llvm/DebugInfo/CodeView/TypeDumper.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000021#include "llvm/DebugInfo/CodeView/TypeIndex.h"
22#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000023#include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
Zachary Turnera3225b02016-07-29 20:56:36 +000024#include "llvm/DebugInfo/MSF/ByteStream.h"
25#include "llvm/DebugInfo/MSF/StreamReader.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000026#include "llvm/IR/Constants.h"
Reid Kleckner46cb48c2016-07-27 16:03:57 +000027#include "llvm/MC/MCAsmInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000028#include "llvm/MC/MCExpr.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000029#include "llvm/MC/MCSectionCOFF.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000030#include "llvm/MC/MCSymbol.h"
31#include "llvm/Support/COFF.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000032#include "llvm/Support/ScopedPrinter.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000033#include "llvm/Target/TargetFrameLowering.h"
Amjad Aboud76c9eb92016-06-18 10:25:07 +000034#include "llvm/Target/TargetRegisterInfo.h"
35#include "llvm/Target/TargetSubtargetInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000036
Reid Klecknerf9c275f2016-02-10 20:55:49 +000037using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000038using namespace llvm::codeview;
Zachary Turnerbac69d32016-07-22 19:56:05 +000039using namespace llvm::msf;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000040
Reid Klecknerf9c275f2016-02-10 20:55:49 +000041CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
Zachary Turnerc6d54da2016-09-09 17:46:17 +000042 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), Allocator(),
43 TypeTable(Allocator), CurFn(nullptr) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +000044 // If module doesn't have named metadata anchors or COFF debug section
45 // is not available, skip any debug info related stuff.
46 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
47 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
48 Asm = nullptr;
49 return;
50 }
51
52 // Tell MMI that we have debug info.
53 MMI->setDebugInfoAvailability(true);
54}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000055
Reid Kleckner9533af42016-01-16 00:09:09 +000056StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
57 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000058 if (!Filepath.empty())
59 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000060
Reid Kleckner9533af42016-01-16 00:09:09 +000061 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
62
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000063 // Clang emits directory and relative filename info into the IR, but CodeView
64 // operates on full paths. We could change Clang to emit full paths too, but
65 // that would increase the IR size and probably not needed for other users.
66 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000067 if (Filename.find(':') == 1)
68 Filepath = Filename;
69 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +000070 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000071
72 // Canonicalize the path. We have to do it textually because we may no longer
73 // have access the file in the filesystem.
74 // First, replace all slashes with backslashes.
75 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
76
77 // Remove all "\.\" with "\".
78 size_t Cursor = 0;
79 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
80 Filepath.erase(Cursor, 2);
81
82 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
83 // path should be well-formatted, e.g. start with a drive letter, etc.
84 Cursor = 0;
85 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
86 // Something's wrong if the path starts with "\..\", abort.
87 if (Cursor == 0)
88 break;
89
90 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
91 if (PrevSlash == std::string::npos)
92 // Something's wrong, abort.
93 break;
94
95 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
96 // The next ".." might be following the one we've just erased.
97 Cursor = PrevSlash;
98 }
99
100 // Remove all duplicate backslashes.
101 Cursor = 0;
102 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
103 Filepath.erase(Cursor, 1);
104
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000105 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000106}
107
Reid Kleckner2214ed82016-01-29 00:49:42 +0000108unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
109 unsigned NextId = FileIdMap.size() + 1;
110 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
111 if (Insertion.second) {
112 // We have to compute the full filepath and emit a .cv_file directive.
113 StringRef FullPath = getFullFilepath(F);
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000114 bool Success = OS.EmitCVFileDirective(NextId, FullPath);
115 (void)Success;
116 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000117 }
118 return Insertion.first->second;
119}
120
Reid Kleckner876330d2016-02-12 21:48:30 +0000121CodeViewDebug::InlineSite &
122CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
123 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000124 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
125 InlineSite *Site = &SiteInsertion.first->second;
126 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000127 unsigned ParentFuncId = CurFn->FuncId;
128 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
129 ParentFuncId =
130 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
131 .SiteFuncId;
132
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000133 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000134 OS.EmitCVInlineSiteIdDirective(
135 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
136 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000137 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000138 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000139 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000140 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000141 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000142}
143
David Majnemer6bdc24e2016-07-01 23:12:45 +0000144static StringRef getPrettyScopeName(const DIScope *Scope) {
145 StringRef ScopeName = Scope->getName();
146 if (!ScopeName.empty())
147 return ScopeName;
148
149 switch (Scope->getTag()) {
150 case dwarf::DW_TAG_enumeration_type:
151 case dwarf::DW_TAG_class_type:
152 case dwarf::DW_TAG_structure_type:
153 case dwarf::DW_TAG_union_type:
154 return "<unnamed-tag>";
155 case dwarf::DW_TAG_namespace:
156 return "`anonymous namespace'";
157 }
158
159 return StringRef();
160}
161
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000162static const DISubprogram *getQualifiedNameComponents(
163 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
164 const DISubprogram *ClosestSubprogram = nullptr;
165 while (Scope != nullptr) {
166 if (ClosestSubprogram == nullptr)
167 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000168 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000169 if (!ScopeName.empty())
170 QualifiedNameComponents.push_back(ScopeName);
171 Scope = Scope->getScope().resolve();
172 }
173 return ClosestSubprogram;
174}
175
176static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
177 StringRef TypeName) {
178 std::string FullyQualifiedName;
179 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
180 FullyQualifiedName.append(QualifiedNameComponent);
181 FullyQualifiedName.append("::");
182 }
183 FullyQualifiedName.append(TypeName);
184 return FullyQualifiedName;
185}
186
187static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
188 SmallVector<StringRef, 5> QualifiedNameComponents;
189 getQualifiedNameComponents(Scope, QualifiedNameComponents);
190 return getQualifiedName(QualifiedNameComponents, Name);
191}
192
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000193struct CodeViewDebug::TypeLoweringScope {
194 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
195 ~TypeLoweringScope() {
196 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
197 // inner TypeLoweringScopes don't attempt to emit deferred types.
198 if (CVD.TypeEmissionLevel == 1)
199 CVD.emitDeferredCompleteTypes();
200 --CVD.TypeEmissionLevel;
201 }
202 CodeViewDebug &CVD;
203};
204
David Majnemer6bdc24e2016-07-01 23:12:45 +0000205static std::string getFullyQualifiedName(const DIScope *Ty) {
206 const DIScope *Scope = Ty->getScope().resolve();
207 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
208}
209
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000210TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
211 // No scope means global scope and that uses the zero index.
212 if (!Scope || isa<DIFile>(Scope))
213 return TypeIndex();
214
215 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
216
217 // Check if we've already translated this scope.
218 auto I = TypeIndices.find({Scope, nullptr});
219 if (I != TypeIndices.end())
220 return I->second;
221
222 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000223 std::string ScopeName = getFullyQualifiedName(Scope);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000224 StringIdRecord SID(TypeIndex(), ScopeName);
225 auto TI = TypeTable.writeKnownType(SID);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000226 return recordTypeIndexForDINode(Scope, TI);
227}
228
David Majnemer75c3ebf2016-06-02 17:13:53 +0000229TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000230 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000231
David Majnemer75c3ebf2016-06-02 17:13:53 +0000232 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000233 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000234 if (I != TypeIndices.end())
235 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000236
Reid Klecknerac945e22016-06-17 16:11:20 +0000237 // The display name includes function template arguments. Drop them to match
238 // MSVC.
239 StringRef DisplayName = SP->getDisplayName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000240
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000241 const DIScope *Scope = SP->getScope().resolve();
242 TypeIndex TI;
243 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
244 // If the scope is a DICompositeType, then this must be a method. Member
245 // function types take some special handling, and require access to the
246 // subprogram.
247 TypeIndex ClassType = getTypeIndex(Class);
248 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
249 DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000250 TI = TypeTable.writeKnownType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000251 } else {
252 // Otherwise, this must be a free function.
253 TypeIndex ParentScope = getScopeIndex(Scope);
254 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000255 TI = TypeTable.writeKnownType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000256 }
257
258 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000259}
260
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000261TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
262 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000263 // Always use the method declaration as the key for the function type. The
264 // method declaration contains the this adjustment.
265 if (SP->getDeclaration())
266 SP = SP->getDeclaration();
267 assert(!SP->getDeclaration() && "should use declaration as key");
268
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000269 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
270 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000271 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000272 if (I != TypeIndices.end())
273 return I->second;
274
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000275 // Make sure complete type info for the class is emitted *after* the member
276 // function type, as the complete class type is likely to reference this
277 // member function type.
278 TypeLoweringScope S(*this);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000279 TypeIndex TI =
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000280 lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000281 return recordTypeIndexForDINode(SP, TI, Class);
282}
283
Amjad Aboudacee5682016-07-12 12:06:34 +0000284TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
285 TypeIndex TI,
286 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000287 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000288 (void)InsertResult;
289 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000290 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000291}
292
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000293unsigned CodeViewDebug::getPointerSizeInBytes() {
294 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
295}
296
Reid Kleckner876330d2016-02-12 21:48:30 +0000297void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
298 const DILocation *InlinedAt) {
299 if (InlinedAt) {
300 // This variable was inlined. Associate it with the InlineSite.
301 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
302 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
303 Site.InlinedLocals.emplace_back(Var);
304 } else {
305 // This variable goes in the main ProcSym.
306 CurFn->Locals.emplace_back(Var);
307 }
308}
309
Reid Kleckner829365a2016-02-11 19:41:47 +0000310static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
311 const DILocation *Loc) {
312 auto B = Locs.begin(), E = Locs.end();
313 if (std::find(B, E, Loc) == E)
314 Locs.push_back(Loc);
315}
316
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000317void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000318 const MachineFunction *MF) {
319 // Skip this instruction if it has the same location as the previous one.
320 if (DL == CurFn->LastLoc)
321 return;
322
323 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000324 if (!Scope)
325 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000326
David Majnemerc3340db2016-01-13 01:05:23 +0000327 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000328 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
329 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
330 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000331 return;
332
Reid Kleckner2214ed82016-01-29 00:49:42 +0000333 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
334 if (CI.getStartColumn() != DL.getCol())
335 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000336
Reid Kleckner2214ed82016-01-29 00:49:42 +0000337 if (!CurFn->HaveLineInfo)
338 CurFn->HaveLineInfo = true;
339 unsigned FileId = 0;
340 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
341 FileId = CurFn->LastFileId;
342 else
343 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
344 CurFn->LastLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000345
346 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000347 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000348 const DILocation *Loc = DL.get();
349
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000350 // If this location was actually inlined from somewhere else, give it the ID
351 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000352 FuncId =
353 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000354
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000355 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000356 bool FirstLoc = true;
357 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000358 InlineSite &Site =
359 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000360 if (!FirstLoc)
361 addLocIfNotPresent(Site.ChildSites, Loc);
362 FirstLoc = false;
363 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000364 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000365 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000366 }
367
Reid Klecknerdac21b42016-02-03 21:15:48 +0000368 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000369 /*PrologueEnd=*/false, /*IsStmt=*/false,
370 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000371}
372
Reid Kleckner5d122f82016-05-25 23:16:12 +0000373void CodeViewDebug::emitCodeViewMagicVersion() {
374 OS.EmitValueToAlignment(4);
375 OS.AddComment("Debug section magic");
376 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
377}
378
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000379void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000380 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000381 return;
382
383 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000384
385 // The COFF .debug$S section consists of several subsections, each starting
386 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
387 // of the payload followed by the payload itself. The subsections are 4-byte
388 // aligned.
389
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000390 // Use the generic .debug$S section, and make a subsection for all the inlined
391 // subprograms.
392 switchToDebugSectionForSymbol(nullptr);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000393
394 MCSymbol *CompilerInfo = beginCVSubsection(ModuleSubstreamKind::Symbols);
395 emitCompilerInformation();
396 endCVSubsection(CompilerInfo);
397
Reid Kleckner5d122f82016-05-25 23:16:12 +0000398 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000399
Reid Kleckner2214ed82016-01-29 00:49:42 +0000400 // Emit per-function debug information.
401 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000402 if (!P.first->isDeclarationForLinker())
403 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000404
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000405 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000406 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000407 emitDebugInfoForGlobals();
408
Hans Wennborgb510b452016-06-23 16:33:53 +0000409 // Emit retained types.
410 emitDebugInfoForRetainedTypes();
411
Reid Kleckner5d122f82016-05-25 23:16:12 +0000412 // Switch back to the generic .debug$S section after potentially processing
413 // comdat symbol sections.
414 switchToDebugSectionForSymbol(nullptr);
415
David Majnemer3128b102016-06-15 18:00:01 +0000416 // Emit UDT records for any types used by global variables.
417 if (!GlobalUDTs.empty()) {
418 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
419 emitDebugInfoForUDTs(GlobalUDTs);
420 endCVSubsection(SymbolsEnd);
421 }
422
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000423 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000424 OS.AddComment("File index to string table offset subsection");
425 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000426
427 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000428 OS.AddComment("String table");
429 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000430
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000431 // Emit type information last, so that any types we translate while emitting
432 // function info are included.
433 emitTypeInformation();
434
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000435 clear();
436}
437
David Majnemerb9456a52016-03-14 05:15:09 +0000438static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000439 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
440 // after a fixed length portion of the record. The fixed length portion should
441 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
442 // overall record size is less than the maximum allowed.
443 unsigned MaxFixedRecordLength = 0xF00;
444 SmallString<32> NullTerminatedString(
445 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
David Majnemerb9456a52016-03-14 05:15:09 +0000446 NullTerminatedString.push_back('\0');
447 OS.EmitBytes(NullTerminatedString);
448}
449
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000450void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000451 // Do nothing if we have no debug info or if no non-trivial types were emitted
452 // to TypeTable during codegen.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000453 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
Reid Klecknerfbd77872016-03-18 18:54:32 +0000454 if (!CU_Nodes)
455 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000456 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000457 return;
458
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000459 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000460 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000461 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000462
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000463 SmallString<8> CommentPrefix;
464 if (OS.isVerboseAsm()) {
465 CommentPrefix += '\t';
466 CommentPrefix += Asm->MAI->getCommentString();
467 CommentPrefix += ' ';
468 }
469
470 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000471 TypeTable.ForEachRecord([&](TypeIndex Index, ArrayRef<uint8_t> Record) {
472 if (OS.isVerboseAsm()) {
473 // Emit a block comment describing the type record for readability.
474 SmallString<512> CommentBlock;
475 raw_svector_ostream CommentOS(CommentBlock);
476 ScopedPrinter SP(CommentOS);
477 SP.setPrefix(CommentPrefix);
478 CVTD.setPrinter(&SP);
479 Error E = CVTD.dump(Record);
480 if (E) {
481 logAllUnhandledErrors(std::move(E), errs(), "error: ");
482 llvm_unreachable("produced malformed type record");
483 }
484 // emitRawComment will insert its own tab and comment string before
485 // the first line, so strip off our first one. It also prints its own
486 // newline.
487 OS.emitRawComment(
488 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
489 } else {
Reid Klecknerc92e9462016-07-01 18:05:56 +0000490#ifndef NDEBUG
Zachary Turner4efa0a42016-11-08 22:24:53 +0000491 // Assert that the type data is valid even if we aren't dumping
492 // comments. The MSVC linker doesn't do much type record validation,
493 // so the first link of an invalid type record can succeed while
494 // subsequent links will fail with LNK1285.
495 ByteStream Stream(Record);
496 CVTypeArray Types;
497 StreamReader Reader(Stream);
498 Error E = Reader.readArray(Types, Reader.getLength());
499 if (!E) {
500 TypeVisitorCallbacks C;
501 E = CVTypeVisitor(C).visitTypeStream(Types);
502 }
503 if (E) {
504 logAllUnhandledErrors(std::move(E), errs(), "error: ");
505 llvm_unreachable("produced malformed type record");
506 }
Reid Klecknerc92e9462016-07-01 18:05:56 +0000507#endif
Zachary Turner4efa0a42016-11-08 22:24:53 +0000508 }
509 StringRef S(reinterpret_cast<const char *>(Record.data()), Record.size());
510 OS.EmitBinaryData(S);
511 });
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000512}
513
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000514namespace {
515
516static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
517 switch (DWLang) {
518 case dwarf::DW_LANG_C:
519 case dwarf::DW_LANG_C89:
520 case dwarf::DW_LANG_C99:
521 case dwarf::DW_LANG_C11:
522 case dwarf::DW_LANG_ObjC:
523 return SourceLanguage::C;
524 case dwarf::DW_LANG_C_plus_plus:
525 case dwarf::DW_LANG_C_plus_plus_03:
526 case dwarf::DW_LANG_C_plus_plus_11:
527 case dwarf::DW_LANG_C_plus_plus_14:
528 return SourceLanguage::Cpp;
529 case dwarf::DW_LANG_Fortran77:
530 case dwarf::DW_LANG_Fortran90:
531 case dwarf::DW_LANG_Fortran03:
532 case dwarf::DW_LANG_Fortran08:
533 return SourceLanguage::Fortran;
534 case dwarf::DW_LANG_Pascal83:
535 return SourceLanguage::Pascal;
536 case dwarf::DW_LANG_Cobol74:
537 case dwarf::DW_LANG_Cobol85:
538 return SourceLanguage::Cobol;
539 case dwarf::DW_LANG_Java:
540 return SourceLanguage::Java;
541 default:
542 // There's no CodeView representation for this language, and CV doesn't
543 // have an "unknown" option for the language field, so we'll use MASM,
544 // as it's very low level.
545 return SourceLanguage::Masm;
546 }
547}
548
549struct Version {
550 int Part[4];
551};
552
553// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
554// the version number.
555static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000556 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000557 int N = 0;
558 for (const char C : Name) {
559 if (isdigit(C)) {
560 V.Part[N] *= 10;
561 V.Part[N] += C - '0';
562 } else if (C == '.') {
563 ++N;
564 if (N >= 4)
565 return V;
566 } else if (N > 0)
567 return V;
568 }
569 return V;
570}
571
572static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
573 switch (Type) {
574 case Triple::ArchType::x86:
575 return CPUType::Pentium3;
576 case Triple::ArchType::x86_64:
577 return CPUType::X64;
578 case Triple::ArchType::thumb:
579 return CPUType::Thumb;
580 default:
581 report_fatal_error("target architecture doesn't map to a CodeView "
582 "CPUType");
583 }
584}
585
586} // anonymous namespace
587
588void CodeViewDebug::emitCompilerInformation() {
589 MCContext &Context = MMI->getContext();
590 MCSymbol *CompilerBegin = Context.createTempSymbol(),
591 *CompilerEnd = Context.createTempSymbol();
592 OS.AddComment("Record length");
593 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
594 OS.EmitLabel(CompilerBegin);
595 OS.AddComment("Record kind: S_COMPILE3");
596 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
597 uint32_t Flags = 0;
598
599 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
600 const MDNode *Node = *CUs->operands().begin();
601 const auto *CU = cast<DICompileUnit>(Node);
602
603 // The low byte of the flags indicates the source language.
604 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
605 // TODO: Figure out which other flags need to be set.
606
607 OS.AddComment("Flags and language");
608 OS.EmitIntValue(Flags, 4);
609
610 OS.AddComment("CPUType");
611 CPUType CPU =
612 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
613 OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
614
615 StringRef CompilerVersion = CU->getProducer();
616 Version FrontVer = parseVersion(CompilerVersion);
617 OS.AddComment("Frontend version");
618 for (int N = 0; N < 4; ++N)
619 OS.EmitIntValue(FrontVer.Part[N], 2);
620
621 // Some Microsoft tools, like Binscope, expect a backend version number of at
622 // least 8.something, so we'll coerce the LLVM version into a form that
623 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000624 int Major = 1000 * LLVM_VERSION_MAJOR +
625 10 * LLVM_VERSION_MINOR +
626 LLVM_VERSION_PATCH;
627 // Clamp it for builds that use unusually large version numbers.
628 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
629 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000630 OS.AddComment("Backend version");
631 for (int N = 0; N < 4; ++N)
632 OS.EmitIntValue(BackVer.Part[N], 2);
633
634 OS.AddComment("Null-terminated compiler version string");
635 emitNullTerminatedSymbolName(OS, CompilerVersion);
636
637 OS.EmitLabel(CompilerEnd);
638}
639
Reid Kleckner5d122f82016-05-25 23:16:12 +0000640void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000641 if (InlinedSubprograms.empty())
642 return;
643
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000644 OS.AddComment("Inlinee lines subsection");
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000645 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000646
647 // We don't provide any extra file info.
648 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000649 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000650 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
651
652 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000653 assert(TypeIndices.count({SP, nullptr}));
654 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000655
David Majnemer30579ec2016-02-02 23:18:23 +0000656 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000657 unsigned FileId = maybeRecordFile(SP->getFile());
658 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
659 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000660 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000661 // The filechecksum table uses 8 byte entries for now, and file ids start at
662 // 1.
663 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000664 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000665 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000666 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000667 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000668 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000669 OS.EmitIntValue(SP->getLine(), 4);
670 }
671
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000672 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000673}
674
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000675void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
676 const DILocation *InlinedAt,
677 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000678 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
679 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000680
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000681 assert(TypeIndices.count({Site.Inlinee, nullptr}));
682 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000683
684 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000685 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000686 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000687 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000688 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000689 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000690
Reid Klecknerdac21b42016-02-03 21:15:48 +0000691 OS.AddComment("PtrParent");
692 OS.EmitIntValue(0, 4);
693 OS.AddComment("PtrEnd");
694 OS.EmitIntValue(0, 4);
695 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000696 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000697
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000698 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
699 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000700
701 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000702 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000703
704 OS.EmitLabel(InlineEnd);
705
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000706 emitLocalVariableList(Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000707
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000708 // Recurse on child inlined call sites before closing the scope.
709 for (const DILocation *ChildSite : Site.ChildSites) {
710 auto I = FI.InlineSites.find(ChildSite);
711 assert(I != FI.InlineSites.end() &&
712 "child site not in function inline site map");
713 emitInlinedCallSite(FI, ChildSite, I->second);
714 }
715
716 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000717 OS.AddComment("Record length");
718 OS.EmitIntValue(2, 2); // RecordLength
719 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000720 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000721}
722
Reid Kleckner5d122f82016-05-25 23:16:12 +0000723void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
724 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
725 // comdat key. A section may be comdat because of -ffunction-sections or
726 // because it is comdat in the IR.
727 MCSectionCOFF *GVSec =
728 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
729 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
730
731 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
732 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
733 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
734
735 OS.SwitchSection(DebugSec);
736
737 // Emit the magic version number if this is the first time we've switched to
738 // this section.
739 if (ComdatDebugSections.insert(DebugSec).second)
740 emitCodeViewMagicVersion();
741}
742
Reid Kleckner2214ed82016-01-29 00:49:42 +0000743void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
744 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000745 // For each function there is a separate subsection
746 // which holds the PC to file:line table.
747 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000748 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000749
Reid Kleckner5d122f82016-05-25 23:16:12 +0000750 // Switch to the to a comdat section, if appropriate.
751 switchToDebugSectionForSymbol(Fn);
752
Reid Klecknerac945e22016-06-17 16:11:20 +0000753 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000754 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000755 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000756 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000757
758 // If we have a display name, build the fully qualified name by walking the
759 // chain of scopes.
David Majnemer67f684e2016-07-28 05:03:22 +0000760 if (!SP->getDisplayName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000761 FuncName =
762 getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000763
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000764 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000765 if (FuncName.empty())
766 FuncName = GlobalValue::getRealLinkageName(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000767
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000768 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000769 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000770 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000771 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000772 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
773 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000774 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000775 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000776 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000777
Reid Kleckner4ad127f2016-09-14 21:49:21 +0000778 if (GV->hasLocalLinkage()) {
779 OS.AddComment("Record kind: S_LPROC32_ID");
780 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
781 } else {
782 OS.AddComment("Record kind: S_GPROC32_ID");
783 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
784 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000785
David Majnemer30579ec2016-02-02 23:18:23 +0000786 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000787 OS.AddComment("PtrParent");
788 OS.EmitIntValue(0, 4);
789 OS.AddComment("PtrEnd");
790 OS.EmitIntValue(0, 4);
791 OS.AddComment("PtrNext");
792 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000793 // This is the important bit that tells the debugger where the function
794 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000795 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000796 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000797 OS.AddComment("Offset after prologue");
798 OS.EmitIntValue(0, 4);
799 OS.AddComment("Offset before epilogue");
800 OS.EmitIntValue(0, 4);
801 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000802 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000803 OS.AddComment("Function section relative address");
Keno Fischerd4ea4c12016-12-08 01:56:23 +0000804 OS.EmitCOFFSecRel32(Fn);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000805 OS.AddComment("Function section index");
806 OS.EmitCOFFSectionIndex(Fn);
807 OS.AddComment("Flags");
808 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000809 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000810 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000811 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000812 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000813 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000814
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000815 emitLocalVariableList(FI.Locals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000816
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000817 // Emit inlined call site information. Only emit functions inlined directly
818 // into the parent function. We'll emit the other sites recursively as part
819 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000820 for (const DILocation *InlinedAt : FI.ChildSites) {
821 auto I = FI.InlineSites.find(InlinedAt);
822 assert(I != FI.InlineSites.end() &&
823 "child site not in function inline site map");
824 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000825 }
826
David Majnemer3128b102016-06-15 18:00:01 +0000827 if (SP != nullptr)
828 emitDebugInfoForUDTs(LocalUDTs);
829
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000830 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000831 OS.AddComment("Record length");
832 OS.EmitIntValue(0x0002, 2);
833 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000834 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000835 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000836 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000837
Reid Kleckner2214ed82016-01-29 00:49:42 +0000838 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000839 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000840}
841
Reid Kleckner876330d2016-02-12 21:48:30 +0000842CodeViewDebug::LocalVarDefRange
843CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
844 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000845 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000846 DR.DataOffset = Offset;
847 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000848 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000849 DR.StructOffset = 0;
850 DR.CVRegister = CVRegister;
851 return DR;
852}
853
854CodeViewDebug::LocalVarDefRange
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000855CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
856 int Offset, bool IsSubfield,
857 uint16_t StructOffset) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000858 LocalVarDefRange DR;
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000859 DR.InMemory = InMemory;
860 DR.DataOffset = Offset;
861 DR.IsSubfield = IsSubfield;
862 DR.StructOffset = StructOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +0000863 DR.CVRegister = CVRegister;
864 return DR;
865}
866
Matthias Braunef331ef2016-11-30 23:48:50 +0000867void CodeViewDebug::collectVariableInfoFromMFTable(
Reid Kleckner876330d2016-02-12 21:48:30 +0000868 DenseSet<InlinedVariable> &Processed) {
Matthias Braunef331ef2016-11-30 23:48:50 +0000869 const MachineFunction &MF = *Asm->MF;
870 const TargetSubtargetInfo &TSI = MF.getSubtarget();
Reid Kleckner876330d2016-02-12 21:48:30 +0000871 const TargetFrameLowering *TFI = TSI.getFrameLowering();
872 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
873
Matthias Braunef331ef2016-11-30 23:48:50 +0000874 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000875 if (!VI.Var)
876 continue;
877 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
878 "Expected inlined-at fields to agree");
879
Reid Kleckner876330d2016-02-12 21:48:30 +0000880 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000881 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
882
883 // If variable scope is not found then skip this variable.
884 if (!Scope)
885 continue;
886
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000887 // Get the frame register used and the offset.
888 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000889 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
890 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000891
892 // Calculate the label ranges.
Reid Kleckner876330d2016-02-12 21:48:30 +0000893 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000894 for (const InsnRange &Range : Scope->getRanges()) {
895 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
896 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000897 End = End ? End : Asm->getFunctionEnd();
898 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000899 }
900
Reid Kleckner876330d2016-02-12 21:48:30 +0000901 LocalVariable Var;
902 Var.DIVar = VI.Var;
903 Var.DefRanges.emplace_back(std::move(DefRange));
904 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
905 }
906}
907
908void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
909 DenseSet<InlinedVariable> Processed;
910 // Grab the variable info that was squirreled away in the MMI side-table.
Matthias Braunef331ef2016-11-30 23:48:50 +0000911 collectVariableInfoFromMFTable(Processed);
Reid Kleckner876330d2016-02-12 21:48:30 +0000912
913 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
914
915 for (const auto &I : DbgValues) {
916 InlinedVariable IV = I.first;
917 if (Processed.count(IV))
918 continue;
919 const DILocalVariable *DIVar = IV.first;
920 const DILocation *InlinedAt = IV.second;
921
922 // Instruction ranges, specifying where IV is accessible.
923 const auto &Ranges = I.second;
924
925 LexicalScope *Scope = nullptr;
926 if (InlinedAt)
927 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
928 else
929 Scope = LScopes.findLexicalScope(DIVar->getScope());
930 // If variable scope is not found then skip this variable.
931 if (!Scope)
932 continue;
933
934 LocalVariable Var;
935 Var.DIVar = DIVar;
936
937 // Calculate the definition ranges.
938 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
939 const InsnRange &Range = *I;
940 const MachineInstr *DVInst = Range.first;
941 assert(DVInst->isDebugValue() && "Invalid History entry");
942 const DIExpression *DIExpr = DVInst->getDebugExpression();
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000943 bool IsSubfield = false;
944 unsigned StructOffset = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000945
Adrian Prantl941fa752016-12-05 18:04:47 +0000946 // Handle fragments.
Adrian Prantl49797ca2016-12-22 05:27:12 +0000947 auto Fragment = DIExpr->getFragmentInfo();
948 if (DIExpr && Fragment) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000949 IsSubfield = true;
Adrian Prantl49797ca2016-12-22 05:27:12 +0000950 StructOffset = Fragment->OffsetInBits / 8;
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000951 } else if (DIExpr && DIExpr->getNumElements() > 0) {
952 continue; // Ignore unrecognized exprs.
953 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000954
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000955 // Bail if operand 0 is not a valid register. This means the variable is a
956 // simple constant, or is described by a complex expression.
957 // FIXME: Find a way to represent constant variables, since they are
958 // relatively common.
959 unsigned Reg =
960 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
961 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +0000962 continue;
963
Reid Kleckner876330d2016-02-12 21:48:30 +0000964 // Handle the two cases we can handle: indirect in memory and in register.
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000965 unsigned CVReg = TRI->getCodeViewRegNum(Reg);
966 bool InMemory = DVInst->getOperand(1).isImm();
967 int Offset = InMemory ? DVInst->getOperand(1).getImm() : 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000968 {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000969 LocalVarDefRange DR;
970 DR.CVRegister = CVReg;
971 DR.InMemory = InMemory;
972 DR.DataOffset = Offset;
973 DR.IsSubfield = IsSubfield;
974 DR.StructOffset = StructOffset;
975
Reid Kleckner876330d2016-02-12 21:48:30 +0000976 if (Var.DefRanges.empty() ||
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000977 Var.DefRanges.back().isDifferentLocation(DR)) {
978 Var.DefRanges.emplace_back(std::move(DR));
Reid Kleckner876330d2016-02-12 21:48:30 +0000979 }
980 }
981
982 // Compute the label range.
983 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
984 const MCSymbol *End = getLabelAfterInsn(Range.second);
985 if (!End) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000986 // This range is valid until the next overlapping bitpiece. In the
987 // common case, ranges will not be bitpieces, so they will overlap.
988 auto J = std::next(I);
Adrian Prantl941fa752016-12-05 18:04:47 +0000989 while (J != E &&
990 !fragmentsOverlap(DIExpr, J->first->getDebugExpression()))
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000991 ++J;
992 if (J != E)
993 End = getLabelBeforeInsn(J->first);
Reid Kleckner876330d2016-02-12 21:48:30 +0000994 else
995 End = Asm->getFunctionEnd();
996 }
997
998 // If the last range end is our begin, just extend the last range.
999 // Otherwise make a new range.
1000 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
1001 Var.DefRanges.back().Ranges;
1002 if (!Ranges.empty() && Ranges.back().second == Begin)
1003 Ranges.back().second = End;
1004 else
1005 Ranges.emplace_back(Begin, End);
1006
1007 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001008 }
Reid Kleckner876330d2016-02-12 21:48:30 +00001009
1010 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001011 }
1012}
1013
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001014void CodeViewDebug::beginFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001015 assert(!CurFn && "Can't process two functions at once!");
1016
David Majnemer67f684e2016-07-28 05:03:22 +00001017 if (!Asm || !MMI->hasDebugInfo() || !MF->getFunction()->getSubprogram())
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001018 return;
1019
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001020 DebugHandlerBase::beginFunction(MF);
1021
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001022 const Function *GV = MF->getFunction();
1023 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001024 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +00001025 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001026 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001027
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001028 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1029
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001030 // Find the end of the function prolog. First known non-DBG_VALUE and
1031 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001032 // FIXME: is there a simpler a way to do this? Can we just search
1033 // for the first instruction of the function, not the last of the prolog?
1034 DebugLoc PrologEndLoc;
1035 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001036 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001037 for (const auto &MI : MBB) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001038 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1039 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001040 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001041 break;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001042 } else if (!MI.isDebugValue()) {
1043 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001044 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001045 }
1046 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001047
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001048 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001049 if (PrologEndLoc && !EmptyPrologue) {
1050 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001051 maybeRecordLocation(FnStartDL, MF);
1052 }
1053}
1054
Hans Wennborg4b63a982016-06-23 22:57:25 +00001055void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001056 // Don't record empty UDTs.
1057 if (Ty->getName().empty())
1058 return;
1059
Hans Wennborg4b63a982016-06-23 22:57:25 +00001060 SmallVector<StringRef, 5> QualifiedNameComponents;
1061 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1062 Ty->getScope().resolve(), QualifiedNameComponents);
1063
1064 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001065 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001066
1067 if (ClosestSubprogram == nullptr)
1068 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1069 else if (ClosestSubprogram == CurrentSubprogram)
1070 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1071
1072 // TODO: What if the ClosestSubprogram is neither null or the current
1073 // subprogram? Currently, the UDT just gets dropped on the floor.
1074 //
1075 // The current behavior is not desirable. To get maximal fidelity, we would
1076 // need to perform all type translation before beginning emission of .debug$S
1077 // and then make LocalUDTs a member of FunctionInfo
1078}
1079
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001080TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001081 // Generic dispatch for lowering an unknown type.
1082 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001083 case dwarf::DW_TAG_array_type:
1084 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001085 case dwarf::DW_TAG_typedef:
1086 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001087 case dwarf::DW_TAG_base_type:
1088 return lowerTypeBasic(cast<DIBasicType>(Ty));
1089 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001090 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1091 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1092 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001093 case dwarf::DW_TAG_reference_type:
1094 case dwarf::DW_TAG_rvalue_reference_type:
1095 return lowerTypePointer(cast<DIDerivedType>(Ty));
1096 case dwarf::DW_TAG_ptr_to_member_type:
1097 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1098 case dwarf::DW_TAG_const_type:
1099 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001100 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001101 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001102 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001103 if (ClassTy) {
1104 // The member function type of a member function pointer has no
1105 // ThisAdjustment.
1106 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1107 /*ThisAdjustment=*/0);
1108 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001109 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001110 case dwarf::DW_TAG_enumeration_type:
1111 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001112 case dwarf::DW_TAG_class_type:
1113 case dwarf::DW_TAG_structure_type:
1114 return lowerTypeClass(cast<DICompositeType>(Ty));
1115 case dwarf::DW_TAG_union_type:
1116 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001117 default:
1118 // Use the null type index.
1119 return TypeIndex();
1120 }
1121}
1122
David Majnemerd065e232016-06-02 06:21:37 +00001123TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001124 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1125 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001126 StringRef TypeName = Ty->getName();
1127
Hans Wennborg4b63a982016-06-23 22:57:25 +00001128 addToUDTs(Ty, UnderlyingTypeIndex);
David Majnemer3128b102016-06-15 18:00:01 +00001129
David Majnemerd065e232016-06-02 06:21:37 +00001130 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001131 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001132 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001133 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001134 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001135 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001136
David Majnemerd065e232016-06-02 06:21:37 +00001137 return UnderlyingTypeIndex;
1138}
1139
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001140TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1141 DITypeRef ElementTypeRef = Ty->getBaseType();
1142 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1143 // IndexType is size_t, which depends on the bitness of the target.
1144 TypeIndex IndexType = Asm->MAI->getPointerSize() == 8
1145 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1146 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001147
1148 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1149
Amjad Aboudacee5682016-07-12 12:06:34 +00001150
Reid Kleckner10762882016-09-09 17:29:36 +00001151 // We want to assert that the element type multiplied by the array lengths
1152 // match the size of the overall array. However, if we don't have complete
1153 // type information for the base type, we can't make this assertion. This
1154 // happens if limited debug info is enabled in this case:
1155 // struct VTableOptzn { VTableOptzn(); virtual ~VTableOptzn(); };
1156 // VTableOptzn array[3];
1157 // The DICompositeType of VTableOptzn will have size zero, and the array will
1158 // have size 3 * sizeof(void*), and we should avoid asserting.
1159 //
1160 // There is a related bug in the front-end where an array of a structure,
1161 // which was declared as incomplete structure first, ends up not getting a
1162 // size assigned to it. (PR28303)
Amjad Aboudacee5682016-07-12 12:06:34 +00001163 // Example:
1164 // struct A(*p)[3];
1165 // struct A { int f; } a[3];
Reid Kleckner10762882016-09-09 17:29:36 +00001166 bool PartiallyIncomplete = false;
1167 if (Ty->getSizeInBits() == 0 || ElementSize == 0) {
1168 PartiallyIncomplete = true;
Amjad Aboudacee5682016-07-12 12:06:34 +00001169 }
1170
1171 // Add subranges to array type.
1172 DINodeArray Elements = Ty->getElements();
1173 for (int i = Elements.size() - 1; i >= 0; --i) {
1174 const DINode *Element = Elements[i];
1175 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1176
1177 const DISubrange *Subrange = cast<DISubrange>(Element);
1178 assert(Subrange->getLowerBound() == 0 &&
1179 "codeview doesn't support subranges with lower bounds");
1180 int64_t Count = Subrange->getCount();
1181
1182 // Variable Length Array (VLA) has Count equal to '-1'.
1183 // Replace with Count '1', assume it is the minimum VLA length.
1184 // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
1185 if (Count == -1) {
1186 Count = 1;
Reid Kleckner10762882016-09-09 17:29:36 +00001187 PartiallyIncomplete = true;
Amjad Aboudacee5682016-07-12 12:06:34 +00001188 }
1189
Amjad Aboudacee5682016-07-12 12:06:34 +00001190 // Update the element size and element type index for subsequent subranges.
1191 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001192
1193 // If this is the outermost array, use the size from the array. It will be
1194 // more accurate if PartiallyIncomplete is true.
1195 uint64_t ArraySize =
1196 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1197
1198 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner4efa0a42016-11-08 22:24:53 +00001199 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1200 ElementTypeIndex = TypeTable.writeKnownType(AR);
Amjad Aboudacee5682016-07-12 12:06:34 +00001201 }
1202
Reid Kleckner10762882016-09-09 17:29:36 +00001203 (void)PartiallyIncomplete;
1204 assert(PartiallyIncomplete || ElementSize == (Ty->getSizeInBits() / 8));
Amjad Aboudacee5682016-07-12 12:06:34 +00001205
1206 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001207}
1208
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001209TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1210 TypeIndex Index;
1211 dwarf::TypeKind Kind;
1212 uint32_t ByteSize;
1213
1214 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001215 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001216
1217 SimpleTypeKind STK = SimpleTypeKind::None;
1218 switch (Kind) {
1219 case dwarf::DW_ATE_address:
1220 // FIXME: Translate
1221 break;
1222 case dwarf::DW_ATE_boolean:
1223 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001224 case 1: STK = SimpleTypeKind::Boolean8; break;
1225 case 2: STK = SimpleTypeKind::Boolean16; break;
1226 case 4: STK = SimpleTypeKind::Boolean32; break;
1227 case 8: STK = SimpleTypeKind::Boolean64; break;
1228 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001229 }
1230 break;
1231 case dwarf::DW_ATE_complex_float:
1232 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001233 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001234 case 4: STK = SimpleTypeKind::Complex32; break;
1235 case 8: STK = SimpleTypeKind::Complex64; break;
1236 case 10: STK = SimpleTypeKind::Complex80; break;
1237 case 16: STK = SimpleTypeKind::Complex128; break;
1238 }
1239 break;
1240 case dwarf::DW_ATE_float:
1241 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001242 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001243 case 4: STK = SimpleTypeKind::Float32; break;
1244 case 6: STK = SimpleTypeKind::Float48; break;
1245 case 8: STK = SimpleTypeKind::Float64; break;
1246 case 10: STK = SimpleTypeKind::Float80; break;
1247 case 16: STK = SimpleTypeKind::Float128; break;
1248 }
1249 break;
1250 case dwarf::DW_ATE_signed:
1251 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001252 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1253 case 2: STK = SimpleTypeKind::Int16Short; break;
1254 case 4: STK = SimpleTypeKind::Int32; break;
1255 case 8: STK = SimpleTypeKind::Int64Quad; break;
1256 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001257 }
1258 break;
1259 case dwarf::DW_ATE_unsigned:
1260 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001261 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1262 case 2: STK = SimpleTypeKind::UInt16Short; break;
1263 case 4: STK = SimpleTypeKind::UInt32; break;
1264 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1265 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001266 }
1267 break;
1268 case dwarf::DW_ATE_UTF:
1269 switch (ByteSize) {
1270 case 2: STK = SimpleTypeKind::Character16; break;
1271 case 4: STK = SimpleTypeKind::Character32; break;
1272 }
1273 break;
1274 case dwarf::DW_ATE_signed_char:
1275 if (ByteSize == 1)
1276 STK = SimpleTypeKind::SignedCharacter;
1277 break;
1278 case dwarf::DW_ATE_unsigned_char:
1279 if (ByteSize == 1)
1280 STK = SimpleTypeKind::UnsignedCharacter;
1281 break;
1282 default:
1283 break;
1284 }
1285
1286 // Apply some fixups based on the source-level type name.
1287 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1288 STK = SimpleTypeKind::Int32Long;
1289 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1290 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001291 if (STK == SimpleTypeKind::UInt16Short &&
1292 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001293 STK = SimpleTypeKind::WideCharacter;
1294 if ((STK == SimpleTypeKind::SignedCharacter ||
1295 STK == SimpleTypeKind::UnsignedCharacter) &&
1296 Ty->getName() == "char")
1297 STK = SimpleTypeKind::NarrowCharacter;
1298
1299 return TypeIndex(STK);
1300}
1301
1302TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1303 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1304
1305 // Pointers to simple types can use SimpleTypeMode, rather than having a
1306 // dedicated pointer type record.
1307 if (PointeeTI.isSimple() &&
1308 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1309 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1310 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1311 ? SimpleTypeMode::NearPointer64
1312 : SimpleTypeMode::NearPointer32;
1313 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1314 }
1315
1316 PointerKind PK =
1317 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1318 PointerMode PM = PointerMode::Pointer;
1319 switch (Ty->getTag()) {
1320 default: llvm_unreachable("not a pointer tag type");
1321 case dwarf::DW_TAG_pointer_type:
1322 PM = PointerMode::Pointer;
1323 break;
1324 case dwarf::DW_TAG_reference_type:
1325 PM = PointerMode::LValueReference;
1326 break;
1327 case dwarf::DW_TAG_rvalue_reference_type:
1328 PM = PointerMode::RValueReference;
1329 break;
1330 }
1331 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1332 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1333 // do.
1334 PointerOptions PO = PointerOptions::None;
1335 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001336 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001337}
1338
Reid Kleckner6fa15462016-06-17 22:14:39 +00001339static PointerToMemberRepresentation
1340translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1341 // SizeInBytes being zero generally implies that the member pointer type was
1342 // incomplete, which can happen if it is part of a function prototype. In this
1343 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001344 if (IsPMF) {
1345 switch (Flags & DINode::FlagPtrToMemberRep) {
1346 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001347 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1348 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001349 case DINode::FlagSingleInheritance:
1350 return PointerToMemberRepresentation::SingleInheritanceFunction;
1351 case DINode::FlagMultipleInheritance:
1352 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1353 case DINode::FlagVirtualInheritance:
1354 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1355 }
1356 } else {
1357 switch (Flags & DINode::FlagPtrToMemberRep) {
1358 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001359 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1360 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001361 case DINode::FlagSingleInheritance:
1362 return PointerToMemberRepresentation::SingleInheritanceData;
1363 case DINode::FlagMultipleInheritance:
1364 return PointerToMemberRepresentation::MultipleInheritanceData;
1365 case DINode::FlagVirtualInheritance:
1366 return PointerToMemberRepresentation::VirtualInheritanceData;
1367 }
1368 }
1369 llvm_unreachable("invalid ptr to member representation");
1370}
1371
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001372TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1373 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1374 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001375 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001376 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
1377 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001378 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1379 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1380 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001381 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner6fa15462016-06-17 22:14:39 +00001382 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1383 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1384 MemberPointerInfo MPI(
1385 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001386 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001387 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001388}
1389
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001390/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1391/// have a translation, use the NearC convention.
1392static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1393 switch (DwarfCC) {
1394 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1395 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1396 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1397 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1398 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1399 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1400 }
1401 return CallingConvention::NearC;
1402}
1403
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001404TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1405 ModifierOptions Mods = ModifierOptions::None;
1406 bool IsModifier = true;
1407 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001408 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001409 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001410 switch (BaseTy->getTag()) {
1411 case dwarf::DW_TAG_const_type:
1412 Mods |= ModifierOptions::Const;
1413 break;
1414 case dwarf::DW_TAG_volatile_type:
1415 Mods |= ModifierOptions::Volatile;
1416 break;
1417 default:
1418 IsModifier = false;
1419 break;
1420 }
1421 if (IsModifier)
1422 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1423 }
1424 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001425 ModifierRecord MR(ModifiedTI, Mods);
1426 return TypeTable.writeKnownType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001427}
1428
David Majnemer75c3ebf2016-06-02 17:13:53 +00001429TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1430 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1431 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1432 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1433
1434 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1435 ArrayRef<TypeIndex> ArgTypeIndices = None;
1436 if (!ReturnAndArgTypeIndices.empty()) {
1437 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1438 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1439 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1440 }
1441
1442 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001443 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001444
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001445 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1446
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001447 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1448 ArgTypeIndices.size(), ArgListIndex);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001449 return TypeTable.writeKnownType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001450}
1451
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001452TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001453 const DIType *ClassTy,
1454 int ThisAdjustment) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001455 // Lower the containing class type.
1456 TypeIndex ClassType = getTypeIndex(ClassTy);
1457
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001458 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1459 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1460 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1461
1462 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1463 ArrayRef<TypeIndex> ArgTypeIndices = None;
1464 if (!ReturnAndArgTypeIndices.empty()) {
1465 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1466 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1467 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1468 }
1469 TypeIndex ThisTypeIndex = TypeIndex::Void();
1470 if (!ArgTypeIndices.empty()) {
1471 ThisTypeIndex = ArgTypeIndices.front();
1472 ArgTypeIndices = ArgTypeIndices.drop_front();
1473 }
1474
1475 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001476 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001477
1478 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1479
1480 // TODO: Need to use the correct values for:
1481 // FunctionOptions
1482 // ThisPointerAdjustment.
Zachary Turner4efa0a42016-11-08 22:24:53 +00001483 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
1484 FunctionOptions::None, ArgTypeIndices.size(),
1485 ArgListIndex, ThisAdjustment);
1486 TypeIndex TI = TypeTable.writeKnownType(MFR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001487
1488 return TI;
1489}
1490
Reid Kleckner9dac4732016-08-31 15:59:30 +00001491TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
1492 unsigned VSlotCount = Ty->getSizeInBits() / (8 * Asm->MAI->getPointerSize());
1493 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001494
1495 VFTableShapeRecord VFTSR(Slots);
1496 return TypeTable.writeKnownType(VFTSR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001497}
1498
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001499static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1500 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001501 case DINode::FlagPrivate: return MemberAccess::Private;
1502 case DINode::FlagPublic: return MemberAccess::Public;
1503 case DINode::FlagProtected: return MemberAccess::Protected;
1504 case 0:
1505 // If there was no explicit access control, provide the default for the tag.
1506 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1507 : MemberAccess::Public;
1508 }
1509 llvm_unreachable("access flags are exclusive");
1510}
1511
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001512static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1513 if (SP->isArtificial())
1514 return MethodOptions::CompilerGenerated;
1515
1516 // FIXME: Handle other MethodOptions.
1517
1518 return MethodOptions::None;
1519}
1520
1521static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1522 bool Introduced) {
1523 switch (SP->getVirtuality()) {
1524 case dwarf::DW_VIRTUALITY_none:
1525 break;
1526 case dwarf::DW_VIRTUALITY_virtual:
1527 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1528 case dwarf::DW_VIRTUALITY_pure_virtual:
1529 return Introduced ? MethodKind::PureIntroducingVirtual
1530 : MethodKind::PureVirtual;
1531 default:
1532 llvm_unreachable("unhandled virtuality case");
1533 }
1534
1535 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1536
1537 return MethodKind::Vanilla;
1538}
1539
Reid Klecknera8d57402016-06-03 15:58:20 +00001540static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1541 switch (Ty->getTag()) {
1542 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1543 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1544 }
1545 llvm_unreachable("unexpected tag");
1546}
1547
Reid Klecknere092dad2016-07-02 00:11:07 +00001548/// Return ClassOptions that should be present on both the forward declaration
1549/// and the defintion of a tag type.
1550static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1551 ClassOptions CO = ClassOptions::None;
1552
1553 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001554 // appear to give every type a linkage name, which may be problematic for us.
1555 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001556 if (!Ty->getIdentifier().empty())
1557 CO |= ClassOptions::HasUniqueName;
1558
1559 // Put the Nested flag on a type if it appears immediately inside a tag type.
1560 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1561 // here. That flag is only set on definitions, and not forward declarations.
1562 const DIScope *ImmediateScope = Ty->getScope().resolve();
1563 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1564 CO |= ClassOptions::Nested;
1565
1566 // Put the Scoped flag on function-local types.
1567 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1568 Scope = Scope->getScope().resolve()) {
1569 if (isa<DISubprogram>(Scope)) {
1570 CO |= ClassOptions::Scoped;
1571 break;
1572 }
1573 }
1574
1575 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001576}
1577
David Majnemer979cb882016-06-16 21:32:16 +00001578TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001579 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001580 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001581 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001582
David Majnemerda9548f2016-06-17 16:13:21 +00001583 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001584 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001585 } else {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001586 FieldListRecordBuilder FLRB(TypeTable);
1587
1588 FLRB.begin();
David Majnemerda9548f2016-06-17 16:13:21 +00001589 for (const DINode *Element : Ty->getElements()) {
1590 // We assume that the frontend provides all members in source declaration
1591 // order, which is what MSVC does.
1592 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001593 EnumeratorRecord ER(MemberAccess::Public,
1594 APSInt::getUnsigned(Enumerator->getValue()),
1595 Enumerator->getName());
1596 FLRB.writeMemberType(ER);
David Majnemerda9548f2016-06-17 16:13:21 +00001597 EnumeratorCount++;
1598 }
1599 }
Zachary Turner4efa0a42016-11-08 22:24:53 +00001600 FTI = FLRB.end();
David Majnemerda9548f2016-06-17 16:13:21 +00001601 }
David Majnemer979cb882016-06-16 21:32:16 +00001602
David Majnemer6bdc24e2016-07-01 23:12:45 +00001603 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001604
Zachary Turner4efa0a42016-11-08 22:24:53 +00001605 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
1606 getTypeIndex(Ty->getBaseType()));
1607 return TypeTable.writeKnownType(ER);
David Majnemer979cb882016-06-16 21:32:16 +00001608}
1609
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001610//===----------------------------------------------------------------------===//
1611// ClassInfo
1612//===----------------------------------------------------------------------===//
1613
1614struct llvm::ClassInfo {
1615 struct MemberInfo {
1616 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00001617 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001618 };
1619 // [MemberInfo]
1620 typedef std::vector<MemberInfo> MemberList;
1621
Reid Kleckner156a7232016-06-22 18:31:14 +00001622 typedef TinyPtrVector<const DISubprogram *> MethodsList;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001623 // MethodName -> MethodsList
1624 typedef MapVector<MDString *, MethodsList> MethodsMap;
1625
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001626 /// Base classes.
1627 std::vector<const DIDerivedType *> Inheritance;
1628
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001629 /// Direct members.
1630 MemberList Members;
1631 // Direct overloaded methods gathered by name.
1632 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001633
Reid Kleckner9dac4732016-08-31 15:59:30 +00001634 TypeIndex VShapeTI;
1635
Adrian McCarthy820ca542016-07-06 19:49:51 +00001636 std::vector<const DICompositeType *> NestedClasses;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001637};
1638
1639void CodeViewDebug::clear() {
1640 assert(CurFn == nullptr);
1641 FileIdMap.clear();
1642 FnDebugInfo.clear();
1643 FileToFilepathMap.clear();
1644 LocalUDTs.clear();
1645 GlobalUDTs.clear();
1646 TypeIndices.clear();
1647 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001648}
1649
1650void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1651 const DIDerivedType *DDTy) {
1652 if (!DDTy->getName().empty()) {
1653 Info.Members.push_back({DDTy, 0});
1654 return;
1655 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001656 // An unnamed member must represent a nested struct or union. Add all the
1657 // indirect fields to the current record.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001658 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00001659 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001660 const DIType *Ty = DDTy->getBaseType().resolve();
Reid Kleckner9ff936c2016-06-21 14:56:24 +00001661 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001662 ClassInfo NestedInfo = collectClassInfo(DCTy);
1663 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001664 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001665 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001666}
1667
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001668ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1669 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001670 // Add elements to structure type.
1671 DINodeArray Elements = Ty->getElements();
1672 for (auto *Element : Elements) {
1673 // We assume that the frontend provides all members in source declaration
1674 // order, which is what MSVC does.
1675 if (!Element)
1676 continue;
1677 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001678 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001679 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001680 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001681 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001682 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1683 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001684 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1685 DDTy->getName() == "__vtbl_ptr_type") {
1686 Info.VShapeTI = getTypeIndex(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001687 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1688 // Ignore friend members. It appears that MSVC emitted info about
1689 // friends in the past, but modern versions do not.
1690 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001691 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1692 Info.NestedClasses.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001693 }
1694 // Skip other unrecognized kinds of elements.
1695 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001696 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001697}
1698
Reid Klecknera8d57402016-06-03 15:58:20 +00001699TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1700 // First, construct the forward decl. Don't look into Ty to compute the
1701 // forward decl options, since it might not be available in all TUs.
1702 TypeRecordKind Kind = getRecordKind(Ty);
1703 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001704 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001705 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001706 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
1707 FullName, Ty->getIdentifier());
1708 TypeIndex FwdDeclTI = TypeTable.writeKnownType(CR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001709 if (!Ty->isForwardDecl())
1710 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001711 return FwdDeclTI;
1712}
1713
1714TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1715 // Construct the field list and complete type record.
1716 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00001717 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001718 TypeIndex FieldTI;
1719 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001720 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001721 bool ContainsNestedClass;
1722 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1723 lowerRecordFieldList(Ty);
1724
1725 if (ContainsNestedClass)
1726 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00001727
David Majnemer6bdc24e2016-07-01 23:12:45 +00001728 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001729
Reid Klecknera8d57402016-06-03 15:58:20 +00001730 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00001731
Zachary Turner4efa0a42016-11-08 22:24:53 +00001732 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
1733 SizeInBytes, FullName, Ty->getIdentifier());
1734 TypeIndex ClassTI = TypeTable.writeKnownType(CR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001735
Zachary Turner4efa0a42016-11-08 22:24:53 +00001736 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
1737 TypeIndex SIDI = TypeTable.writeKnownType(SIDR);
1738 UdtSourceLineRecord USLR(ClassTI, SIDI, Ty->getLine());
1739 TypeTable.writeKnownType(USLR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001740
Hans Wennborg4b63a982016-06-23 22:57:25 +00001741 addToUDTs(Ty, ClassTI);
1742
Hans Wennborg9a519a02016-06-22 21:22:13 +00001743 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001744}
1745
1746TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1747 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001748 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001749 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001750 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
1751 TypeIndex FwdDeclTI = TypeTable.writeKnownType(UR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001752 if (!Ty->isForwardDecl())
1753 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001754 return FwdDeclTI;
1755}
1756
1757TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00001758 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001759 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001760 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001761 bool ContainsNestedClass;
1762 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1763 lowerRecordFieldList(Ty);
1764
1765 if (ContainsNestedClass)
1766 CO |= ClassOptions::ContainsNestedClass;
1767
Reid Klecknera8d57402016-06-03 15:58:20 +00001768 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00001769 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001770
Zachary Turner4efa0a42016-11-08 22:24:53 +00001771 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
1772 Ty->getIdentifier());
1773 TypeIndex UnionTI = TypeTable.writeKnownType(UR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001774
Zachary Turner4efa0a42016-11-08 22:24:53 +00001775 StringIdRecord SIR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
1776 TypeIndex SIRI = TypeTable.writeKnownType(SIR);
1777 UdtSourceLineRecord USLR(UnionTI, SIRI, Ty->getLine());
1778 TypeTable.writeKnownType(USLR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001779
Hans Wennborg4b63a982016-06-23 22:57:25 +00001780 addToUDTs(Ty, UnionTI);
1781
Hans Wennborg9a519a02016-06-22 21:22:13 +00001782 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001783}
1784
Adrian McCarthy820ca542016-07-06 19:49:51 +00001785std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00001786CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1787 // Manually count members. MSVC appears to count everything that generates a
1788 // field list record. Each individual overload in a method overload group
1789 // contributes to this count, even though the overload group is a single field
1790 // list record.
1791 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001792 ClassInfo Info = collectClassInfo(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001793 FieldListRecordBuilder FLBR(TypeTable);
1794 FLBR.begin();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001795
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001796 // Create base classes.
1797 for (const DIDerivedType *I : Info.Inheritance) {
1798 if (I->getFlags() & DINode::FlagVirtual) {
1799 // Virtual base.
1800 // FIXME: Emit VBPtrOffset when the frontend provides it.
1801 unsigned VBPtrOffset = 0;
1802 // FIXME: Despite the accessor name, the offset is really in bytes.
1803 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00001804 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
1805 ? TypeRecordKind::IndirectVirtualBaseClass
1806 : TypeRecordKind::VirtualBaseClass;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001807 VirtualBaseClassRecord VBCR(
Bob Haarman26a87bd2016-10-25 22:11:52 +00001808 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001809 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
Zachary Turner4efa0a42016-11-08 22:24:53 +00001810 VBTableIndex);
1811
1812 FLBR.writeMemberType(VBCR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001813 } else {
1814 assert(I->getOffsetInBits() % 8 == 0 &&
1815 "bases must be on byte boundaries");
Zachary Turner4efa0a42016-11-08 22:24:53 +00001816 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
1817 getTypeIndex(I->getBaseType()),
1818 I->getOffsetInBits() / 8);
1819 FLBR.writeMemberType(BCR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001820 }
1821 }
1822
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001823 // Create members.
1824 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1825 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1826 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00001827 StringRef MemberName = Member->getName();
1828 MemberAccess Access =
1829 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001830
1831 if (Member->isStaticMember()) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001832 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
1833 FLBR.writeMemberType(SDMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001834 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001835 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00001836 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001837
Reid Kleckner9dac4732016-08-31 15:59:30 +00001838 // Virtual function pointer member.
1839 if ((Member->getFlags() & DINode::FlagArtificial) &&
1840 Member->getName().startswith("_vptr$")) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001841 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
1842 FLBR.writeMemberType(VFPR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001843 MemberCount++;
1844 continue;
1845 }
1846
David Majnemer9319cbc2016-06-30 03:00:20 +00001847 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00001848 uint64_t MemberOffsetInBits =
1849 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001850 if (Member->isBitField()) {
1851 uint64_t StartBitOffset = MemberOffsetInBits;
1852 if (const auto *CI =
1853 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00001854 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001855 }
1856 StartBitOffset -= MemberOffsetInBits;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001857 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
1858 StartBitOffset);
1859 MemberBaseType = TypeTable.writeKnownType(BFR);
David Majnemer9319cbc2016-06-30 03:00:20 +00001860 }
1861 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001862 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
1863 MemberName);
1864 FLBR.writeMemberType(DMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001865 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001866 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001867
1868 // Create methods
1869 for (auto &MethodItr : Info.Methods) {
1870 StringRef Name = MethodItr.first->getString();
1871
1872 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00001873 for (const DISubprogram *SP : MethodItr.second) {
1874 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1875 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001876
1877 unsigned VFTableOffset = -1;
1878 if (Introduced)
1879 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1880
Zachary Turner7251ede2016-11-02 17:05:19 +00001881 Methods.push_back(OneMethodRecord(
1882 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
1883 translateMethodKindFlags(SP, Introduced),
1884 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001885 MemberCount++;
1886 }
1887 assert(Methods.size() > 0 && "Empty methods map entry");
1888 if (Methods.size() == 1)
Zachary Turner4efa0a42016-11-08 22:24:53 +00001889 FLBR.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001890 else {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001891 MethodOverloadListRecord MOLR(Methods);
1892 TypeIndex MethodList = TypeTable.writeKnownType(MOLR);
1893 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
1894 FLBR.writeMemberType(OMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001895 }
1896 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001897
1898 // Create nested classes.
1899 for (const DICompositeType *Nested : Info.NestedClasses) {
1900 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner4efa0a42016-11-08 22:24:53 +00001901 FLBR.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00001902 MemberCount++;
1903 }
1904
Zachary Turner4efa0a42016-11-08 22:24:53 +00001905 TypeIndex FieldTI = FLBR.end();
Reid Kleckner9dac4732016-08-31 15:59:30 +00001906 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Adrian McCarthy820ca542016-07-06 19:49:51 +00001907 !Info.NestedClasses.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00001908}
1909
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001910TypeIndex CodeViewDebug::getVBPTypeIndex() {
1911 if (!VBPType.getIndex()) {
1912 // Make a 'const int *' type.
1913 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001914 TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001915
1916 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1917 : PointerKind::Near32;
1918 PointerMode PM = PointerMode::Pointer;
1919 PointerOptions PO = PointerOptions::None;
1920 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1921
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001922 VBPType = TypeTable.writeKnownType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001923 }
1924
1925 return VBPType;
1926}
1927
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001928TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001929 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001930 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001931
1932 // The null DIType is the void type. Don't try to hash it.
1933 if (!Ty)
1934 return TypeIndex::Void();
1935
Reid Klecknera8d57402016-06-03 15:58:20 +00001936 // Check if we've already translated this type. Don't try to do a
1937 // get-or-create style insertion that caches the hash lookup across the
1938 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001939 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001940 if (I != TypeIndices.end())
1941 return I->second;
1942
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001943 TypeLoweringScope S(*this);
1944 TypeIndex TI = lowerType(Ty, ClassTy);
1945 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00001946}
1947
1948TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1949 const DIType *Ty = TypeRef.resolve();
1950
1951 // The null DIType is the void type. Don't try to hash it.
1952 if (!Ty)
1953 return TypeIndex::Void();
1954
1955 // If this is a non-record type, the complete type index is the same as the
1956 // normal type index. Just call getTypeIndex.
1957 switch (Ty->getTag()) {
1958 case dwarf::DW_TAG_class_type:
1959 case dwarf::DW_TAG_structure_type:
1960 case dwarf::DW_TAG_union_type:
1961 break;
1962 default:
1963 return getTypeIndex(Ty);
1964 }
1965
1966 // Check if we've already translated the complete record type. Lowering a
1967 // complete type should never trigger lowering another complete type, so we
1968 // can reuse the hash table lookup result.
1969 const auto *CTy = cast<DICompositeType>(Ty);
1970 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1971 if (!InsertResult.second)
1972 return InsertResult.first->second;
1973
Reid Kleckner643dd832016-06-22 17:15:28 +00001974 TypeLoweringScope S(*this);
1975
Reid Klecknera8d57402016-06-03 15:58:20 +00001976 // Make sure the forward declaration is emitted first. It's unclear if this
1977 // is necessary, but MSVC does it, and we should follow suit until we can show
1978 // otherwise.
1979 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1980
1981 // Just use the forward decl if we don't have complete type info. This might
1982 // happen if the frontend is using modules and expects the complete definition
1983 // to be emitted elsewhere.
1984 if (CTy->isForwardDecl())
1985 return FwdDeclTI;
1986
1987 TypeIndex TI;
1988 switch (CTy->getTag()) {
1989 case dwarf::DW_TAG_class_type:
1990 case dwarf::DW_TAG_structure_type:
1991 TI = lowerCompleteTypeClass(CTy);
1992 break;
1993 case dwarf::DW_TAG_union_type:
1994 TI = lowerCompleteTypeUnion(CTy);
1995 break;
1996 default:
1997 llvm_unreachable("not a record");
1998 }
1999
2000 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002001 return TI;
2002}
2003
Reid Kleckner643dd832016-06-22 17:15:28 +00002004/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00002005/// and do this until fixpoint, as each complete record type typically
2006/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00002007/// many other record types.
2008void CodeViewDebug::emitDeferredCompleteTypes() {
2009 SmallVector<const DICompositeType *, 4> TypesToEmit;
2010 while (!DeferredCompleteTypes.empty()) {
2011 std::swap(DeferredCompleteTypes, TypesToEmit);
2012 for (const DICompositeType *RecordTy : TypesToEmit)
2013 getCompleteTypeIndex(RecordTy);
2014 TypesToEmit.clear();
2015 }
2016}
2017
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002018void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
2019 // Get the sorted list of parameters and emit them first.
2020 SmallVector<const LocalVariable *, 6> Params;
2021 for (const LocalVariable &L : Locals)
2022 if (L.DIVar->isParameter())
2023 Params.push_back(&L);
2024 std::sort(Params.begin(), Params.end(),
2025 [](const LocalVariable *L, const LocalVariable *R) {
2026 return L->DIVar->getArg() < R->DIVar->getArg();
2027 });
2028 for (const LocalVariable *L : Params)
2029 emitLocalVariable(*L);
2030
2031 // Next emit all non-parameters in the order that we found them.
2032 for (const LocalVariable &L : Locals)
2033 if (!L.DIVar->isParameter())
2034 emitLocalVariable(L);
2035}
2036
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002037void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
2038 // LocalSym record, see SymbolRecord.h for more info.
2039 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2040 *LocalEnd = MMI->getContext().createTempSymbol();
2041 OS.AddComment("Record length");
2042 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2043 OS.EmitLabel(LocalBegin);
2044
2045 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00002046 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002047
Zachary Turner63a28462016-05-17 23:50:21 +00002048 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002049 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002050 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002051 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002052 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002053
2054 OS.AddComment("TypeIndex");
Reid Klecknera8d57402016-06-03 15:58:20 +00002055 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002056 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002057 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002058 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002059 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002060 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002061 OS.EmitLabel(LocalEnd);
2062
Reid Kleckner876330d2016-02-12 21:48:30 +00002063 // Calculate the on disk prefix of the appropriate def range record. The
2064 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2065 // should be big enough to hold all forms without memory allocation.
2066 SmallString<20> BytePrefix;
2067 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2068 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002069 if (DefRange.InMemory) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002070 uint16_t RegRelFlags = 0;
2071 if (DefRange.IsSubfield) {
2072 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2073 (DefRange.StructOffset
2074 << DefRangeRegisterRelSym::OffsetInParentShift);
2075 }
Zachary Turner46225b12016-12-16 22:48:14 +00002076 DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
2077 Sym.Hdr.Register = DefRange.CVRegister;
2078 Sym.Hdr.Flags = RegRelFlags;
2079 Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +00002080 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00002081 BytePrefix +=
2082 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00002083 BytePrefix +=
Zachary Turner46225b12016-12-16 22:48:14 +00002084 StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
Reid Kleckner876330d2016-02-12 21:48:30 +00002085 } else {
2086 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002087 if (DefRange.IsSubfield) {
2088 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002089 DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
2090 Sym.Hdr.Register = DefRange.CVRegister;
2091 Sym.Hdr.MayHaveNoName = 0;
2092 Sym.Hdr.OffsetInParent = DefRange.StructOffset;
2093
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002094 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2095 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2096 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002097 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2098 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002099 } else {
2100 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002101 DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
2102 Sym.Hdr.Register = DefRange.CVRegister;
2103 Sym.Hdr.MayHaveNoName = 0;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002104 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2105 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2106 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002107 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2108 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002109 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002110 }
2111 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2112 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002113}
2114
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002115void CodeViewDebug::endFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002116 if (!Asm || !CurFn) // We haven't created any debug info for this function.
2117 return;
2118
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002119 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00002120 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002121 assert(CurFn == &FnDebugInfo[GV]);
2122
Pete Cooperadebb932016-03-11 02:14:16 +00002123 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002124
2125 DebugHandlerBase::endFunction(MF);
2126
Reid Kleckner2214ed82016-01-29 00:49:42 +00002127 // Don't emit anything if we don't have any line tables.
2128 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002129 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002130 CurFn = nullptr;
2131 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002132 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002133
2134 CurFn->End = Asm->getFunctionEnd();
2135
Craig Topper353eda42014-04-24 06:44:33 +00002136 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002137}
2138
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002139void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002140 DebugHandlerBase::beginInstruction(MI);
2141
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002142 // Ignore DBG_VALUE locations and function prologue.
David Majnemer67f684e2016-07-28 05:03:22 +00002143 if (!Asm || !CurFn || MI->isDebugValue() ||
2144 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002145 return;
2146 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00002147 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002148 return;
2149 maybeRecordLocation(DL, Asm->MF);
2150}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002151
2152MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
2153 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2154 *EndLabel = MMI->getContext().createTempSymbol();
2155 OS.EmitIntValue(unsigned(Kind), 4);
2156 OS.AddComment("Subsection size");
2157 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2158 OS.EmitLabel(BeginLabel);
2159 return EndLabel;
2160}
2161
2162void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2163 OS.EmitLabel(EndLabel);
2164 // Every subsection must be aligned to a 4-byte boundary.
2165 OS.EmitValueToAlignment(4);
2166}
2167
David Majnemer3128b102016-06-15 18:00:01 +00002168void CodeViewDebug::emitDebugInfoForUDTs(
2169 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
2170 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
2171 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2172 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2173 OS.AddComment("Record length");
2174 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2175 OS.EmitLabel(UDTRecordBegin);
2176
2177 OS.AddComment("Record kind: S_UDT");
2178 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2179
2180 OS.AddComment("Type");
2181 OS.EmitIntValue(UDT.second.getIndex(), 4);
2182
2183 emitNullTerminatedSymbolName(OS, UDT.first);
2184 OS.EmitLabel(UDTRecordEnd);
2185 }
2186}
2187
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002188void CodeViewDebug::emitDebugInfoForGlobals() {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002189 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2190 GlobalMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002191 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002192 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2193 GV.getDebugInfo(GVEs);
2194 for (const auto *GVE : GVEs)
2195 GlobalMap[GVE] = &GV;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002196 }
2197
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002198 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2199 for (const MDNode *Node : CUs->operands()) {
2200 const auto *CU = cast<DICompileUnit>(Node);
2201
2202 // First, emit all globals that are not in a comdat in a single symbol
2203 // substream. MSVC doesn't like it if the substream is empty, so only open
2204 // it if we have at least one global to emit.
2205 switchToDebugSectionForSymbol(nullptr);
2206 MCSymbol *EndLabel = nullptr;
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002207 for (const auto *GVE : CU->getGlobalVariables()) {
2208 if (const auto *GV = GlobalMap.lookup(GVE))
David Majnemer577be0f2016-06-15 00:19:52 +00002209 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002210 if (!EndLabel) {
2211 OS.AddComment("Symbol subsection for globals");
2212 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
2213 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002214 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2215 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002216 }
2217 }
2218 if (EndLabel)
2219 endCVSubsection(EndLabel);
2220
2221 // Second, emit each global that is in a comdat into its own .debug$S
2222 // section along with its own symbol substream.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002223 for (const auto *GVE : CU->getGlobalVariables()) {
2224 if (const auto *GV = GlobalMap.lookup(GVE)) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002225 if (GV->hasComdat()) {
2226 MCSymbol *GVSym = Asm->getSymbol(GV);
2227 OS.AddComment("Symbol subsection for " +
2228 Twine(GlobalValue::getRealLinkageName(GV->getName())));
2229 switchToDebugSectionForSymbol(GVSym);
2230 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002231 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2232 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002233 endCVSubsection(EndLabel);
2234 }
2235 }
2236 }
2237 }
2238}
2239
Hans Wennborgb510b452016-06-23 16:33:53 +00002240void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2241 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2242 for (const MDNode *Node : CUs->operands()) {
2243 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2244 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2245 getTypeIndex(RT);
2246 // FIXME: Add to global/local DTU list.
2247 }
2248 }
2249 }
2250}
2251
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002252void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002253 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002254 MCSymbol *GVSym) {
2255 // DataSym record, see SymbolRecord.h for more info.
2256 // FIXME: Thread local data, etc
2257 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2258 *DataEnd = MMI->getContext().createTempSymbol();
2259 OS.AddComment("Record length");
2260 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2261 OS.EmitLabel(DataBegin);
David Majnemer7abd2692016-07-06 21:07:47 +00002262 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002263 if (GV->isThreadLocal()) {
2264 OS.AddComment("Record kind: S_LTHREAD32");
2265 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2266 } else {
2267 OS.AddComment("Record kind: S_LDATA32");
2268 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2269 }
David Majnemer7abd2692016-07-06 21:07:47 +00002270 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002271 if (GV->isThreadLocal()) {
2272 OS.AddComment("Record kind: S_GTHREAD32");
2273 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2274 } else {
2275 OS.AddComment("Record kind: S_GDATA32");
2276 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2277 }
David Majnemer7abd2692016-07-06 21:07:47 +00002278 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002279 OS.AddComment("Type");
2280 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2281 OS.AddComment("DataOffset");
Keno Fischerd4ea4c12016-12-08 01:56:23 +00002282 OS.EmitCOFFSecRel32(GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002283 OS.AddComment("Segment");
2284 OS.EmitCOFFSectionIndex(GVSym);
2285 OS.AddComment("Name");
2286 emitNullTerminatedSymbolName(OS, DIGV->getName());
2287 OS.EmitLabel(DataEnd);
2288}