blob: 4c46e5177fa5ad2efffe19e0b7a2df28691de84a [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 Kleckner6b3faef2016-01-13 23:44:57 +000016#include "llvm/DebugInfo/CodeView/CodeView.h"
Reid Klecknera8d57402016-06-03 15:58:20 +000017#include "llvm/DebugInfo/CodeView/FieldListRecordBuilder.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"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000023#include "llvm/MC/MCExpr.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000024#include "llvm/MC/MCSectionCOFF.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000025#include "llvm/MC/MCSymbol.h"
26#include "llvm/Support/COFF.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000027#include "llvm/Support/ScopedPrinter.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000028#include "llvm/Target/TargetFrameLowering.h"
Amjad Aboud76c9eb92016-06-18 10:25:07 +000029#include "llvm/Target/TargetRegisterInfo.h"
30#include "llvm/Target/TargetSubtargetInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000031
Reid Klecknerf9c275f2016-02-10 20:55:49 +000032using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000033using namespace llvm::codeview;
34
Reid Klecknerf9c275f2016-02-10 20:55:49 +000035CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
36 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
37 // If module doesn't have named metadata anchors or COFF debug section
38 // is not available, skip any debug info related stuff.
39 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
40 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
41 Asm = nullptr;
42 return;
43 }
44
45 // Tell MMI that we have debug info.
46 MMI->setDebugInfoAvailability(true);
47}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000048
Reid Kleckner9533af42016-01-16 00:09:09 +000049StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
50 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000051 if (!Filepath.empty())
52 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000053
Reid Kleckner9533af42016-01-16 00:09:09 +000054 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
55
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000056 // Clang emits directory and relative filename info into the IR, but CodeView
57 // operates on full paths. We could change Clang to emit full paths too, but
58 // that would increase the IR size and probably not needed for other users.
59 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000060 if (Filename.find(':') == 1)
61 Filepath = Filename;
62 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +000063 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000064
65 // Canonicalize the path. We have to do it textually because we may no longer
66 // have access the file in the filesystem.
67 // First, replace all slashes with backslashes.
68 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
69
70 // Remove all "\.\" with "\".
71 size_t Cursor = 0;
72 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
73 Filepath.erase(Cursor, 2);
74
75 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
76 // path should be well-formatted, e.g. start with a drive letter, etc.
77 Cursor = 0;
78 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
79 // Something's wrong if the path starts with "\..\", abort.
80 if (Cursor == 0)
81 break;
82
83 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
84 if (PrevSlash == std::string::npos)
85 // Something's wrong, abort.
86 break;
87
88 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
89 // The next ".." might be following the one we've just erased.
90 Cursor = PrevSlash;
91 }
92
93 // Remove all duplicate backslashes.
94 Cursor = 0;
95 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
96 Filepath.erase(Cursor, 1);
97
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000098 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000099}
100
Reid Kleckner2214ed82016-01-29 00:49:42 +0000101unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
102 unsigned NextId = FileIdMap.size() + 1;
103 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
104 if (Insertion.second) {
105 // We have to compute the full filepath and emit a .cv_file directive.
106 StringRef FullPath = getFullFilepath(F);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000107 NextId = OS.EmitCVFileDirective(NextId, FullPath);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000108 assert(NextId == FileIdMap.size() && ".cv_file directive failed");
109 }
110 return Insertion.first->second;
111}
112
Reid Kleckner876330d2016-02-12 21:48:30 +0000113CodeViewDebug::InlineSite &
114CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
115 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000116 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
117 InlineSite *Site = &SiteInsertion.first->second;
118 if (SiteInsertion.second) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000119 Site->SiteFuncId = NextFuncId++;
Reid Kleckner876330d2016-02-12 21:48:30 +0000120 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000121 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000122 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000123 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000124 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000125}
126
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000127static const DISubprogram *getQualifiedNameComponents(
128 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
129 const DISubprogram *ClosestSubprogram = nullptr;
130 while (Scope != nullptr) {
131 if (ClosestSubprogram == nullptr)
132 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
133 StringRef ScopeName = Scope->getName();
134 if (!ScopeName.empty())
135 QualifiedNameComponents.push_back(ScopeName);
136 Scope = Scope->getScope().resolve();
137 }
138 return ClosestSubprogram;
139}
140
141static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
142 StringRef TypeName) {
143 std::string FullyQualifiedName;
144 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
145 FullyQualifiedName.append(QualifiedNameComponent);
146 FullyQualifiedName.append("::");
147 }
148 FullyQualifiedName.append(TypeName);
149 return FullyQualifiedName;
150}
151
152static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
153 SmallVector<StringRef, 5> QualifiedNameComponents;
154 getQualifiedNameComponents(Scope, QualifiedNameComponents);
155 return getQualifiedName(QualifiedNameComponents, Name);
156}
157
158TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
159 // No scope means global scope and that uses the zero index.
160 if (!Scope || isa<DIFile>(Scope))
161 return TypeIndex();
162
163 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
164
165 // Check if we've already translated this scope.
166 auto I = TypeIndices.find({Scope, nullptr});
167 if (I != TypeIndices.end())
168 return I->second;
169
170 // Build the fully qualified name of the scope.
171 std::string ScopeName =
172 getFullyQualifiedName(Scope->getScope().resolve(), Scope->getName());
173 TypeIndex TI =
174 TypeTable.writeStringId(StringIdRecord(TypeIndex(), ScopeName));
175 return recordTypeIndexForDINode(Scope, TI);
176}
177
David Majnemer75c3ebf2016-06-02 17:13:53 +0000178TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
179 // It's possible to ask for the FuncId of a function which doesn't have a
180 // subprogram: inlining a function with debug info into a function with none.
181 if (!SP)
David Majnemerb68f32f02016-06-02 18:51:24 +0000182 return TypeIndex::None();
Reid Kleckner2280f932016-05-23 20:23:46 +0000183
David Majnemer75c3ebf2016-06-02 17:13:53 +0000184 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000185 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000186 if (I != TypeIndices.end())
187 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000188
Reid Klecknerac945e22016-06-17 16:11:20 +0000189 // The display name includes function template arguments. Drop them to match
190 // MSVC.
191 StringRef DisplayName = SP->getDisplayName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000192
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000193 const DIScope *Scope = SP->getScope().resolve();
194 TypeIndex TI;
195 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
196 // If the scope is a DICompositeType, then this must be a method. Member
197 // function types take some special handling, and require access to the
198 // subprogram.
199 TypeIndex ClassType = getTypeIndex(Class);
200 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
201 DisplayName);
202 TI = TypeTable.writeMemberFuncId(MFuncId);
203 } else {
204 // Otherwise, this must be a free function.
205 TypeIndex ParentScope = getScopeIndex(Scope);
206 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
207 TI = TypeTable.writeFuncId(FuncId);
208 }
209
210 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000211}
212
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000213TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
214 const DICompositeType *Class) {
215 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
216 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
217 auto I = TypeIndices.find({SP, nullptr});
218 if (I != TypeIndices.end())
219 return I->second;
220
221 // FIXME: Get the ThisAdjustment off of SP when it is available.
222 TypeIndex TI =
223 lowerTypeMemberFunction(SP->getType(), Class, /*ThisAdjustment=*/0);
224
225 return recordTypeIndexForDINode(SP, TI, Class);
226}
227
228TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, TypeIndex TI,
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000229 const DIType *ClassTy) {
230 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000231 (void)InsertResult;
232 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000233 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000234}
235
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000236unsigned CodeViewDebug::getPointerSizeInBytes() {
237 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
238}
239
Reid Kleckner876330d2016-02-12 21:48:30 +0000240void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
241 const DILocation *InlinedAt) {
242 if (InlinedAt) {
243 // This variable was inlined. Associate it with the InlineSite.
244 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
245 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
246 Site.InlinedLocals.emplace_back(Var);
247 } else {
248 // This variable goes in the main ProcSym.
249 CurFn->Locals.emplace_back(Var);
250 }
251}
252
Reid Kleckner829365a2016-02-11 19:41:47 +0000253static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
254 const DILocation *Loc) {
255 auto B = Locs.begin(), E = Locs.end();
256 if (std::find(B, E, Loc) == E)
257 Locs.push_back(Loc);
258}
259
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000260void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000261 const MachineFunction *MF) {
262 // Skip this instruction if it has the same location as the previous one.
263 if (DL == CurFn->LastLoc)
264 return;
265
266 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000267 if (!Scope)
268 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000269
David Majnemerc3340db2016-01-13 01:05:23 +0000270 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000271 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
272 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
273 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000274 return;
275
Reid Kleckner2214ed82016-01-29 00:49:42 +0000276 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
277 if (CI.getStartColumn() != DL.getCol())
278 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000279
Reid Kleckner2214ed82016-01-29 00:49:42 +0000280 if (!CurFn->HaveLineInfo)
281 CurFn->HaveLineInfo = true;
282 unsigned FileId = 0;
283 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
284 FileId = CurFn->LastFileId;
285 else
286 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
287 CurFn->LastLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000288
289 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000290 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000291 const DILocation *Loc = DL.get();
292
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000293 // If this location was actually inlined from somewhere else, give it the ID
294 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000295 FuncId =
296 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000297
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000298 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000299 bool FirstLoc = true;
300 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000301 InlineSite &Site =
302 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000303 if (!FirstLoc)
304 addLocIfNotPresent(Site.ChildSites, Loc);
305 FirstLoc = false;
306 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000307 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000308 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000309 }
310
Reid Klecknerdac21b42016-02-03 21:15:48 +0000311 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
312 /*PrologueEnd=*/false,
313 /*IsStmt=*/false, DL->getFilename());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000314}
315
Reid Kleckner5d122f82016-05-25 23:16:12 +0000316void CodeViewDebug::emitCodeViewMagicVersion() {
317 OS.EmitValueToAlignment(4);
318 OS.AddComment("Debug section magic");
319 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
320}
321
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000322void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000323 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000324 return;
325
326 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000327
328 // The COFF .debug$S section consists of several subsections, each starting
329 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
330 // of the payload followed by the payload itself. The subsections are 4-byte
331 // aligned.
332
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000333 // Use the generic .debug$S section, and make a subsection for all the inlined
334 // subprograms.
335 switchToDebugSectionForSymbol(nullptr);
Reid Kleckner5d122f82016-05-25 23:16:12 +0000336 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000337
Reid Kleckner2214ed82016-01-29 00:49:42 +0000338 // Emit per-function debug information.
339 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000340 if (!P.first->isDeclarationForLinker())
341 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000342
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000343 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000344 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000345 emitDebugInfoForGlobals();
346
Hans Wennborgb510b452016-06-23 16:33:53 +0000347 // Emit retained types.
348 emitDebugInfoForRetainedTypes();
349
Reid Kleckner5d122f82016-05-25 23:16:12 +0000350 // Switch back to the generic .debug$S section after potentially processing
351 // comdat symbol sections.
352 switchToDebugSectionForSymbol(nullptr);
353
David Majnemer3128b102016-06-15 18:00:01 +0000354 // Emit UDT records for any types used by global variables.
355 if (!GlobalUDTs.empty()) {
356 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
357 emitDebugInfoForUDTs(GlobalUDTs);
358 endCVSubsection(SymbolsEnd);
359 }
360
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000361 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000362 OS.AddComment("File index to string table offset subsection");
363 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000364
365 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000366 OS.AddComment("String table");
367 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000368
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000369 // Emit type information last, so that any types we translate while emitting
370 // function info are included.
371 emitTypeInformation();
372
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000373 clear();
374}
375
David Majnemerb9456a52016-03-14 05:15:09 +0000376static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
377 // Microsoft's linker seems to have trouble with symbol names longer than
378 // 0xffd8 bytes.
379 S = S.substr(0, 0xffd8);
380 SmallString<32> NullTerminatedString(S);
381 NullTerminatedString.push_back('\0');
382 OS.EmitBytes(NullTerminatedString);
383}
384
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000385void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000386 // Do nothing if we have no debug info or if no non-trivial types were emitted
387 // to TypeTable during codegen.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000388 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
Reid Klecknerfbd77872016-03-18 18:54:32 +0000389 if (!CU_Nodes)
390 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000391 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000392 return;
393
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000394 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000395 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000396 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000397
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000398 SmallString<8> CommentPrefix;
399 if (OS.isVerboseAsm()) {
400 CommentPrefix += '\t';
401 CommentPrefix += Asm->MAI->getCommentString();
402 CommentPrefix += ' ';
403 }
404
405 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
Reid Kleckner2280f932016-05-23 20:23:46 +0000406 TypeTable.ForEachRecord(
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000407 [&](TypeIndex Index, StringRef Record) {
408 if (OS.isVerboseAsm()) {
409 // Emit a block comment describing the type record for readability.
410 SmallString<512> CommentBlock;
411 raw_svector_ostream CommentOS(CommentBlock);
412 ScopedPrinter SP(CommentOS);
413 SP.setPrefix(CommentPrefix);
414 CVTD.setPrinter(&SP);
Zachary Turner01ee3dae2016-06-16 18:22:27 +0000415 Error EC = CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
416 assert(!EC && "produced malformed type record");
417 consumeError(std::move(EC));
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000418 // emitRawComment will insert its own tab and comment string before
419 // the first line, so strip off our first one. It also prints its own
420 // newline.
421 OS.emitRawComment(
422 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
423 }
424 OS.EmitBinaryData(Record);
Reid Kleckner2280f932016-05-23 20:23:46 +0000425 });
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000426}
427
Reid Kleckner5d122f82016-05-25 23:16:12 +0000428void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000429 if (InlinedSubprograms.empty())
430 return;
431
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000432 OS.AddComment("Inlinee lines subsection");
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000433 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000434
435 // We don't provide any extra file info.
436 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000437 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000438 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
439
440 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000441 assert(TypeIndices.count({SP, nullptr}));
442 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000443
David Majnemer30579ec2016-02-02 23:18:23 +0000444 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000445 unsigned FileId = maybeRecordFile(SP->getFile());
446 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
447 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000448 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000449 // The filechecksum table uses 8 byte entries for now, and file ids start at
450 // 1.
451 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000452 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000453 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000454 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000455 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000456 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000457 OS.EmitIntValue(SP->getLine(), 4);
458 }
459
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000460 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000461}
462
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000463void CodeViewDebug::collectInlineSiteChildren(
464 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
465 const InlineSite &Site) {
466 for (const DILocation *ChildSiteLoc : Site.ChildSites) {
467 auto I = FI.InlineSites.find(ChildSiteLoc);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000468 const InlineSite &ChildSite = I->second;
469 Children.push_back(ChildSite.SiteFuncId);
470 collectInlineSiteChildren(Children, FI, ChildSite);
471 }
472}
473
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000474void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
475 const DILocation *InlinedAt,
476 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000477 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
478 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000479
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000480 assert(TypeIndices.count({Site.Inlinee, nullptr}));
481 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000482
483 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000484 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000485 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000486 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000487 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000488 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000489
Reid Klecknerdac21b42016-02-03 21:15:48 +0000490 OS.AddComment("PtrParent");
491 OS.EmitIntValue(0, 4);
492 OS.AddComment("PtrEnd");
493 OS.EmitIntValue(0, 4);
494 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000495 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000496
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000497 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
498 unsigned StartLineNum = Site.Inlinee->getLine();
499 SmallVector<unsigned, 3> SecondaryFuncIds;
500 collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
501
502 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
David Majnemerc9911f22016-02-02 19:22:34 +0000503 FI.Begin, FI.End, SecondaryFuncIds);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000504
505 OS.EmitLabel(InlineEnd);
506
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000507 for (const LocalVariable &Var : Site.InlinedLocals)
508 emitLocalVariable(Var);
509
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000510 // Recurse on child inlined call sites before closing the scope.
511 for (const DILocation *ChildSite : Site.ChildSites) {
512 auto I = FI.InlineSites.find(ChildSite);
513 assert(I != FI.InlineSites.end() &&
514 "child site not in function inline site map");
515 emitInlinedCallSite(FI, ChildSite, I->second);
516 }
517
518 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000519 OS.AddComment("Record length");
520 OS.EmitIntValue(2, 2); // RecordLength
521 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000522 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000523}
524
Reid Kleckner5d122f82016-05-25 23:16:12 +0000525void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
526 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
527 // comdat key. A section may be comdat because of -ffunction-sections or
528 // because it is comdat in the IR.
529 MCSectionCOFF *GVSec =
530 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
531 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
532
533 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
534 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
535 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
536
537 OS.SwitchSection(DebugSec);
538
539 // Emit the magic version number if this is the first time we've switched to
540 // this section.
541 if (ComdatDebugSections.insert(DebugSec).second)
542 emitCodeViewMagicVersion();
543}
544
Reid Kleckner2214ed82016-01-29 00:49:42 +0000545void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
546 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000547 // For each function there is a separate subsection
548 // which holds the PC to file:line table.
549 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000550 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000551
Reid Kleckner5d122f82016-05-25 23:16:12 +0000552 // Switch to the to a comdat section, if appropriate.
553 switchToDebugSectionForSymbol(Fn);
554
Reid Klecknerac945e22016-06-17 16:11:20 +0000555 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000556 auto *SP = GV->getSubprogram();
557 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000558
559 // If we have a display name, build the fully qualified name by walking the
560 // chain of scopes.
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000561 if (SP != nullptr && !SP->getDisplayName().empty())
562 FuncName =
563 getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000564
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000565 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000566 if (FuncName.empty())
567 FuncName = GlobalValue::getRealLinkageName(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000568
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000569 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000570 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000571 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000572 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000573 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
574 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000575 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000576 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000577 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000578
Reid Klecknerdac21b42016-02-03 21:15:48 +0000579 OS.AddComment("Record kind: S_GPROC32_ID");
Zachary Turner63a28462016-05-17 23:50:21 +0000580 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000581
David Majnemer30579ec2016-02-02 23:18:23 +0000582 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000583 OS.AddComment("PtrParent");
584 OS.EmitIntValue(0, 4);
585 OS.AddComment("PtrEnd");
586 OS.EmitIntValue(0, 4);
587 OS.AddComment("PtrNext");
588 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000589 // This is the important bit that tells the debugger where the function
590 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000591 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000592 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000593 OS.AddComment("Offset after prologue");
594 OS.EmitIntValue(0, 4);
595 OS.AddComment("Offset before epilogue");
596 OS.EmitIntValue(0, 4);
597 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000598 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000599 OS.AddComment("Function section relative address");
600 OS.EmitCOFFSecRel32(Fn);
601 OS.AddComment("Function section index");
602 OS.EmitCOFFSectionIndex(Fn);
603 OS.AddComment("Flags");
604 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000605 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000606 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000607 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000608 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000609 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000610
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000611 for (const LocalVariable &Var : FI.Locals)
612 emitLocalVariable(Var);
613
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000614 // Emit inlined call site information. Only emit functions inlined directly
615 // into the parent function. We'll emit the other sites recursively as part
616 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000617 for (const DILocation *InlinedAt : FI.ChildSites) {
618 auto I = FI.InlineSites.find(InlinedAt);
619 assert(I != FI.InlineSites.end() &&
620 "child site not in function inline site map");
621 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000622 }
623
David Majnemer3128b102016-06-15 18:00:01 +0000624 if (SP != nullptr)
625 emitDebugInfoForUDTs(LocalUDTs);
626
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000627 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000628 OS.AddComment("Record length");
629 OS.EmitIntValue(0x0002, 2);
630 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000631 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000632 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000633 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000634
Reid Kleckner2214ed82016-01-29 00:49:42 +0000635 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000636 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000637}
638
Reid Kleckner876330d2016-02-12 21:48:30 +0000639CodeViewDebug::LocalVarDefRange
640CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
641 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000642 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000643 DR.DataOffset = Offset;
644 assert(DR.DataOffset == Offset && "truncation");
645 DR.StructOffset = 0;
646 DR.CVRegister = CVRegister;
647 return DR;
648}
649
650CodeViewDebug::LocalVarDefRange
651CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
652 LocalVarDefRange DR;
653 DR.InMemory = 0;
654 DR.DataOffset = 0;
655 DR.StructOffset = 0;
656 DR.CVRegister = CVRegister;
657 return DR;
658}
659
660void CodeViewDebug::collectVariableInfoFromMMITable(
661 DenseSet<InlinedVariable> &Processed) {
662 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
663 const TargetFrameLowering *TFI = TSI.getFrameLowering();
664 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
665
666 for (const MachineModuleInfo::VariableDbgInfo &VI :
667 MMI->getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000668 if (!VI.Var)
669 continue;
670 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
671 "Expected inlined-at fields to agree");
672
Reid Kleckner876330d2016-02-12 21:48:30 +0000673 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000674 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
675
676 // If variable scope is not found then skip this variable.
677 if (!Scope)
678 continue;
679
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000680 // Get the frame register used and the offset.
681 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000682 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
683 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000684
685 // Calculate the label ranges.
Reid Kleckner876330d2016-02-12 21:48:30 +0000686 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000687 for (const InsnRange &Range : Scope->getRanges()) {
688 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
689 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000690 End = End ? End : Asm->getFunctionEnd();
691 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000692 }
693
Reid Kleckner876330d2016-02-12 21:48:30 +0000694 LocalVariable Var;
695 Var.DIVar = VI.Var;
696 Var.DefRanges.emplace_back(std::move(DefRange));
697 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
698 }
699}
700
701void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
702 DenseSet<InlinedVariable> Processed;
703 // Grab the variable info that was squirreled away in the MMI side-table.
704 collectVariableInfoFromMMITable(Processed);
705
706 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
707
708 for (const auto &I : DbgValues) {
709 InlinedVariable IV = I.first;
710 if (Processed.count(IV))
711 continue;
712 const DILocalVariable *DIVar = IV.first;
713 const DILocation *InlinedAt = IV.second;
714
715 // Instruction ranges, specifying where IV is accessible.
716 const auto &Ranges = I.second;
717
718 LexicalScope *Scope = nullptr;
719 if (InlinedAt)
720 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
721 else
722 Scope = LScopes.findLexicalScope(DIVar->getScope());
723 // If variable scope is not found then skip this variable.
724 if (!Scope)
725 continue;
726
727 LocalVariable Var;
728 Var.DIVar = DIVar;
729
730 // Calculate the definition ranges.
731 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
732 const InsnRange &Range = *I;
733 const MachineInstr *DVInst = Range.first;
734 assert(DVInst->isDebugValue() && "Invalid History entry");
735 const DIExpression *DIExpr = DVInst->getDebugExpression();
736
737 // Bail if there is a complex DWARF expression for now.
738 if (DIExpr && DIExpr->getNumElements() > 0)
739 continue;
740
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000741 // Bail if operand 0 is not a valid register. This means the variable is a
742 // simple constant, or is described by a complex expression.
743 // FIXME: Find a way to represent constant variables, since they are
744 // relatively common.
745 unsigned Reg =
746 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
747 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +0000748 continue;
749
Reid Kleckner876330d2016-02-12 21:48:30 +0000750 // Handle the two cases we can handle: indirect in memory and in register.
751 bool IsIndirect = DVInst->getOperand(1).isImm();
752 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
753 {
754 LocalVarDefRange DefRange;
755 if (IsIndirect) {
756 int64_t Offset = DVInst->getOperand(1).getImm();
757 DefRange = createDefRangeMem(CVReg, Offset);
758 } else {
759 DefRange = createDefRangeReg(CVReg);
760 }
761 if (Var.DefRanges.empty() ||
762 Var.DefRanges.back().isDifferentLocation(DefRange)) {
763 Var.DefRanges.emplace_back(std::move(DefRange));
764 }
765 }
766
767 // Compute the label range.
768 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
769 const MCSymbol *End = getLabelAfterInsn(Range.second);
770 if (!End) {
771 if (std::next(I) != E)
772 End = getLabelBeforeInsn(std::next(I)->first);
773 else
774 End = Asm->getFunctionEnd();
775 }
776
777 // If the last range end is our begin, just extend the last range.
778 // Otherwise make a new range.
779 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
780 Var.DefRanges.back().Ranges;
781 if (!Ranges.empty() && Ranges.back().second == Begin)
782 Ranges.back().second = End;
783 else
784 Ranges.emplace_back(Begin, End);
785
786 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000787 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000788
789 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000790 }
791}
792
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000793void CodeViewDebug::beginFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000794 assert(!CurFn && "Can't process two functions at once!");
795
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000796 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000797 return;
798
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000799 DebugHandlerBase::beginFunction(MF);
800
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000801 const Function *GV = MF->getFunction();
802 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000803 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +0000804 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000805 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000806
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000807 // Find the end of the function prolog. First known non-DBG_VALUE and
808 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000809 // FIXME: is there a simpler a way to do this? Can we just search
810 // for the first instruction of the function, not the last of the prolog?
811 DebugLoc PrologEndLoc;
812 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000813 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000814 for (const auto &MI : MBB) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000815 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
816 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000817 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000818 break;
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000819 } else if (!MI.isDebugValue()) {
820 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000821 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000822 }
823 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000824
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000825 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000826 if (PrologEndLoc && !EmptyPrologue) {
827 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000828 maybeRecordLocation(FnStartDL, MF);
829 }
830}
831
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000832TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000833 // Generic dispatch for lowering an unknown type.
834 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +0000835 case dwarf::DW_TAG_array_type:
836 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +0000837 case dwarf::DW_TAG_typedef:
838 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000839 case dwarf::DW_TAG_base_type:
840 return lowerTypeBasic(cast<DIBasicType>(Ty));
841 case dwarf::DW_TAG_pointer_type:
842 case dwarf::DW_TAG_reference_type:
843 case dwarf::DW_TAG_rvalue_reference_type:
844 return lowerTypePointer(cast<DIDerivedType>(Ty));
845 case dwarf::DW_TAG_ptr_to_member_type:
846 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
847 case dwarf::DW_TAG_const_type:
848 case dwarf::DW_TAG_volatile_type:
849 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +0000850 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000851 if (ClassTy) {
852 // The member function type of a member function pointer has no
853 // ThisAdjustment.
854 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
855 /*ThisAdjustment=*/0);
856 }
David Majnemer75c3ebf2016-06-02 17:13:53 +0000857 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +0000858 case dwarf::DW_TAG_enumeration_type:
859 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +0000860 case dwarf::DW_TAG_class_type:
861 case dwarf::DW_TAG_structure_type:
862 return lowerTypeClass(cast<DICompositeType>(Ty));
863 case dwarf::DW_TAG_union_type:
864 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000865 default:
866 // Use the null type index.
867 return TypeIndex();
868 }
869}
870
David Majnemerd065e232016-06-02 06:21:37 +0000871TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +0000872 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
873 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +0000874 StringRef TypeName = Ty->getName();
875
876 SmallVector<StringRef, 5> QualifiedNameComponents;
877 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
878 Ty->getScope().resolve(), QualifiedNameComponents);
879
880 if (ClosestSubprogram == nullptr) {
881 std::string FullyQualifiedName =
882 getQualifiedName(QualifiedNameComponents, TypeName);
883 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), UnderlyingTypeIndex);
884 } else if (ClosestSubprogram == CurrentSubprogram) {
885 std::string FullyQualifiedName =
886 getQualifiedName(QualifiedNameComponents, TypeName);
887 LocalUDTs.emplace_back(std::move(FullyQualifiedName), UnderlyingTypeIndex);
888 }
889 // TODO: What if the ClosestSubprogram is neither null or the current
890 // subprogram? Currently, the UDT just gets dropped on the floor.
891 //
892 // The current behavior is not desirable. To get maximal fidelity, we would
893 // need to perform all type translation before beginning emission of .debug$S
894 // and then make LocalUDTs a member of FunctionInfo
895
David Majnemerd065e232016-06-02 06:21:37 +0000896 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +0000897 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +0000898 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +0000899 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +0000900 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +0000901 return TypeIndex(SimpleTypeKind::WideCharacter);
David Majnemerd065e232016-06-02 06:21:37 +0000902 return UnderlyingTypeIndex;
903}
904
Adrian McCarthyf3c3c132016-06-08 18:22:59 +0000905TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
906 DITypeRef ElementTypeRef = Ty->getBaseType();
907 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
908 // IndexType is size_t, which depends on the bitness of the target.
909 TypeIndex IndexType = Asm->MAI->getPointerSize() == 8
910 ? TypeIndex(SimpleTypeKind::UInt64Quad)
911 : TypeIndex(SimpleTypeKind::UInt32Long);
912 uint64_t Size = Ty->getSizeInBits() / 8;
913 ArrayRecord Record(ElementTypeIndex, IndexType, Size, Ty->getName());
914 return TypeTable.writeArray(Record);
915}
916
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000917TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
918 TypeIndex Index;
919 dwarf::TypeKind Kind;
920 uint32_t ByteSize;
921
922 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +0000923 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000924
925 SimpleTypeKind STK = SimpleTypeKind::None;
926 switch (Kind) {
927 case dwarf::DW_ATE_address:
928 // FIXME: Translate
929 break;
930 case dwarf::DW_ATE_boolean:
931 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000932 case 1: STK = SimpleTypeKind::Boolean8; break;
933 case 2: STK = SimpleTypeKind::Boolean16; break;
934 case 4: STK = SimpleTypeKind::Boolean32; break;
935 case 8: STK = SimpleTypeKind::Boolean64; break;
936 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000937 }
938 break;
939 case dwarf::DW_ATE_complex_float:
940 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000941 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000942 case 4: STK = SimpleTypeKind::Complex32; break;
943 case 8: STK = SimpleTypeKind::Complex64; break;
944 case 10: STK = SimpleTypeKind::Complex80; break;
945 case 16: STK = SimpleTypeKind::Complex128; break;
946 }
947 break;
948 case dwarf::DW_ATE_float:
949 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000950 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000951 case 4: STK = SimpleTypeKind::Float32; break;
952 case 6: STK = SimpleTypeKind::Float48; break;
953 case 8: STK = SimpleTypeKind::Float64; break;
954 case 10: STK = SimpleTypeKind::Float80; break;
955 case 16: STK = SimpleTypeKind::Float128; break;
956 }
957 break;
958 case dwarf::DW_ATE_signed:
959 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000960 case 1: STK = SimpleTypeKind::SByte; break;
961 case 2: STK = SimpleTypeKind::Int16Short; break;
962 case 4: STK = SimpleTypeKind::Int32; break;
963 case 8: STK = SimpleTypeKind::Int64Quad; break;
964 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000965 }
966 break;
967 case dwarf::DW_ATE_unsigned:
968 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000969 case 1: STK = SimpleTypeKind::Byte; break;
970 case 2: STK = SimpleTypeKind::UInt16Short; break;
971 case 4: STK = SimpleTypeKind::UInt32; break;
972 case 8: STK = SimpleTypeKind::UInt64Quad; break;
973 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000974 }
975 break;
976 case dwarf::DW_ATE_UTF:
977 switch (ByteSize) {
978 case 2: STK = SimpleTypeKind::Character16; break;
979 case 4: STK = SimpleTypeKind::Character32; break;
980 }
981 break;
982 case dwarf::DW_ATE_signed_char:
983 if (ByteSize == 1)
984 STK = SimpleTypeKind::SignedCharacter;
985 break;
986 case dwarf::DW_ATE_unsigned_char:
987 if (ByteSize == 1)
988 STK = SimpleTypeKind::UnsignedCharacter;
989 break;
990 default:
991 break;
992 }
993
994 // Apply some fixups based on the source-level type name.
995 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
996 STK = SimpleTypeKind::Int32Long;
997 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
998 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +0000999 if (STK == SimpleTypeKind::UInt16Short &&
1000 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001001 STK = SimpleTypeKind::WideCharacter;
1002 if ((STK == SimpleTypeKind::SignedCharacter ||
1003 STK == SimpleTypeKind::UnsignedCharacter) &&
1004 Ty->getName() == "char")
1005 STK = SimpleTypeKind::NarrowCharacter;
1006
1007 return TypeIndex(STK);
1008}
1009
1010TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1011 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1012
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001013 // While processing the type being pointed to it is possible we already
1014 // created this pointer type. If so, we check here and return the existing
1015 // pointer type.
1016 auto I = TypeIndices.find({Ty, nullptr});
1017 if (I != TypeIndices.end())
1018 return I->second;
1019
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001020 // Pointers to simple types can use SimpleTypeMode, rather than having a
1021 // dedicated pointer type record.
1022 if (PointeeTI.isSimple() &&
1023 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1024 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1025 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1026 ? SimpleTypeMode::NearPointer64
1027 : SimpleTypeMode::NearPointer32;
1028 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1029 }
1030
1031 PointerKind PK =
1032 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1033 PointerMode PM = PointerMode::Pointer;
1034 switch (Ty->getTag()) {
1035 default: llvm_unreachable("not a pointer tag type");
1036 case dwarf::DW_TAG_pointer_type:
1037 PM = PointerMode::Pointer;
1038 break;
1039 case dwarf::DW_TAG_reference_type:
1040 PM = PointerMode::LValueReference;
1041 break;
1042 case dwarf::DW_TAG_rvalue_reference_type:
1043 PM = PointerMode::RValueReference;
1044 break;
1045 }
1046 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1047 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1048 // do.
1049 PointerOptions PO = PointerOptions::None;
1050 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1051 return TypeTable.writePointer(PR);
1052}
1053
Reid Kleckner6fa15462016-06-17 22:14:39 +00001054static PointerToMemberRepresentation
1055translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1056 // SizeInBytes being zero generally implies that the member pointer type was
1057 // incomplete, which can happen if it is part of a function prototype. In this
1058 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001059 if (IsPMF) {
1060 switch (Flags & DINode::FlagPtrToMemberRep) {
1061 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001062 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1063 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001064 case DINode::FlagSingleInheritance:
1065 return PointerToMemberRepresentation::SingleInheritanceFunction;
1066 case DINode::FlagMultipleInheritance:
1067 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1068 case DINode::FlagVirtualInheritance:
1069 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1070 }
1071 } else {
1072 switch (Flags & DINode::FlagPtrToMemberRep) {
1073 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001074 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1075 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001076 case DINode::FlagSingleInheritance:
1077 return PointerToMemberRepresentation::SingleInheritanceData;
1078 case DINode::FlagMultipleInheritance:
1079 return PointerToMemberRepresentation::MultipleInheritanceData;
1080 case DINode::FlagVirtualInheritance:
1081 return PointerToMemberRepresentation::VirtualInheritanceData;
1082 }
1083 }
1084 llvm_unreachable("invalid ptr to member representation");
1085}
1086
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001087TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1088 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1089 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001090 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001091 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
1092 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001093 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1094 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1095 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001096 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner6fa15462016-06-17 22:14:39 +00001097 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1098 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1099 MemberPointerInfo MPI(
1100 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001101 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001102 return TypeTable.writePointer(PR);
1103}
1104
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001105/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1106/// have a translation, use the NearC convention.
1107static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1108 switch (DwarfCC) {
1109 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1110 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1111 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1112 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1113 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1114 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1115 }
1116 return CallingConvention::NearC;
1117}
1118
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001119TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1120 ModifierOptions Mods = ModifierOptions::None;
1121 bool IsModifier = true;
1122 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001123 while (IsModifier && BaseTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001124 // FIXME: Need to add DWARF tag for __unaligned.
1125 switch (BaseTy->getTag()) {
1126 case dwarf::DW_TAG_const_type:
1127 Mods |= ModifierOptions::Const;
1128 break;
1129 case dwarf::DW_TAG_volatile_type:
1130 Mods |= ModifierOptions::Volatile;
1131 break;
1132 default:
1133 IsModifier = false;
1134 break;
1135 }
1136 if (IsModifier)
1137 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1138 }
1139 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001140
1141 // While processing the type being pointed to, it is possible we already
1142 // created this modifier type. If so, we check here and return the existing
1143 // modifier type.
1144 auto I = TypeIndices.find({Ty, nullptr});
1145 if (I != TypeIndices.end())
1146 return I->second;
1147
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001148 ModifierRecord MR(ModifiedTI, Mods);
1149 return TypeTable.writeModifier(MR);
1150}
1151
David Majnemer75c3ebf2016-06-02 17:13:53 +00001152TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1153 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1154 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1155 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1156
1157 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1158 ArrayRef<TypeIndex> ArgTypeIndices = None;
1159 if (!ReturnAndArgTypeIndices.empty()) {
1160 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1161 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1162 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1163 }
1164
1165 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1166 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
1167
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001168 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1169
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001170 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1171 ArgTypeIndices.size(), ArgListIndex);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001172 return TypeTable.writeProcedure(Procedure);
1173}
1174
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001175TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001176 const DIType *ClassTy,
1177 int ThisAdjustment) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001178 // Lower the containing class type.
1179 TypeIndex ClassType = getTypeIndex(ClassTy);
1180
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001181 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1182 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1183 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1184
1185 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1186 ArrayRef<TypeIndex> ArgTypeIndices = None;
1187 if (!ReturnAndArgTypeIndices.empty()) {
1188 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1189 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1190 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1191 }
1192 TypeIndex ThisTypeIndex = TypeIndex::Void();
1193 if (!ArgTypeIndices.empty()) {
1194 ThisTypeIndex = ArgTypeIndices.front();
1195 ArgTypeIndices = ArgTypeIndices.drop_front();
1196 }
1197
1198 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1199 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
1200
1201 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1202
1203 // TODO: Need to use the correct values for:
1204 // FunctionOptions
1205 // ThisPointerAdjustment.
1206 TypeIndex TI = TypeTable.writeMemberFunction(MemberFunctionRecord(
1207 ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FunctionOptions::None,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001208 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001209
1210 return TI;
1211}
1212
1213static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1214 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001215 case DINode::FlagPrivate: return MemberAccess::Private;
1216 case DINode::FlagPublic: return MemberAccess::Public;
1217 case DINode::FlagProtected: return MemberAccess::Protected;
1218 case 0:
1219 // If there was no explicit access control, provide the default for the tag.
1220 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1221 : MemberAccess::Public;
1222 }
1223 llvm_unreachable("access flags are exclusive");
1224}
1225
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001226static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1227 if (SP->isArtificial())
1228 return MethodOptions::CompilerGenerated;
1229
1230 // FIXME: Handle other MethodOptions.
1231
1232 return MethodOptions::None;
1233}
1234
1235static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1236 bool Introduced) {
1237 switch (SP->getVirtuality()) {
1238 case dwarf::DW_VIRTUALITY_none:
1239 break;
1240 case dwarf::DW_VIRTUALITY_virtual:
1241 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1242 case dwarf::DW_VIRTUALITY_pure_virtual:
1243 return Introduced ? MethodKind::PureIntroducingVirtual
1244 : MethodKind::PureVirtual;
1245 default:
1246 llvm_unreachable("unhandled virtuality case");
1247 }
1248
1249 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1250
1251 return MethodKind::Vanilla;
1252}
1253
Reid Klecknera8d57402016-06-03 15:58:20 +00001254static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1255 switch (Ty->getTag()) {
1256 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1257 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1258 }
1259 llvm_unreachable("unexpected tag");
1260}
1261
1262/// Return the HasUniqueName option if it should be present in ClassOptions, or
1263/// None otherwise.
1264static ClassOptions getRecordUniqueNameOption(const DICompositeType *Ty) {
1265 // MSVC always sets this flag now, even for local types. Clang doesn't always
1266 // appear to give every type a linkage name, which may be problematic for us.
1267 // FIXME: Investigate the consequences of not following them here.
1268 return !Ty->getIdentifier().empty() ? ClassOptions::HasUniqueName
1269 : ClassOptions::None;
1270}
1271
David Majnemer979cb882016-06-16 21:32:16 +00001272TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
1273 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1274 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001275 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001276
David Majnemerda9548f2016-06-17 16:13:21 +00001277 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001278 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001279 } else {
1280 FieldListRecordBuilder Fields;
1281 for (const DINode *Element : Ty->getElements()) {
1282 // We assume that the frontend provides all members in source declaration
1283 // order, which is what MSVC does.
1284 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
1285 Fields.writeEnumerator(EnumeratorRecord(
1286 MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()),
1287 Enumerator->getName()));
1288 EnumeratorCount++;
1289 }
1290 }
1291 FTI = TypeTable.writeFieldList(Fields);
1292 }
David Majnemer979cb882016-06-16 21:32:16 +00001293
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001294 std::string FullName =
1295 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
1296
1297 return TypeTable.writeEnum(EnumRecord(EnumeratorCount, CO, FTI, FullName,
David Majnemer979cb882016-06-16 21:32:16 +00001298 Ty->getIdentifier(),
1299 getTypeIndex(Ty->getBaseType())));
1300}
1301
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001302//===----------------------------------------------------------------------===//
1303// ClassInfo
1304//===----------------------------------------------------------------------===//
1305
1306struct llvm::ClassInfo {
1307 struct MemberInfo {
1308 const DIDerivedType *MemberTypeNode;
1309 unsigned BaseOffset;
1310 };
1311 // [MemberInfo]
1312 typedef std::vector<MemberInfo> MemberList;
1313
Reid Kleckner156a7232016-06-22 18:31:14 +00001314 typedef TinyPtrVector<const DISubprogram *> MethodsList;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001315 // MethodName -> MethodsList
1316 typedef MapVector<MDString *, MethodsList> MethodsMap;
1317
1318 /// Direct members.
1319 MemberList Members;
1320 // Direct overloaded methods gathered by name.
1321 MethodsMap Methods;
1322};
1323
1324void CodeViewDebug::clear() {
1325 assert(CurFn == nullptr);
1326 FileIdMap.clear();
1327 FnDebugInfo.clear();
1328 FileToFilepathMap.clear();
1329 LocalUDTs.clear();
1330 GlobalUDTs.clear();
1331 TypeIndices.clear();
1332 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001333}
1334
1335void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1336 const DIDerivedType *DDTy) {
1337 if (!DDTy->getName().empty()) {
1338 Info.Members.push_back({DDTy, 0});
1339 return;
1340 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001341 // An unnamed member must represent a nested struct or union. Add all the
1342 // indirect fields to the current record.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001343 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001344 unsigned Offset = DDTy->getOffsetInBits() / 8;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001345 const DIType *Ty = DDTy->getBaseType().resolve();
Reid Kleckner9ff936c2016-06-21 14:56:24 +00001346 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001347 ClassInfo NestedInfo = collectClassInfo(DCTy);
1348 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001349 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001350 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001351}
1352
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001353ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1354 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001355 // Add elements to structure type.
1356 DINodeArray Elements = Ty->getElements();
1357 for (auto *Element : Elements) {
1358 // We assume that the frontend provides all members in source declaration
1359 // order, which is what MSVC does.
1360 if (!Element)
1361 continue;
1362 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001363 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001364 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
1365 if (DDTy->getTag() == dwarf::DW_TAG_member)
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001366 collectMemberInfo(Info, DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001367 else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1368 // FIXME: collect class info from inheritance.
1369 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1370 // Ignore friend members. It appears that MSVC emitted info about
1371 // friends in the past, but modern versions do not.
1372 }
1373 // FIXME: Get Clang to emit function virtual table here and handle it.
1374 // FIXME: Get clang to emit nested types here and do something with
1375 // them.
1376 }
1377 // Skip other unrecognized kinds of elements.
1378 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001379 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001380}
1381
Reid Klecknera8d57402016-06-03 15:58:20 +00001382TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1383 // First, construct the forward decl. Don't look into Ty to compute the
1384 // forward decl options, since it might not be available in all TUs.
1385 TypeRecordKind Kind = getRecordKind(Ty);
1386 ClassOptions CO =
1387 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001388 std::string FullName =
1389 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
Reid Klecknera8d57402016-06-03 15:58:20 +00001390 TypeIndex FwdDeclTI = TypeTable.writeClass(ClassRecord(
1391 Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(),
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001392 TypeIndex(), TypeIndex(), 0, FullName, Ty->getIdentifier()));
Reid Kleckner643dd832016-06-22 17:15:28 +00001393 if (!Ty->isForwardDecl())
1394 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001395 return FwdDeclTI;
1396}
1397
1398TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1399 // Construct the field list and complete type record.
1400 TypeRecordKind Kind = getRecordKind(Ty);
1401 // FIXME: Other ClassOptions, like ContainsNestedClass and NestedClass.
1402 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001403 TypeIndex FieldTI;
1404 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001405 unsigned FieldCount;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001406 std::tie(FieldTI, VShapeTI, FieldCount) = lowerRecordFieldList(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001407
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001408 std::string FullName =
1409 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
1410
Reid Klecknera8d57402016-06-03 15:58:20 +00001411 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00001412
1413 TypeIndex ClassTI = TypeTable.writeClass(ClassRecord(
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001414 Kind, FieldCount, CO, HfaKind::None, WindowsRTClassKind::None, FieldTI,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001415 TypeIndex(), VShapeTI, SizeInBytes, FullName, Ty->getIdentifier()));
Hans Wennborg9a519a02016-06-22 21:22:13 +00001416
1417 TypeTable.writeUdtSourceLine(UdtSourceLineRecord(
1418 ClassTI, TypeTable.writeStringId(StringIdRecord(
1419 TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1420 Ty->getLine()));
1421
1422 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001423}
1424
1425TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1426 ClassOptions CO =
1427 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001428 std::string FullName =
1429 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
Reid Klecknera8d57402016-06-03 15:58:20 +00001430 TypeIndex FwdDeclTI =
1431 TypeTable.writeUnion(UnionRecord(0, CO, HfaKind::None, TypeIndex(), 0,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001432 FullName, Ty->getIdentifier()));
Reid Kleckner643dd832016-06-22 17:15:28 +00001433 if (!Ty->isForwardDecl())
1434 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001435 return FwdDeclTI;
1436}
1437
1438TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
1439 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001440 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001441 unsigned FieldCount;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001442 std::tie(FieldTI, std::ignore, FieldCount) = lowerRecordFieldList(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001443 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001444 std::string FullName =
1445 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
Hans Wennborg9a519a02016-06-22 21:22:13 +00001446
1447 TypeIndex UnionTI = TypeTable.writeUnion(
1448 UnionRecord(FieldCount, CO, HfaKind::None, FieldTI, SizeInBytes, FullName,
1449 Ty->getIdentifier()));
1450
1451 TypeTable.writeUdtSourceLine(UdtSourceLineRecord(
1452 UnionTI, TypeTable.writeStringId(StringIdRecord(
1453 TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1454 Ty->getLine()));
1455
1456 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001457}
1458
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001459std::tuple<TypeIndex, TypeIndex, unsigned>
Reid Klecknera8d57402016-06-03 15:58:20 +00001460CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1461 // Manually count members. MSVC appears to count everything that generates a
1462 // field list record. Each individual overload in a method overload group
1463 // contributes to this count, even though the overload group is a single field
1464 // list record.
1465 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001466 ClassInfo Info = collectClassInfo(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001467 FieldListRecordBuilder Fields;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001468
1469 // Create members.
1470 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1471 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1472 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
1473
1474 if (Member->isStaticMember()) {
1475 Fields.writeStaticDataMember(StaticDataMemberRecord(
1476 translateAccessFlags(Ty->getTag(), Member->getFlags()),
1477 MemberBaseType, Member->getName()));
1478 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001479 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00001480 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001481
1482 uint64_t OffsetInBytes = MemberInfo.BaseOffset;
1483
1484 // FIXME: Handle bitfield type memeber.
1485 OffsetInBytes += Member->getOffsetInBits() / 8;
1486
1487 Fields.writeDataMember(
1488 DataMemberRecord(translateAccessFlags(Ty->getTag(), Member->getFlags()),
1489 MemberBaseType, OffsetInBytes, Member->getName()));
1490 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001491 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001492
1493 // Create methods
1494 for (auto &MethodItr : Info.Methods) {
1495 StringRef Name = MethodItr.first->getString();
1496
1497 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00001498 for (const DISubprogram *SP : MethodItr.second) {
1499 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1500 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001501
1502 unsigned VFTableOffset = -1;
1503 if (Introduced)
1504 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1505
1506 Methods.push_back(
1507 OneMethodRecord(MethodType, translateMethodKindFlags(SP, Introduced),
1508 translateMethodOptionFlags(SP),
1509 translateAccessFlags(Ty->getTag(), SP->getFlags()),
1510 VFTableOffset, Name));
1511 MemberCount++;
1512 }
1513 assert(Methods.size() > 0 && "Empty methods map entry");
1514 if (Methods.size() == 1)
1515 Fields.writeOneMethod(Methods[0]);
1516 else {
1517 TypeIndex MethodList =
1518 TypeTable.writeMethodOverloadList(MethodOverloadListRecord(Methods));
1519 Fields.writeOverloadedMethod(
1520 OverloadedMethodRecord(Methods.size(), MethodList, Name));
1521 }
1522 }
1523 TypeIndex FieldTI = TypeTable.writeFieldList(Fields);
1524 return std::make_tuple(FieldTI, TypeIndex(), MemberCount);
Reid Klecknera8d57402016-06-03 15:58:20 +00001525}
1526
Reid Kleckner643dd832016-06-22 17:15:28 +00001527struct CodeViewDebug::TypeLoweringScope {
1528 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
1529 ~TypeLoweringScope() {
1530 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
1531 // inner TypeLoweringScopes don't attempt to emit deferred types.
1532 if (CVD.TypeEmissionLevel == 1)
1533 CVD.emitDeferredCompleteTypes();
1534 --CVD.TypeEmissionLevel;
1535 }
1536 CodeViewDebug &CVD;
1537};
1538
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001539TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001540 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001541 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001542
1543 // The null DIType is the void type. Don't try to hash it.
1544 if (!Ty)
1545 return TypeIndex::Void();
1546
Reid Klecknera8d57402016-06-03 15:58:20 +00001547 // Check if we've already translated this type. Don't try to do a
1548 // get-or-create style insertion that caches the hash lookup across the
1549 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001550 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001551 if (I != TypeIndices.end())
1552 return I->second;
1553
Reid Kleckner643dd832016-06-22 17:15:28 +00001554 TypeIndex TI;
1555 {
1556 TypeLoweringScope S(*this);
1557 TI = lowerType(Ty, ClassTy);
1558 recordTypeIndexForDINode(Ty, TI, ClassTy);
1559 }
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001560
Reid Kleckner643dd832016-06-22 17:15:28 +00001561 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001562}
1563
1564TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1565 const DIType *Ty = TypeRef.resolve();
1566
1567 // The null DIType is the void type. Don't try to hash it.
1568 if (!Ty)
1569 return TypeIndex::Void();
1570
1571 // If this is a non-record type, the complete type index is the same as the
1572 // normal type index. Just call getTypeIndex.
1573 switch (Ty->getTag()) {
1574 case dwarf::DW_TAG_class_type:
1575 case dwarf::DW_TAG_structure_type:
1576 case dwarf::DW_TAG_union_type:
1577 break;
1578 default:
1579 return getTypeIndex(Ty);
1580 }
1581
1582 // Check if we've already translated the complete record type. Lowering a
1583 // complete type should never trigger lowering another complete type, so we
1584 // can reuse the hash table lookup result.
1585 const auto *CTy = cast<DICompositeType>(Ty);
1586 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1587 if (!InsertResult.second)
1588 return InsertResult.first->second;
1589
Reid Kleckner643dd832016-06-22 17:15:28 +00001590 TypeLoweringScope S(*this);
1591
Reid Klecknera8d57402016-06-03 15:58:20 +00001592 // Make sure the forward declaration is emitted first. It's unclear if this
1593 // is necessary, but MSVC does it, and we should follow suit until we can show
1594 // otherwise.
1595 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1596
1597 // Just use the forward decl if we don't have complete type info. This might
1598 // happen if the frontend is using modules and expects the complete definition
1599 // to be emitted elsewhere.
1600 if (CTy->isForwardDecl())
1601 return FwdDeclTI;
1602
1603 TypeIndex TI;
1604 switch (CTy->getTag()) {
1605 case dwarf::DW_TAG_class_type:
1606 case dwarf::DW_TAG_structure_type:
1607 TI = lowerCompleteTypeClass(CTy);
1608 break;
1609 case dwarf::DW_TAG_union_type:
1610 TI = lowerCompleteTypeUnion(CTy);
1611 break;
1612 default:
1613 llvm_unreachable("not a record");
1614 }
1615
1616 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001617 return TI;
1618}
1619
Reid Kleckner643dd832016-06-22 17:15:28 +00001620/// Emit all the deferred complete record types. Try to do this in FIFO order,
1621/// and do this until fixpoint, as each complete record type typically references
1622/// many other record types.
1623void CodeViewDebug::emitDeferredCompleteTypes() {
1624 SmallVector<const DICompositeType *, 4> TypesToEmit;
1625 while (!DeferredCompleteTypes.empty()) {
1626 std::swap(DeferredCompleteTypes, TypesToEmit);
1627 for (const DICompositeType *RecordTy : TypesToEmit)
1628 getCompleteTypeIndex(RecordTy);
1629 TypesToEmit.clear();
1630 }
1631}
1632
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001633void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
1634 // LocalSym record, see SymbolRecord.h for more info.
1635 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
1636 *LocalEnd = MMI->getContext().createTempSymbol();
1637 OS.AddComment("Record length");
1638 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
1639 OS.EmitLabel(LocalBegin);
1640
1641 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00001642 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001643
Zachary Turner63a28462016-05-17 23:50:21 +00001644 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001645 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00001646 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00001647 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00001648 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001649
1650 OS.AddComment("TypeIndex");
Reid Klecknera8d57402016-06-03 15:58:20 +00001651 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001652 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001653 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00001654 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00001655 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00001656 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001657 OS.EmitLabel(LocalEnd);
1658
Reid Kleckner876330d2016-02-12 21:48:30 +00001659 // Calculate the on disk prefix of the appropriate def range record. The
1660 // records and on disk formats are described in SymbolRecords.h. BytePrefix
1661 // should be big enough to hold all forms without memory allocation.
1662 SmallString<20> BytePrefix;
1663 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
1664 BytePrefix.clear();
1665 // FIXME: Handle bitpieces.
1666 if (DefRange.StructOffset != 0)
1667 continue;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001668
Reid Kleckner876330d2016-02-12 21:48:30 +00001669 if (DefRange.InMemory) {
Zachary Turnera78ecd12016-05-23 18:49:06 +00001670 DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
1671 0, 0, ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001672 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00001673 BytePrefix +=
1674 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001675 BytePrefix +=
1676 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1677 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001678 } else {
1679 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Zachary Turnera78ecd12016-05-23 18:49:06 +00001680 // Unclear what matters here.
1681 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
1682 ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001683 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
Reid Kleckner876330d2016-02-12 21:48:30 +00001684 BytePrefix +=
1685 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001686 BytePrefix +=
1687 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1688 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001689 }
1690 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
1691 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001692}
1693
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001694void CodeViewDebug::endFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001695 if (!Asm || !CurFn) // We haven't created any debug info for this function.
1696 return;
1697
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001698 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00001699 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001700 assert(CurFn == &FnDebugInfo[GV]);
1701
Pete Cooperadebb932016-03-11 02:14:16 +00001702 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00001703
1704 DebugHandlerBase::endFunction(MF);
1705
Reid Kleckner2214ed82016-01-29 00:49:42 +00001706 // Don't emit anything if we don't have any line tables.
1707 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001708 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001709 CurFn = nullptr;
1710 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00001711 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001712
1713 CurFn->End = Asm->getFunctionEnd();
1714
Craig Topper353eda42014-04-24 06:44:33 +00001715 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001716}
1717
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001718void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001719 DebugHandlerBase::beginInstruction(MI);
1720
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001721 // Ignore DBG_VALUE locations and function prologue.
1722 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
1723 return;
1724 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001725 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001726 return;
1727 maybeRecordLocation(DL, Asm->MF);
1728}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001729
1730MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
1731 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
1732 *EndLabel = MMI->getContext().createTempSymbol();
1733 OS.EmitIntValue(unsigned(Kind), 4);
1734 OS.AddComment("Subsection size");
1735 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
1736 OS.EmitLabel(BeginLabel);
1737 return EndLabel;
1738}
1739
1740void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
1741 OS.EmitLabel(EndLabel);
1742 // Every subsection must be aligned to a 4-byte boundary.
1743 OS.EmitValueToAlignment(4);
1744}
1745
David Majnemer3128b102016-06-15 18:00:01 +00001746void CodeViewDebug::emitDebugInfoForUDTs(
1747 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
1748 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
1749 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
1750 *UDTRecordEnd = MMI->getContext().createTempSymbol();
1751 OS.AddComment("Record length");
1752 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
1753 OS.EmitLabel(UDTRecordBegin);
1754
1755 OS.AddComment("Record kind: S_UDT");
1756 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
1757
1758 OS.AddComment("Type");
1759 OS.EmitIntValue(UDT.second.getIndex(), 4);
1760
1761 emitNullTerminatedSymbolName(OS, UDT.first);
1762 OS.EmitLabel(UDTRecordEnd);
1763 }
1764}
1765
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001766void CodeViewDebug::emitDebugInfoForGlobals() {
1767 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
1768 for (const MDNode *Node : CUs->operands()) {
1769 const auto *CU = cast<DICompileUnit>(Node);
1770
1771 // First, emit all globals that are not in a comdat in a single symbol
1772 // substream. MSVC doesn't like it if the substream is empty, so only open
1773 // it if we have at least one global to emit.
1774 switchToDebugSectionForSymbol(nullptr);
1775 MCSymbol *EndLabel = nullptr;
1776 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Reid Kleckner6d1d2752016-06-09 00:29:00 +00001777 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
David Majnemer577be0f2016-06-15 00:19:52 +00001778 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001779 if (!EndLabel) {
1780 OS.AddComment("Symbol subsection for globals");
1781 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
1782 }
1783 emitDebugInfoForGlobal(G, Asm->getSymbol(GV));
1784 }
Reid Kleckner6d1d2752016-06-09 00:29:00 +00001785 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001786 }
1787 if (EndLabel)
1788 endCVSubsection(EndLabel);
1789
1790 // Second, emit each global that is in a comdat into its own .debug$S
1791 // section along with its own symbol substream.
1792 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Reid Kleckner6d1d2752016-06-09 00:29:00 +00001793 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001794 if (GV->hasComdat()) {
1795 MCSymbol *GVSym = Asm->getSymbol(GV);
1796 OS.AddComment("Symbol subsection for " +
1797 Twine(GlobalValue::getRealLinkageName(GV->getName())));
1798 switchToDebugSectionForSymbol(GVSym);
1799 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
1800 emitDebugInfoForGlobal(G, GVSym);
1801 endCVSubsection(EndLabel);
1802 }
1803 }
1804 }
1805 }
1806}
1807
Hans Wennborgb510b452016-06-23 16:33:53 +00001808void CodeViewDebug::emitDebugInfoForRetainedTypes() {
1809 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
1810 for (const MDNode *Node : CUs->operands()) {
1811 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
1812 if (DIType *RT = dyn_cast<DIType>(Ty)) {
1813 getTypeIndex(RT);
1814 // FIXME: Add to global/local DTU list.
1815 }
1816 }
1817 }
1818}
1819
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001820void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
1821 MCSymbol *GVSym) {
1822 // DataSym record, see SymbolRecord.h for more info.
1823 // FIXME: Thread local data, etc
1824 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
1825 *DataEnd = MMI->getContext().createTempSymbol();
1826 OS.AddComment("Record length");
1827 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
1828 OS.EmitLabel(DataBegin);
1829 OS.AddComment("Record kind: S_GDATA32");
1830 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
1831 OS.AddComment("Type");
1832 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
1833 OS.AddComment("DataOffset");
1834 OS.EmitCOFFSecRel32(GVSym);
1835 OS.AddComment("Segment");
1836 OS.EmitCOFFSectionIndex(GVSym);
1837 OS.AddComment("Name");
1838 emitNullTerminatedSymbolName(OS, DIGV->getName());
1839 OS.EmitLabel(DataEnd);
1840}