blob: b673a4bba46b3e84d790f4c34ddb57bbb66c2bb6 [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 Kleckner6b3faef2016-01-13 23:44:57 +000015#include "llvm/DebugInfo/CodeView/CodeView.h"
Reid Klecknera8d57402016-06-03 15:58:20 +000016#include "llvm/DebugInfo/CodeView/FieldListRecordBuilder.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000017#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000018#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000019#include "llvm/DebugInfo/CodeView/TypeDumper.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000020#include "llvm/DebugInfo/CodeView/TypeIndex.h"
21#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000022#include "llvm/MC/MCExpr.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000023#include "llvm/MC/MCSectionCOFF.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000024#include "llvm/MC/MCSymbol.h"
25#include "llvm/Support/COFF.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000026#include "llvm/Support/ScopedPrinter.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000027#include "llvm/Target/TargetSubtargetInfo.h"
28#include "llvm/Target/TargetRegisterInfo.h"
29#include "llvm/Target/TargetFrameLowering.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000030
Reid Klecknerf9c275f2016-02-10 20:55:49 +000031using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000032using namespace llvm::codeview;
33
Reid Klecknerf9c275f2016-02-10 20:55:49 +000034CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
35 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
36 // If module doesn't have named metadata anchors or COFF debug section
37 // is not available, skip any debug info related stuff.
38 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
39 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
40 Asm = nullptr;
41 return;
42 }
43
44 // Tell MMI that we have debug info.
45 MMI->setDebugInfoAvailability(true);
46}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000047
Reid Kleckner9533af42016-01-16 00:09:09 +000048StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
49 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000050 if (!Filepath.empty())
51 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000052
Reid Kleckner9533af42016-01-16 00:09:09 +000053 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
54
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000055 // Clang emits directory and relative filename info into the IR, but CodeView
56 // operates on full paths. We could change Clang to emit full paths too, but
57 // that would increase the IR size and probably not needed for other users.
58 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000059 if (Filename.find(':') == 1)
60 Filepath = Filename;
61 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +000062 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000063
64 // Canonicalize the path. We have to do it textually because we may no longer
65 // have access the file in the filesystem.
66 // First, replace all slashes with backslashes.
67 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
68
69 // Remove all "\.\" with "\".
70 size_t Cursor = 0;
71 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
72 Filepath.erase(Cursor, 2);
73
74 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
75 // path should be well-formatted, e.g. start with a drive letter, etc.
76 Cursor = 0;
77 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
78 // Something's wrong if the path starts with "\..\", abort.
79 if (Cursor == 0)
80 break;
81
82 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
83 if (PrevSlash == std::string::npos)
84 // Something's wrong, abort.
85 break;
86
87 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
88 // The next ".." might be following the one we've just erased.
89 Cursor = PrevSlash;
90 }
91
92 // Remove all duplicate backslashes.
93 Cursor = 0;
94 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
95 Filepath.erase(Cursor, 1);
96
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000097 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000098}
99
Reid Kleckner2214ed82016-01-29 00:49:42 +0000100unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
101 unsigned NextId = FileIdMap.size() + 1;
102 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
103 if (Insertion.second) {
104 // We have to compute the full filepath and emit a .cv_file directive.
105 StringRef FullPath = getFullFilepath(F);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000106 NextId = OS.EmitCVFileDirective(NextId, FullPath);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000107 assert(NextId == FileIdMap.size() && ".cv_file directive failed");
108 }
109 return Insertion.first->second;
110}
111
Reid Kleckner876330d2016-02-12 21:48:30 +0000112CodeViewDebug::InlineSite &
113CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
114 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000115 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
116 InlineSite *Site = &SiteInsertion.first->second;
117 if (SiteInsertion.second) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000118 Site->SiteFuncId = NextFuncId++;
Reid Kleckner876330d2016-02-12 21:48:30 +0000119 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000120 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000121 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000122 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000123 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000124}
125
David Majnemer75c3ebf2016-06-02 17:13:53 +0000126TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
127 // It's possible to ask for the FuncId of a function which doesn't have a
128 // subprogram: inlining a function with debug info into a function with none.
129 if (!SP)
David Majnemerb68f32f02016-06-02 18:51:24 +0000130 return TypeIndex::None();
Reid Kleckner2280f932016-05-23 20:23:46 +0000131
David Majnemer75c3ebf2016-06-02 17:13:53 +0000132 // Check if we've already translated this subprogram.
133 auto I = TypeIndices.find(SP);
134 if (I != TypeIndices.end())
135 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000136
Reid Kleckner2280f932016-05-23 20:23:46 +0000137 TypeIndex ParentScope = TypeIndex(0);
Reid Klecknerac945e22016-06-17 16:11:20 +0000138 // The display name includes function template arguments. Drop them to match
139 // MSVC.
140 StringRef DisplayName = SP->getDisplayName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000141 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Reid Kleckner2280f932016-05-23 20:23:46 +0000142 TypeIndex TI = TypeTable.writeFuncId(FuncId);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000143
Reid Klecknera8d57402016-06-03 15:58:20 +0000144 recordTypeIndexForDINode(SP, TI);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000145 return TI;
Reid Kleckner2280f932016-05-23 20:23:46 +0000146}
147
Reid Klecknera8d57402016-06-03 15:58:20 +0000148void CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, TypeIndex TI) {
149 auto InsertResult = TypeIndices.insert({Node, TI});
150 (void)InsertResult;
151 assert(InsertResult.second && "DINode was already assigned a type index");
152}
153
Reid Kleckner876330d2016-02-12 21:48:30 +0000154void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
155 const DILocation *InlinedAt) {
156 if (InlinedAt) {
157 // This variable was inlined. Associate it with the InlineSite.
158 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
159 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
160 Site.InlinedLocals.emplace_back(Var);
161 } else {
162 // This variable goes in the main ProcSym.
163 CurFn->Locals.emplace_back(Var);
164 }
165}
166
Reid Kleckner829365a2016-02-11 19:41:47 +0000167static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
168 const DILocation *Loc) {
169 auto B = Locs.begin(), E = Locs.end();
170 if (std::find(B, E, Loc) == E)
171 Locs.push_back(Loc);
172}
173
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000174void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000175 const MachineFunction *MF) {
176 // Skip this instruction if it has the same location as the previous one.
177 if (DL == CurFn->LastLoc)
178 return;
179
180 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000181 if (!Scope)
182 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000183
David Majnemerc3340db2016-01-13 01:05:23 +0000184 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000185 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
186 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
187 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000188 return;
189
Reid Kleckner2214ed82016-01-29 00:49:42 +0000190 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
191 if (CI.getStartColumn() != DL.getCol())
192 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000193
Reid Kleckner2214ed82016-01-29 00:49:42 +0000194 if (!CurFn->HaveLineInfo)
195 CurFn->HaveLineInfo = true;
196 unsigned FileId = 0;
197 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
198 FileId = CurFn->LastFileId;
199 else
200 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
201 CurFn->LastLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000202
203 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000204 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000205 const DILocation *Loc = DL.get();
206
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000207 // If this location was actually inlined from somewhere else, give it the ID
208 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000209 FuncId =
210 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000211
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000212 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000213 bool FirstLoc = true;
214 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000215 InlineSite &Site =
216 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000217 if (!FirstLoc)
218 addLocIfNotPresent(Site.ChildSites, Loc);
219 FirstLoc = false;
220 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000221 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000222 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000223 }
224
Reid Klecknerdac21b42016-02-03 21:15:48 +0000225 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
226 /*PrologueEnd=*/false,
227 /*IsStmt=*/false, DL->getFilename());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000228}
229
Reid Kleckner5d122f82016-05-25 23:16:12 +0000230void CodeViewDebug::emitCodeViewMagicVersion() {
231 OS.EmitValueToAlignment(4);
232 OS.AddComment("Debug section magic");
233 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
234}
235
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000236void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000237 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000238 return;
239
240 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000241
242 // The COFF .debug$S section consists of several subsections, each starting
243 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
244 // of the payload followed by the payload itself. The subsections are 4-byte
245 // aligned.
246
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000247 // Use the generic .debug$S section, and make a subsection for all the inlined
248 // subprograms.
249 switchToDebugSectionForSymbol(nullptr);
Reid Kleckner5d122f82016-05-25 23:16:12 +0000250 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000251
Reid Kleckner2214ed82016-01-29 00:49:42 +0000252 // Emit per-function debug information.
253 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000254 if (!P.first->isDeclarationForLinker())
255 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000256
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000257 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000258 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000259 emitDebugInfoForGlobals();
260
Reid Kleckner5d122f82016-05-25 23:16:12 +0000261 // Switch back to the generic .debug$S section after potentially processing
262 // comdat symbol sections.
263 switchToDebugSectionForSymbol(nullptr);
264
David Majnemer3128b102016-06-15 18:00:01 +0000265 // Emit UDT records for any types used by global variables.
266 if (!GlobalUDTs.empty()) {
267 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
268 emitDebugInfoForUDTs(GlobalUDTs);
269 endCVSubsection(SymbolsEnd);
270 }
271
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000272 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000273 OS.AddComment("File index to string table offset subsection");
274 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000275
276 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000277 OS.AddComment("String table");
278 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000279
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000280 // Emit type information last, so that any types we translate while emitting
281 // function info are included.
282 emitTypeInformation();
283
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000284 clear();
285}
286
David Majnemerb9456a52016-03-14 05:15:09 +0000287static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
288 // Microsoft's linker seems to have trouble with symbol names longer than
289 // 0xffd8 bytes.
290 S = S.substr(0, 0xffd8);
291 SmallString<32> NullTerminatedString(S);
292 NullTerminatedString.push_back('\0');
293 OS.EmitBytes(NullTerminatedString);
294}
295
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000296void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000297 // Do nothing if we have no debug info or if no non-trivial types were emitted
298 // to TypeTable during codegen.
Reid Klecknerfbd77872016-03-18 18:54:32 +0000299 NamedMDNode *CU_Nodes =
300 MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
301 if (!CU_Nodes)
302 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000303 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000304 return;
305
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000306 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000307 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000308 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000309
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000310 SmallString<8> CommentPrefix;
311 if (OS.isVerboseAsm()) {
312 CommentPrefix += '\t';
313 CommentPrefix += Asm->MAI->getCommentString();
314 CommentPrefix += ' ';
315 }
316
317 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
Reid Kleckner2280f932016-05-23 20:23:46 +0000318 TypeTable.ForEachRecord(
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000319 [&](TypeIndex Index, StringRef Record) {
320 if (OS.isVerboseAsm()) {
321 // Emit a block comment describing the type record for readability.
322 SmallString<512> CommentBlock;
323 raw_svector_ostream CommentOS(CommentBlock);
324 ScopedPrinter SP(CommentOS);
325 SP.setPrefix(CommentPrefix);
326 CVTD.setPrinter(&SP);
Zachary Turner01ee3dae2016-06-16 18:22:27 +0000327 Error EC = CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
328 assert(!EC && "produced malformed type record");
329 consumeError(std::move(EC));
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000330 // emitRawComment will insert its own tab and comment string before
331 // the first line, so strip off our first one. It also prints its own
332 // newline.
333 OS.emitRawComment(
334 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
335 }
336 OS.EmitBinaryData(Record);
Reid Kleckner2280f932016-05-23 20:23:46 +0000337 });
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000338}
339
Reid Kleckner5d122f82016-05-25 23:16:12 +0000340void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000341 if (InlinedSubprograms.empty())
342 return;
343
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000344
345 OS.AddComment("Inlinee lines subsection");
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000346 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000347
348 // We don't provide any extra file info.
349 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000350 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000351 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
352
353 for (const DISubprogram *SP : InlinedSubprograms) {
Reid Kleckner2280f932016-05-23 20:23:46 +0000354 assert(TypeIndices.count(SP));
355 TypeIndex InlineeIdx = TypeIndices[SP];
356
David Majnemer30579ec2016-02-02 23:18:23 +0000357 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000358 unsigned FileId = maybeRecordFile(SP->getFile());
359 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
360 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000361 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000362 // The filechecksum table uses 8 byte entries for now, and file ids start at
363 // 1.
364 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000365 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000366 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000367 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000368 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000369 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000370 OS.EmitIntValue(SP->getLine(), 4);
371 }
372
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000373 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000374}
375
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000376void CodeViewDebug::collectInlineSiteChildren(
377 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
378 const InlineSite &Site) {
379 for (const DILocation *ChildSiteLoc : Site.ChildSites) {
380 auto I = FI.InlineSites.find(ChildSiteLoc);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000381 const InlineSite &ChildSite = I->second;
382 Children.push_back(ChildSite.SiteFuncId);
383 collectInlineSiteChildren(Children, FI, ChildSite);
384 }
385}
386
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000387void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
388 const DILocation *InlinedAt,
389 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000390 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
391 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000392
Reid Kleckner2280f932016-05-23 20:23:46 +0000393 assert(TypeIndices.count(Site.Inlinee));
394 TypeIndex InlineeIdx = TypeIndices[Site.Inlinee];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000395
396 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000397 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000398 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000399 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000400 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000401 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000402
Reid Klecknerdac21b42016-02-03 21:15:48 +0000403 OS.AddComment("PtrParent");
404 OS.EmitIntValue(0, 4);
405 OS.AddComment("PtrEnd");
406 OS.EmitIntValue(0, 4);
407 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000408 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000409
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000410 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
411 unsigned StartLineNum = Site.Inlinee->getLine();
412 SmallVector<unsigned, 3> SecondaryFuncIds;
413 collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
414
415 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
David Majnemerc9911f22016-02-02 19:22:34 +0000416 FI.Begin, FI.End, SecondaryFuncIds);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000417
418 OS.EmitLabel(InlineEnd);
419
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000420 for (const LocalVariable &Var : Site.InlinedLocals)
421 emitLocalVariable(Var);
422
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000423 // Recurse on child inlined call sites before closing the scope.
424 for (const DILocation *ChildSite : Site.ChildSites) {
425 auto I = FI.InlineSites.find(ChildSite);
426 assert(I != FI.InlineSites.end() &&
427 "child site not in function inline site map");
428 emitInlinedCallSite(FI, ChildSite, I->second);
429 }
430
431 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000432 OS.AddComment("Record length");
433 OS.EmitIntValue(2, 2); // RecordLength
434 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000435 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000436}
437
Reid Kleckner5d122f82016-05-25 23:16:12 +0000438void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
439 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
440 // comdat key. A section may be comdat because of -ffunction-sections or
441 // because it is comdat in the IR.
442 MCSectionCOFF *GVSec =
443 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
444 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
445
446 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
447 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
448 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
449
450 OS.SwitchSection(DebugSec);
451
452 // Emit the magic version number if this is the first time we've switched to
453 // this section.
454 if (ComdatDebugSections.insert(DebugSec).second)
455 emitCodeViewMagicVersion();
456}
457
Reid Klecknerac945e22016-06-17 16:11:20 +0000458static const DISubprogram *getQualifiedNameComponents(
459 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
460 const DISubprogram *ClosestSubprogram = nullptr;
461 while (Scope != nullptr) {
462 if (ClosestSubprogram == nullptr)
463 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
464 StringRef ScopeName = Scope->getName();
465 if (!ScopeName.empty())
466 QualifiedNameComponents.push_back(ScopeName);
467 Scope = Scope->getScope().resolve();
468 }
469 return ClosestSubprogram;
470}
471
472static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
473 StringRef TypeName) {
474 std::string FullyQualifiedName;
475 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
476 FullyQualifiedName.append(QualifiedNameComponent);
477 FullyQualifiedName.append("::");
478 }
479 FullyQualifiedName.append(TypeName);
480 return FullyQualifiedName;
481}
482
Reid Kleckner2214ed82016-01-29 00:49:42 +0000483void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
484 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000485 // For each function there is a separate subsection
486 // which holds the PC to file:line table.
487 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000488 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000489
Reid Kleckner5d122f82016-05-25 23:16:12 +0000490 // Switch to the to a comdat section, if appropriate.
491 switchToDebugSectionForSymbol(Fn);
492
Reid Klecknerac945e22016-06-17 16:11:20 +0000493 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000494 auto *SP = GV->getSubprogram();
495 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000496
497 // If we have a display name, build the fully qualified name by walking the
498 // chain of scopes.
499 if (SP != nullptr && !SP->getDisplayName().empty()) {
500 SmallVector<StringRef, 5> QualifiedNameComponents;
501 getQualifiedNameComponents(SP->getScope().resolve(),
502 QualifiedNameComponents);
503 FuncName = getQualifiedName(QualifiedNameComponents, SP->getDisplayName());
504 }
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000505
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000506 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000507 if (FuncName.empty())
508 FuncName = GlobalValue::getRealLinkageName(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000509
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000510 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000511 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000512 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000513 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000514 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
515 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000516 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000517 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000518 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000519
Reid Klecknerdac21b42016-02-03 21:15:48 +0000520 OS.AddComment("Record kind: S_GPROC32_ID");
Zachary Turner63a28462016-05-17 23:50:21 +0000521 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000522
David Majnemer30579ec2016-02-02 23:18:23 +0000523 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000524 OS.AddComment("PtrParent");
525 OS.EmitIntValue(0, 4);
526 OS.AddComment("PtrEnd");
527 OS.EmitIntValue(0, 4);
528 OS.AddComment("PtrNext");
529 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000530 // This is the important bit that tells the debugger where the function
531 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000532 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000533 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000534 OS.AddComment("Offset after prologue");
535 OS.EmitIntValue(0, 4);
536 OS.AddComment("Offset before epilogue");
537 OS.EmitIntValue(0, 4);
538 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000539 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000540 OS.AddComment("Function section relative address");
541 OS.EmitCOFFSecRel32(Fn);
542 OS.AddComment("Function section index");
543 OS.EmitCOFFSectionIndex(Fn);
544 OS.AddComment("Flags");
545 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000546 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000547 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000548 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000549 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000550 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000551
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000552 for (const LocalVariable &Var : FI.Locals)
553 emitLocalVariable(Var);
554
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000555 // Emit inlined call site information. Only emit functions inlined directly
556 // into the parent function. We'll emit the other sites recursively as part
557 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000558 for (const DILocation *InlinedAt : FI.ChildSites) {
559 auto I = FI.InlineSites.find(InlinedAt);
560 assert(I != FI.InlineSites.end() &&
561 "child site not in function inline site map");
562 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000563 }
564
David Majnemer3128b102016-06-15 18:00:01 +0000565 if (SP != nullptr)
566 emitDebugInfoForUDTs(LocalUDTs);
567
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000568 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000569 OS.AddComment("Record length");
570 OS.EmitIntValue(0x0002, 2);
571 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000572 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000573 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000574 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000575
Reid Kleckner2214ed82016-01-29 00:49:42 +0000576 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000577 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000578}
579
Reid Kleckner876330d2016-02-12 21:48:30 +0000580CodeViewDebug::LocalVarDefRange
581CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
582 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000583 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000584 DR.DataOffset = Offset;
585 assert(DR.DataOffset == Offset && "truncation");
586 DR.StructOffset = 0;
587 DR.CVRegister = CVRegister;
588 return DR;
589}
590
591CodeViewDebug::LocalVarDefRange
592CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
593 LocalVarDefRange DR;
594 DR.InMemory = 0;
595 DR.DataOffset = 0;
596 DR.StructOffset = 0;
597 DR.CVRegister = CVRegister;
598 return DR;
599}
600
601void CodeViewDebug::collectVariableInfoFromMMITable(
602 DenseSet<InlinedVariable> &Processed) {
603 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
604 const TargetFrameLowering *TFI = TSI.getFrameLowering();
605 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
606
607 for (const MachineModuleInfo::VariableDbgInfo &VI :
608 MMI->getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000609 if (!VI.Var)
610 continue;
611 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
612 "Expected inlined-at fields to agree");
613
Reid Kleckner876330d2016-02-12 21:48:30 +0000614 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000615 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
616
617 // If variable scope is not found then skip this variable.
618 if (!Scope)
619 continue;
620
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000621 // Get the frame register used and the offset.
622 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000623 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
624 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000625
626 // Calculate the label ranges.
Reid Kleckner876330d2016-02-12 21:48:30 +0000627 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000628 for (const InsnRange &Range : Scope->getRanges()) {
629 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
630 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000631 End = End ? End : Asm->getFunctionEnd();
632 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000633 }
634
Reid Kleckner876330d2016-02-12 21:48:30 +0000635 LocalVariable Var;
636 Var.DIVar = VI.Var;
637 Var.DefRanges.emplace_back(std::move(DefRange));
638 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
639 }
640}
641
642void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
643 DenseSet<InlinedVariable> Processed;
644 // Grab the variable info that was squirreled away in the MMI side-table.
645 collectVariableInfoFromMMITable(Processed);
646
647 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
648
649 for (const auto &I : DbgValues) {
650 InlinedVariable IV = I.first;
651 if (Processed.count(IV))
652 continue;
653 const DILocalVariable *DIVar = IV.first;
654 const DILocation *InlinedAt = IV.second;
655
656 // Instruction ranges, specifying where IV is accessible.
657 const auto &Ranges = I.second;
658
659 LexicalScope *Scope = nullptr;
660 if (InlinedAt)
661 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
662 else
663 Scope = LScopes.findLexicalScope(DIVar->getScope());
664 // If variable scope is not found then skip this variable.
665 if (!Scope)
666 continue;
667
668 LocalVariable Var;
669 Var.DIVar = DIVar;
670
671 // Calculate the definition ranges.
672 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
673 const InsnRange &Range = *I;
674 const MachineInstr *DVInst = Range.first;
675 assert(DVInst->isDebugValue() && "Invalid History entry");
676 const DIExpression *DIExpr = DVInst->getDebugExpression();
677
678 // Bail if there is a complex DWARF expression for now.
679 if (DIExpr && DIExpr->getNumElements() > 0)
680 continue;
681
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000682 // Bail if operand 0 is not a valid register. This means the variable is a
683 // simple constant, or is described by a complex expression.
684 // FIXME: Find a way to represent constant variables, since they are
685 // relatively common.
686 unsigned Reg =
687 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
688 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +0000689 continue;
690
Reid Kleckner876330d2016-02-12 21:48:30 +0000691 // Handle the two cases we can handle: indirect in memory and in register.
692 bool IsIndirect = DVInst->getOperand(1).isImm();
693 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
694 {
695 LocalVarDefRange DefRange;
696 if (IsIndirect) {
697 int64_t Offset = DVInst->getOperand(1).getImm();
698 DefRange = createDefRangeMem(CVReg, Offset);
699 } else {
700 DefRange = createDefRangeReg(CVReg);
701 }
702 if (Var.DefRanges.empty() ||
703 Var.DefRanges.back().isDifferentLocation(DefRange)) {
704 Var.DefRanges.emplace_back(std::move(DefRange));
705 }
706 }
707
708 // Compute the label range.
709 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
710 const MCSymbol *End = getLabelAfterInsn(Range.second);
711 if (!End) {
712 if (std::next(I) != E)
713 End = getLabelBeforeInsn(std::next(I)->first);
714 else
715 End = Asm->getFunctionEnd();
716 }
717
718 // If the last range end is our begin, just extend the last range.
719 // Otherwise make a new range.
720 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
721 Var.DefRanges.back().Ranges;
722 if (!Ranges.empty() && Ranges.back().second == Begin)
723 Ranges.back().second = End;
724 else
725 Ranges.emplace_back(Begin, End);
726
727 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000728 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000729
730 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000731 }
732}
733
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000734void CodeViewDebug::beginFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000735 assert(!CurFn && "Can't process two functions at once!");
736
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000737 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000738 return;
739
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000740 DebugHandlerBase::beginFunction(MF);
741
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000742 const Function *GV = MF->getFunction();
743 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000744 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +0000745 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000746 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000747
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000748 // Find the end of the function prolog. First known non-DBG_VALUE and
749 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000750 // FIXME: is there a simpler a way to do this? Can we just search
751 // for the first instruction of the function, not the last of the prolog?
752 DebugLoc PrologEndLoc;
753 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000754 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000755 for (const auto &MI : MBB) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000756 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
757 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000758 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000759 break;
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000760 } else if (!MI.isDebugValue()) {
761 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000762 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000763 }
764 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000765
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000766 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000767 if (PrologEndLoc && !EmptyPrologue) {
768 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000769 maybeRecordLocation(FnStartDL, MF);
770 }
771}
772
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000773TypeIndex CodeViewDebug::lowerType(const DIType *Ty) {
774 // Generic dispatch for lowering an unknown type.
775 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +0000776 case dwarf::DW_TAG_array_type:
777 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +0000778 case dwarf::DW_TAG_typedef:
779 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000780 case dwarf::DW_TAG_base_type:
781 return lowerTypeBasic(cast<DIBasicType>(Ty));
782 case dwarf::DW_TAG_pointer_type:
783 case dwarf::DW_TAG_reference_type:
784 case dwarf::DW_TAG_rvalue_reference_type:
785 return lowerTypePointer(cast<DIDerivedType>(Ty));
786 case dwarf::DW_TAG_ptr_to_member_type:
787 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
788 case dwarf::DW_TAG_const_type:
789 case dwarf::DW_TAG_volatile_type:
790 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +0000791 case dwarf::DW_TAG_subroutine_type:
792 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +0000793 case dwarf::DW_TAG_enumeration_type:
794 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +0000795 case dwarf::DW_TAG_class_type:
796 case dwarf::DW_TAG_structure_type:
797 return lowerTypeClass(cast<DICompositeType>(Ty));
798 case dwarf::DW_TAG_union_type:
799 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000800 default:
801 // Use the null type index.
802 return TypeIndex();
803 }
804}
805
David Majnemerd065e232016-06-02 06:21:37 +0000806TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +0000807 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
808 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +0000809 StringRef TypeName = Ty->getName();
810
811 SmallVector<StringRef, 5> QualifiedNameComponents;
812 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
813 Ty->getScope().resolve(), QualifiedNameComponents);
814
815 if (ClosestSubprogram == nullptr) {
816 std::string FullyQualifiedName =
817 getQualifiedName(QualifiedNameComponents, TypeName);
818 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), UnderlyingTypeIndex);
819 } else if (ClosestSubprogram == CurrentSubprogram) {
820 std::string FullyQualifiedName =
821 getQualifiedName(QualifiedNameComponents, TypeName);
822 LocalUDTs.emplace_back(std::move(FullyQualifiedName), UnderlyingTypeIndex);
823 }
824 // TODO: What if the ClosestSubprogram is neither null or the current
825 // subprogram? Currently, the UDT just gets dropped on the floor.
826 //
827 // The current behavior is not desirable. To get maximal fidelity, we would
828 // need to perform all type translation before beginning emission of .debug$S
829 // and then make LocalUDTs a member of FunctionInfo
830
David Majnemerd065e232016-06-02 06:21:37 +0000831 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +0000832 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +0000833 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +0000834 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +0000835 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +0000836 return TypeIndex(SimpleTypeKind::WideCharacter);
David Majnemerd065e232016-06-02 06:21:37 +0000837 return UnderlyingTypeIndex;
838}
839
Adrian McCarthyf3c3c132016-06-08 18:22:59 +0000840TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
841 DITypeRef ElementTypeRef = Ty->getBaseType();
842 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
843 // IndexType is size_t, which depends on the bitness of the target.
844 TypeIndex IndexType = Asm->MAI->getPointerSize() == 8
845 ? TypeIndex(SimpleTypeKind::UInt64Quad)
846 : TypeIndex(SimpleTypeKind::UInt32Long);
847 uint64_t Size = Ty->getSizeInBits() / 8;
848 ArrayRecord Record(ElementTypeIndex, IndexType, Size, Ty->getName());
849 return TypeTable.writeArray(Record);
850}
851
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000852TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
853 TypeIndex Index;
854 dwarf::TypeKind Kind;
855 uint32_t ByteSize;
856
857 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +0000858 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000859
860 SimpleTypeKind STK = SimpleTypeKind::None;
861 switch (Kind) {
862 case dwarf::DW_ATE_address:
863 // FIXME: Translate
864 break;
865 case dwarf::DW_ATE_boolean:
866 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000867 case 1: STK = SimpleTypeKind::Boolean8; break;
868 case 2: STK = SimpleTypeKind::Boolean16; break;
869 case 4: STK = SimpleTypeKind::Boolean32; break;
870 case 8: STK = SimpleTypeKind::Boolean64; break;
871 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000872 }
873 break;
874 case dwarf::DW_ATE_complex_float:
875 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000876 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000877 case 4: STK = SimpleTypeKind::Complex32; break;
878 case 8: STK = SimpleTypeKind::Complex64; break;
879 case 10: STK = SimpleTypeKind::Complex80; break;
880 case 16: STK = SimpleTypeKind::Complex128; break;
881 }
882 break;
883 case dwarf::DW_ATE_float:
884 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000885 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000886 case 4: STK = SimpleTypeKind::Float32; break;
887 case 6: STK = SimpleTypeKind::Float48; break;
888 case 8: STK = SimpleTypeKind::Float64; break;
889 case 10: STK = SimpleTypeKind::Float80; break;
890 case 16: STK = SimpleTypeKind::Float128; break;
891 }
892 break;
893 case dwarf::DW_ATE_signed:
894 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000895 case 1: STK = SimpleTypeKind::SByte; break;
896 case 2: STK = SimpleTypeKind::Int16Short; break;
897 case 4: STK = SimpleTypeKind::Int32; break;
898 case 8: STK = SimpleTypeKind::Int64Quad; break;
899 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000900 }
901 break;
902 case dwarf::DW_ATE_unsigned:
903 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000904 case 1: STK = SimpleTypeKind::Byte; break;
905 case 2: STK = SimpleTypeKind::UInt16Short; break;
906 case 4: STK = SimpleTypeKind::UInt32; break;
907 case 8: STK = SimpleTypeKind::UInt64Quad; break;
908 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000909 }
910 break;
911 case dwarf::DW_ATE_UTF:
912 switch (ByteSize) {
913 case 2: STK = SimpleTypeKind::Character16; break;
914 case 4: STK = SimpleTypeKind::Character32; break;
915 }
916 break;
917 case dwarf::DW_ATE_signed_char:
918 if (ByteSize == 1)
919 STK = SimpleTypeKind::SignedCharacter;
920 break;
921 case dwarf::DW_ATE_unsigned_char:
922 if (ByteSize == 1)
923 STK = SimpleTypeKind::UnsignedCharacter;
924 break;
925 default:
926 break;
927 }
928
929 // Apply some fixups based on the source-level type name.
930 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
931 STK = SimpleTypeKind::Int32Long;
932 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
933 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +0000934 if (STK == SimpleTypeKind::UInt16Short &&
935 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000936 STK = SimpleTypeKind::WideCharacter;
937 if ((STK == SimpleTypeKind::SignedCharacter ||
938 STK == SimpleTypeKind::UnsignedCharacter) &&
939 Ty->getName() == "char")
940 STK = SimpleTypeKind::NarrowCharacter;
941
942 return TypeIndex(STK);
943}
944
945TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
946 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
947
948 // Pointers to simple types can use SimpleTypeMode, rather than having a
949 // dedicated pointer type record.
950 if (PointeeTI.isSimple() &&
951 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
952 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
953 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
954 ? SimpleTypeMode::NearPointer64
955 : SimpleTypeMode::NearPointer32;
956 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
957 }
958
959 PointerKind PK =
960 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
961 PointerMode PM = PointerMode::Pointer;
962 switch (Ty->getTag()) {
963 default: llvm_unreachable("not a pointer tag type");
964 case dwarf::DW_TAG_pointer_type:
965 PM = PointerMode::Pointer;
966 break;
967 case dwarf::DW_TAG_reference_type:
968 PM = PointerMode::LValueReference;
969 break;
970 case dwarf::DW_TAG_rvalue_reference_type:
971 PM = PointerMode::RValueReference;
972 break;
973 }
974 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
975 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
976 // do.
977 PointerOptions PO = PointerOptions::None;
978 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
979 return TypeTable.writePointer(PR);
980}
981
Reid Kleckner604105b2016-06-17 21:31:33 +0000982static PointerToMemberRepresentation translatePtrToMemberRep(bool IsPMF,
983 unsigned Flags) {
984 if (IsPMF) {
985 switch (Flags & DINode::FlagPtrToMemberRep) {
986 case 0:
987 return PointerToMemberRepresentation::GeneralFunction;
988 case DINode::FlagSingleInheritance:
989 return PointerToMemberRepresentation::SingleInheritanceFunction;
990 case DINode::FlagMultipleInheritance:
991 return PointerToMemberRepresentation::MultipleInheritanceFunction;
992 case DINode::FlagVirtualInheritance:
993 return PointerToMemberRepresentation::VirtualInheritanceFunction;
994 }
995 } else {
996 switch (Flags & DINode::FlagPtrToMemberRep) {
997 case 0:
998 return PointerToMemberRepresentation::GeneralData;
999 case DINode::FlagSingleInheritance:
1000 return PointerToMemberRepresentation::SingleInheritanceData;
1001 case DINode::FlagMultipleInheritance:
1002 return PointerToMemberRepresentation::MultipleInheritanceData;
1003 case DINode::FlagVirtualInheritance:
1004 return PointerToMemberRepresentation::VirtualInheritanceData;
1005 }
1006 }
1007 llvm_unreachable("invalid ptr to member representation");
1008}
1009
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001010TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1011 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1012 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1013 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1014 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
1015 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001016 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1017 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1018 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001019 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner604105b2016-06-17 21:31:33 +00001020 MemberPointerInfo MPI(ClassTI,
1021 translatePtrToMemberRep(IsPMF, Ty->getFlags()));
1022 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1023 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001024 return TypeTable.writePointer(PR);
1025}
1026
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001027/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1028/// have a translation, use the NearC convention.
1029static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1030 switch (DwarfCC) {
1031 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1032 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1033 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1034 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1035 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1036 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1037 }
1038 return CallingConvention::NearC;
1039}
1040
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001041TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1042 ModifierOptions Mods = ModifierOptions::None;
1043 bool IsModifier = true;
1044 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001045 while (IsModifier && BaseTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001046 // FIXME: Need to add DWARF tag for __unaligned.
1047 switch (BaseTy->getTag()) {
1048 case dwarf::DW_TAG_const_type:
1049 Mods |= ModifierOptions::Const;
1050 break;
1051 case dwarf::DW_TAG_volatile_type:
1052 Mods |= ModifierOptions::Volatile;
1053 break;
1054 default:
1055 IsModifier = false;
1056 break;
1057 }
1058 if (IsModifier)
1059 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1060 }
1061 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
1062 ModifierRecord MR(ModifiedTI, Mods);
1063 return TypeTable.writeModifier(MR);
1064}
1065
David Majnemer75c3ebf2016-06-02 17:13:53 +00001066TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1067 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1068 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1069 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1070
1071 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1072 ArrayRef<TypeIndex> ArgTypeIndices = None;
1073 if (!ReturnAndArgTypeIndices.empty()) {
1074 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1075 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1076 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1077 }
1078
1079 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1080 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
1081
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001082 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1083
David Majnemer75c3ebf2016-06-02 17:13:53 +00001084 // TODO: Some functions are member functions, we should use a more appropriate
1085 // record for those.
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001086 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1087 ArgTypeIndices.size(), ArgListIndex);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001088 return TypeTable.writeProcedure(Procedure);
1089}
1090
Reid Klecknera8d57402016-06-03 15:58:20 +00001091static MemberAccess translateAccessFlags(unsigned RecordTag,
1092 const DIType *Member) {
1093 switch (Member->getFlags() & DINode::FlagAccessibility) {
1094 case DINode::FlagPrivate: return MemberAccess::Private;
1095 case DINode::FlagPublic: return MemberAccess::Public;
1096 case DINode::FlagProtected: return MemberAccess::Protected;
1097 case 0:
1098 // If there was no explicit access control, provide the default for the tag.
1099 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1100 : MemberAccess::Public;
1101 }
1102 llvm_unreachable("access flags are exclusive");
1103}
1104
1105static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1106 switch (Ty->getTag()) {
1107 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1108 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1109 }
1110 llvm_unreachable("unexpected tag");
1111}
1112
1113/// Return the HasUniqueName option if it should be present in ClassOptions, or
1114/// None otherwise.
1115static ClassOptions getRecordUniqueNameOption(const DICompositeType *Ty) {
1116 // MSVC always sets this flag now, even for local types. Clang doesn't always
1117 // appear to give every type a linkage name, which may be problematic for us.
1118 // FIXME: Investigate the consequences of not following them here.
1119 return !Ty->getIdentifier().empty() ? ClassOptions::HasUniqueName
1120 : ClassOptions::None;
1121}
1122
David Majnemer979cb882016-06-16 21:32:16 +00001123TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
1124 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1125 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001126 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001127
David Majnemerda9548f2016-06-17 16:13:21 +00001128 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001129 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001130 } else {
1131 FieldListRecordBuilder Fields;
1132 for (const DINode *Element : Ty->getElements()) {
1133 // We assume that the frontend provides all members in source declaration
1134 // order, which is what MSVC does.
1135 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
1136 Fields.writeEnumerator(EnumeratorRecord(
1137 MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()),
1138 Enumerator->getName()));
1139 EnumeratorCount++;
1140 }
1141 }
1142 FTI = TypeTable.writeFieldList(Fields);
1143 }
David Majnemer979cb882016-06-16 21:32:16 +00001144
David Majnemerda9548f2016-06-17 16:13:21 +00001145 return TypeTable.writeEnum(EnumRecord(EnumeratorCount, CO, FTI, Ty->getName(),
David Majnemer979cb882016-06-16 21:32:16 +00001146 Ty->getIdentifier(),
1147 getTypeIndex(Ty->getBaseType())));
1148}
1149
Reid Klecknera8d57402016-06-03 15:58:20 +00001150TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1151 // First, construct the forward decl. Don't look into Ty to compute the
1152 // forward decl options, since it might not be available in all TUs.
1153 TypeRecordKind Kind = getRecordKind(Ty);
1154 ClassOptions CO =
1155 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
1156 TypeIndex FwdDeclTI = TypeTable.writeClass(ClassRecord(
1157 Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(),
1158 TypeIndex(), TypeIndex(), 0, Ty->getName(), Ty->getIdentifier()));
1159 return FwdDeclTI;
1160}
1161
1162TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1163 // Construct the field list and complete type record.
1164 TypeRecordKind Kind = getRecordKind(Ty);
1165 // FIXME: Other ClassOptions, like ContainsNestedClass and NestedClass.
1166 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1167 TypeIndex FTI;
1168 unsigned FieldCount;
1169 std::tie(FTI, FieldCount) = lowerRecordFieldList(Ty);
1170
1171 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1172 return TypeTable.writeClass(ClassRecord(Kind, FieldCount, CO, HfaKind::None,
1173 WindowsRTClassKind::None, FTI,
1174 TypeIndex(), TypeIndex(), SizeInBytes,
1175 Ty->getName(), Ty->getIdentifier()));
1176 // FIXME: Make an LF_UDT_SRC_LINE record.
1177}
1178
1179TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1180 ClassOptions CO =
1181 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
1182 TypeIndex FwdDeclTI =
1183 TypeTable.writeUnion(UnionRecord(0, CO, HfaKind::None, TypeIndex(), 0,
1184 Ty->getName(), Ty->getIdentifier()));
1185 return FwdDeclTI;
1186}
1187
1188TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
1189 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1190 TypeIndex FTI;
1191 unsigned FieldCount;
1192 std::tie(FTI, FieldCount) = lowerRecordFieldList(Ty);
1193 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1194 return TypeTable.writeUnion(UnionRecord(FieldCount, CO, HfaKind::None, FTI,
1195 SizeInBytes, Ty->getName(),
1196 Ty->getIdentifier()));
1197 // FIXME: Make an LF_UDT_SRC_LINE record.
1198}
1199
1200std::pair<TypeIndex, unsigned>
1201CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1202 // Manually count members. MSVC appears to count everything that generates a
1203 // field list record. Each individual overload in a method overload group
1204 // contributes to this count, even though the overload group is a single field
1205 // list record.
1206 unsigned MemberCount = 0;
1207 FieldListRecordBuilder Fields;
1208 for (const DINode *Element : Ty->getElements()) {
1209 // We assume that the frontend provides all members in source declaration
1210 // order, which is what MSVC does.
1211 if (!Element)
1212 continue;
1213 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
1214 // C++ method.
1215 // FIXME: Overloaded methods are grouped together, so we'll need two
1216 // passes to group them.
1217 (void)SP;
1218 } else if (auto *Member = dyn_cast<DIDerivedType>(Element)) {
1219 if (Member->getTag() == dwarf::DW_TAG_member) {
1220 if (Member->isStaticMember()) {
1221 // Static data member.
1222 Fields.writeStaticDataMember(StaticDataMemberRecord(
1223 translateAccessFlags(Ty->getTag(), Member),
1224 getTypeIndex(Member->getBaseType()), Member->getName()));
1225 MemberCount++;
1226 } else {
1227 // Data member.
1228 // FIXME: Make a BitFieldRecord for bitfields.
1229 Fields.writeDataMember(DataMemberRecord(
1230 translateAccessFlags(Ty->getTag(), Member),
1231 getTypeIndex(Member->getBaseType()),
1232 Member->getOffsetInBits() / 8, Member->getName()));
1233 MemberCount++;
1234 }
1235 } else if (Member->getTag() == dwarf::DW_TAG_friend) {
1236 // Ignore friend members. It appears that MSVC emitted info about
1237 // friends in the past, but modern versions do not.
1238 }
1239 // FIXME: Get clang to emit nested types here and do something with
1240 // them.
1241 }
1242 // Skip other unrecognized kinds of elements.
1243 }
1244 return {TypeTable.writeFieldList(Fields), MemberCount};
1245}
1246
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001247TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef) {
1248 const DIType *Ty = TypeRef.resolve();
1249
1250 // The null DIType is the void type. Don't try to hash it.
1251 if (!Ty)
1252 return TypeIndex::Void();
1253
Reid Klecknera8d57402016-06-03 15:58:20 +00001254 // Check if we've already translated this type. Don't try to do a
1255 // get-or-create style insertion that caches the hash lookup across the
1256 // lowerType call. It will update the TypeIndices map.
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001257 auto I = TypeIndices.find(Ty);
1258 if (I != TypeIndices.end())
1259 return I->second;
1260
1261 TypeIndex TI = lowerType(Ty);
1262
Reid Klecknera8d57402016-06-03 15:58:20 +00001263 recordTypeIndexForDINode(Ty, TI);
1264 return TI;
1265}
1266
1267TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1268 const DIType *Ty = TypeRef.resolve();
1269
1270 // The null DIType is the void type. Don't try to hash it.
1271 if (!Ty)
1272 return TypeIndex::Void();
1273
1274 // If this is a non-record type, the complete type index is the same as the
1275 // normal type index. Just call getTypeIndex.
1276 switch (Ty->getTag()) {
1277 case dwarf::DW_TAG_class_type:
1278 case dwarf::DW_TAG_structure_type:
1279 case dwarf::DW_TAG_union_type:
1280 break;
1281 default:
1282 return getTypeIndex(Ty);
1283 }
1284
1285 // Check if we've already translated the complete record type. Lowering a
1286 // complete type should never trigger lowering another complete type, so we
1287 // can reuse the hash table lookup result.
1288 const auto *CTy = cast<DICompositeType>(Ty);
1289 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1290 if (!InsertResult.second)
1291 return InsertResult.first->second;
1292
1293 // Make sure the forward declaration is emitted first. It's unclear if this
1294 // is necessary, but MSVC does it, and we should follow suit until we can show
1295 // otherwise.
1296 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1297
1298 // Just use the forward decl if we don't have complete type info. This might
1299 // happen if the frontend is using modules and expects the complete definition
1300 // to be emitted elsewhere.
1301 if (CTy->isForwardDecl())
1302 return FwdDeclTI;
1303
1304 TypeIndex TI;
1305 switch (CTy->getTag()) {
1306 case dwarf::DW_TAG_class_type:
1307 case dwarf::DW_TAG_structure_type:
1308 TI = lowerCompleteTypeClass(CTy);
1309 break;
1310 case dwarf::DW_TAG_union_type:
1311 TI = lowerCompleteTypeUnion(CTy);
1312 break;
1313 default:
1314 llvm_unreachable("not a record");
1315 }
1316
1317 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001318 return TI;
1319}
1320
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001321void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
1322 // LocalSym record, see SymbolRecord.h for more info.
1323 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
1324 *LocalEnd = MMI->getContext().createTempSymbol();
1325 OS.AddComment("Record length");
1326 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
1327 OS.EmitLabel(LocalBegin);
1328
1329 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00001330 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001331
Zachary Turner63a28462016-05-17 23:50:21 +00001332 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001333 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00001334 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00001335 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00001336 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001337
1338 OS.AddComment("TypeIndex");
Reid Klecknera8d57402016-06-03 15:58:20 +00001339 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001340 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001341 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00001342 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00001343 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00001344 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001345 OS.EmitLabel(LocalEnd);
1346
Reid Kleckner876330d2016-02-12 21:48:30 +00001347 // Calculate the on disk prefix of the appropriate def range record. The
1348 // records and on disk formats are described in SymbolRecords.h. BytePrefix
1349 // should be big enough to hold all forms without memory allocation.
1350 SmallString<20> BytePrefix;
1351 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
1352 BytePrefix.clear();
1353 // FIXME: Handle bitpieces.
1354 if (DefRange.StructOffset != 0)
1355 continue;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001356
Reid Kleckner876330d2016-02-12 21:48:30 +00001357 if (DefRange.InMemory) {
Zachary Turnera78ecd12016-05-23 18:49:06 +00001358 DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
1359 0, 0, ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001360 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00001361 BytePrefix +=
1362 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001363 BytePrefix +=
1364 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1365 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001366 } else {
1367 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Zachary Turnera78ecd12016-05-23 18:49:06 +00001368 // Unclear what matters here.
1369 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
1370 ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001371 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
Reid Kleckner876330d2016-02-12 21:48:30 +00001372 BytePrefix +=
1373 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001374 BytePrefix +=
1375 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1376 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001377 }
1378 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
1379 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001380}
1381
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001382void CodeViewDebug::endFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001383 if (!Asm || !CurFn) // We haven't created any debug info for this function.
1384 return;
1385
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001386 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00001387 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001388 assert(CurFn == &FnDebugInfo[GV]);
1389
Pete Cooperadebb932016-03-11 02:14:16 +00001390 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00001391
1392 DebugHandlerBase::endFunction(MF);
1393
Reid Kleckner2214ed82016-01-29 00:49:42 +00001394 // Don't emit anything if we don't have any line tables.
1395 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001396 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001397 CurFn = nullptr;
1398 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00001399 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001400
1401 CurFn->End = Asm->getFunctionEnd();
1402
Craig Topper353eda42014-04-24 06:44:33 +00001403 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001404}
1405
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001406void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001407 DebugHandlerBase::beginInstruction(MI);
1408
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001409 // Ignore DBG_VALUE locations and function prologue.
1410 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
1411 return;
1412 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001413 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001414 return;
1415 maybeRecordLocation(DL, Asm->MF);
1416}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001417
1418MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
1419 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
1420 *EndLabel = MMI->getContext().createTempSymbol();
1421 OS.EmitIntValue(unsigned(Kind), 4);
1422 OS.AddComment("Subsection size");
1423 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
1424 OS.EmitLabel(BeginLabel);
1425 return EndLabel;
1426}
1427
1428void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
1429 OS.EmitLabel(EndLabel);
1430 // Every subsection must be aligned to a 4-byte boundary.
1431 OS.EmitValueToAlignment(4);
1432}
1433
David Majnemer3128b102016-06-15 18:00:01 +00001434void CodeViewDebug::emitDebugInfoForUDTs(
1435 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
1436 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
1437 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
1438 *UDTRecordEnd = MMI->getContext().createTempSymbol();
1439 OS.AddComment("Record length");
1440 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
1441 OS.EmitLabel(UDTRecordBegin);
1442
1443 OS.AddComment("Record kind: S_UDT");
1444 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
1445
1446 OS.AddComment("Type");
1447 OS.EmitIntValue(UDT.second.getIndex(), 4);
1448
1449 emitNullTerminatedSymbolName(OS, UDT.first);
1450 OS.EmitLabel(UDTRecordEnd);
1451 }
1452}
1453
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001454void CodeViewDebug::emitDebugInfoForGlobals() {
1455 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
1456 for (const MDNode *Node : CUs->operands()) {
1457 const auto *CU = cast<DICompileUnit>(Node);
1458
1459 // First, emit all globals that are not in a comdat in a single symbol
1460 // substream. MSVC doesn't like it if the substream is empty, so only open
1461 // it if we have at least one global to emit.
1462 switchToDebugSectionForSymbol(nullptr);
1463 MCSymbol *EndLabel = nullptr;
1464 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Reid Kleckner6d1d2752016-06-09 00:29:00 +00001465 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
David Majnemer577be0f2016-06-15 00:19:52 +00001466 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001467 if (!EndLabel) {
1468 OS.AddComment("Symbol subsection for globals");
1469 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
1470 }
1471 emitDebugInfoForGlobal(G, Asm->getSymbol(GV));
1472 }
Reid Kleckner6d1d2752016-06-09 00:29:00 +00001473 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001474 }
1475 if (EndLabel)
1476 endCVSubsection(EndLabel);
1477
1478 // Second, emit each global that is in a comdat into its own .debug$S
1479 // section along with its own symbol substream.
1480 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Reid Kleckner6d1d2752016-06-09 00:29:00 +00001481 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001482 if (GV->hasComdat()) {
1483 MCSymbol *GVSym = Asm->getSymbol(GV);
1484 OS.AddComment("Symbol subsection for " +
1485 Twine(GlobalValue::getRealLinkageName(GV->getName())));
1486 switchToDebugSectionForSymbol(GVSym);
1487 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
1488 emitDebugInfoForGlobal(G, GVSym);
1489 endCVSubsection(EndLabel);
1490 }
1491 }
1492 }
1493 }
1494}
1495
1496void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
1497 MCSymbol *GVSym) {
1498 // DataSym record, see SymbolRecord.h for more info.
1499 // FIXME: Thread local data, etc
1500 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
1501 *DataEnd = MMI->getContext().createTempSymbol();
1502 OS.AddComment("Record length");
1503 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
1504 OS.EmitLabel(DataBegin);
1505 OS.AddComment("Record kind: S_GDATA32");
1506 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
1507 OS.AddComment("Type");
1508 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
1509 OS.AddComment("DataOffset");
1510 OS.EmitCOFFSecRel32(GVSym);
1511 OS.AddComment("Segment");
1512 OS.EmitCOFFSectionIndex(GVSym);
1513 OS.AddComment("Name");
1514 emitNullTerminatedSymbolName(OS, DIGV->getName());
1515 OS.EmitLabel(DataEnd);
1516}