blob: 481772944b426b5b0beb8dc067327aca176ccdc1 [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 Kleckner2214ed82016-01-29 00:49:42 +000016#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000017#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000018#include "llvm/DebugInfo/CodeView/TypeIndex.h"
19#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000020#include "llvm/MC/MCExpr.h"
21#include "llvm/MC/MCSymbol.h"
22#include "llvm/Support/COFF.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000023#include "llvm/Target/TargetSubtargetInfo.h"
24#include "llvm/Target/TargetRegisterInfo.h"
25#include "llvm/Target/TargetFrameLowering.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000026
Reid Klecknerf9c275f2016-02-10 20:55:49 +000027using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000028using namespace llvm::codeview;
29
Reid Klecknerf9c275f2016-02-10 20:55:49 +000030CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
31 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
32 // If module doesn't have named metadata anchors or COFF debug section
33 // is not available, skip any debug info related stuff.
34 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
35 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
36 Asm = nullptr;
37 return;
38 }
39
40 // Tell MMI that we have debug info.
41 MMI->setDebugInfoAvailability(true);
42}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000043
Reid Kleckner9533af42016-01-16 00:09:09 +000044StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
45 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000046 if (!Filepath.empty())
47 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000048
Reid Kleckner9533af42016-01-16 00:09:09 +000049 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
50
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000051 // Clang emits directory and relative filename info into the IR, but CodeView
52 // operates on full paths. We could change Clang to emit full paths too, but
53 // that would increase the IR size and probably not needed for other users.
54 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000055 if (Filename.find(':') == 1)
56 Filepath = Filename;
57 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +000058 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000059
60 // Canonicalize the path. We have to do it textually because we may no longer
61 // have access the file in the filesystem.
62 // First, replace all slashes with backslashes.
63 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
64
65 // Remove all "\.\" with "\".
66 size_t Cursor = 0;
67 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
68 Filepath.erase(Cursor, 2);
69
70 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
71 // path should be well-formatted, e.g. start with a drive letter, etc.
72 Cursor = 0;
73 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
74 // Something's wrong if the path starts with "\..\", abort.
75 if (Cursor == 0)
76 break;
77
78 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
79 if (PrevSlash == std::string::npos)
80 // Something's wrong, abort.
81 break;
82
83 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
84 // The next ".." might be following the one we've just erased.
85 Cursor = PrevSlash;
86 }
87
88 // Remove all duplicate backslashes.
89 Cursor = 0;
90 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
91 Filepath.erase(Cursor, 1);
92
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000093 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000094}
95
Reid Kleckner2214ed82016-01-29 00:49:42 +000096unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
97 unsigned NextId = FileIdMap.size() + 1;
98 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
99 if (Insertion.second) {
100 // We have to compute the full filepath and emit a .cv_file directive.
101 StringRef FullPath = getFullFilepath(F);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000102 NextId = OS.EmitCVFileDirective(NextId, FullPath);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000103 assert(NextId == FileIdMap.size() && ".cv_file directive failed");
104 }
105 return Insertion.first->second;
106}
107
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000108CodeViewDebug::InlineSite &CodeViewDebug::getInlineSite(const DILocation *Loc) {
109 const DILocation *InlinedAt = Loc->getInlinedAt();
110 auto Insertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000111 InlineSite *Site = &Insertion.first->second;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000112 if (Insertion.second) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000113 Site->SiteFuncId = NextFuncId++;
114 Site->Inlinee = Loc->getScope()->getSubprogram();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000115 InlinedSubprograms.insert(Loc->getScope()->getSubprogram());
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000116 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000117 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000118}
119
Reid Kleckner829365a2016-02-11 19:41:47 +0000120static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
121 const DILocation *Loc) {
122 auto B = Locs.begin(), E = Locs.end();
123 if (std::find(B, E, Loc) == E)
124 Locs.push_back(Loc);
125}
126
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000127void CodeViewDebug::maybeRecordLocation(DebugLoc DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000128 const MachineFunction *MF) {
129 // Skip this instruction if it has the same location as the previous one.
130 if (DL == CurFn->LastLoc)
131 return;
132
133 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000134 if (!Scope)
135 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000136
David Majnemerc3340db2016-01-13 01:05:23 +0000137 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000138 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
139 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
140 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000141 return;
142
Reid Kleckner2214ed82016-01-29 00:49:42 +0000143 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
144 if (CI.getStartColumn() != DL.getCol())
145 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000146
Reid Kleckner2214ed82016-01-29 00:49:42 +0000147 if (!CurFn->HaveLineInfo)
148 CurFn->HaveLineInfo = true;
149 unsigned FileId = 0;
150 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
151 FileId = CurFn->LastFileId;
152 else
153 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
154 CurFn->LastLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000155
156 unsigned FuncId = CurFn->FuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000157 if (DL->getInlinedAt()) {
158 const DILocation *Loc = DL.get();
159
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000160 // If this location was actually inlined from somewhere else, give it the ID
161 // of the inline call site.
Reid Kleckner829365a2016-02-11 19:41:47 +0000162 FuncId = getInlineSite(Loc).SiteFuncId;
163
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000164 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000165 const DILocation *SiteLoc;
166 bool FirstLoc = true;
167 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000168 InlineSite &Site = getInlineSite(Loc);
Reid Kleckner829365a2016-02-11 19:41:47 +0000169 if (!FirstLoc)
170 addLocIfNotPresent(Site.ChildSites, Loc);
171 FirstLoc = false;
172 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000173 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000174 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000175 }
176
Reid Klecknerdac21b42016-02-03 21:15:48 +0000177 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
178 /*PrologueEnd=*/false,
179 /*IsStmt=*/false, DL->getFilename());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000180}
181
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000182void CodeViewDebug::endModule() {
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000183 if (FnDebugInfo.empty())
184 return;
185
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000186 emitTypeInformation();
187
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000188 // FIXME: For functions that are comdat, we should emit separate .debug$S
189 // sections that are comdat associative with the main function instead of
190 // having one big .debug$S section.
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000191 assert(Asm != nullptr);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000192 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
193 OS.AddComment("Debug section magic");
194 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000195
196 // The COFF .debug$S section consists of several subsections, each starting
197 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
198 // of the payload followed by the payload itself. The subsections are 4-byte
199 // aligned.
200
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000201 // Make a subsection for all the inlined subprograms.
202 emitInlineeLinesSubsection();
203
Reid Kleckner2214ed82016-01-29 00:49:42 +0000204 // Emit per-function debug information.
205 for (auto &P : FnDebugInfo)
206 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000207
208 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000209 OS.AddComment("File index to string table offset subsection");
210 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000211
212 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000213 OS.AddComment("String table");
214 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000215
216 clear();
217}
218
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000219void CodeViewDebug::emitTypeInformation() {
220 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000221 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
222 OS.AddComment("Debug section magic");
223 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000224
225 NamedMDNode *CU_Nodes =
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000226 MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000227 if (!CU_Nodes)
228 return;
229
230 // This type info currently only holds function ids for use with inline call
231 // frame info. All functions are assigned a simple 'void ()' type. Emit that
232 // type here.
233 TypeIndex ArgListIdx = getNextTypeIndex();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000234 OS.AddComment("Type record length");
235 OS.EmitIntValue(2 + sizeof(ArgList), 2);
236 OS.AddComment("Leaf type: LF_ARGLIST");
237 OS.EmitIntValue(LF_ARGLIST, 2);
238 OS.AddComment("Number of arguments");
239 OS.EmitIntValue(0, 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000240
241 TypeIndex VoidProcIdx = getNextTypeIndex();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000242 OS.AddComment("Type record length");
243 OS.EmitIntValue(2 + sizeof(ProcedureType), 2);
244 OS.AddComment("Leaf type: LF_PROCEDURE");
245 OS.EmitIntValue(LF_PROCEDURE, 2);
246 OS.AddComment("Return type index");
247 OS.EmitIntValue(TypeIndex::Void().getIndex(), 4);
248 OS.AddComment("Calling convention");
249 OS.EmitIntValue(char(CallingConvention::NearC), 1);
250 OS.AddComment("Function options");
251 OS.EmitIntValue(char(FunctionOptions::None), 1);
252 OS.AddComment("# of parameters");
253 OS.EmitIntValue(0, 2);
254 OS.AddComment("Argument list type index");
255 OS.EmitIntValue(ArgListIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000256
257 for (MDNode *N : CU_Nodes->operands()) {
258 auto *CUNode = cast<DICompileUnit>(N);
259 for (auto *SP : CUNode->getSubprograms()) {
260 StringRef DisplayName = SP->getDisplayName();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000261 OS.AddComment("Type record length");
262 OS.EmitIntValue(2 + sizeof(FuncId) + DisplayName.size() + 1, 2);
263 OS.AddComment("Leaf type: LF_FUNC_ID");
264 OS.EmitIntValue(LF_FUNC_ID, 2);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000265
Reid Klecknerdac21b42016-02-03 21:15:48 +0000266 OS.AddComment("Scope type index");
267 OS.EmitIntValue(TypeIndex().getIndex(), 4);
268 OS.AddComment("Function type");
269 OS.EmitIntValue(VoidProcIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000270 {
271 SmallString<32> NullTerminatedString(DisplayName);
272 if (NullTerminatedString.empty() || NullTerminatedString.back() != '\0')
273 NullTerminatedString.push_back('\0');
Reid Klecknerdac21b42016-02-03 21:15:48 +0000274 OS.AddComment("Function name");
275 OS.EmitBytes(NullTerminatedString);
David Majnemer30579ec2016-02-02 23:18:23 +0000276 }
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000277
278 TypeIndex FuncIdIdx = getNextTypeIndex();
279 SubprogramToFuncId.insert(std::make_pair(SP, FuncIdIdx));
280 }
281 }
282}
283
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000284void CodeViewDebug::emitInlineeLinesSubsection() {
285 if (InlinedSubprograms.empty())
286 return;
287
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000288 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
289 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000290
291 OS.AddComment("Inlinee lines subsection");
292 OS.EmitIntValue(unsigned(ModuleSubstreamKind::InlineeLines), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000293 OS.AddComment("Subsection size");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000294 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 4);
295 OS.EmitLabel(InlineBegin);
296
297 // We don't provide any extra file info.
298 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000299 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000300 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
301
302 for (const DISubprogram *SP : InlinedSubprograms) {
David Majnemer30579ec2016-02-02 23:18:23 +0000303 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000304 TypeIndex TypeId = SubprogramToFuncId[SP];
305 unsigned FileId = maybeRecordFile(SP->getFile());
306 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
307 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000308 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000309 // The filechecksum table uses 8 byte entries for now, and file ids start at
310 // 1.
311 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000312 OS.AddComment("Type index of inlined function");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000313 OS.EmitIntValue(TypeId.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000314 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000315 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000316 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000317 OS.EmitIntValue(SP->getLine(), 4);
318 }
319
320 OS.EmitLabel(InlineEnd);
321}
322
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000323void CodeViewDebug::collectInlineSiteChildren(
324 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
325 const InlineSite &Site) {
326 for (const DILocation *ChildSiteLoc : Site.ChildSites) {
327 auto I = FI.InlineSites.find(ChildSiteLoc);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000328 const InlineSite &ChildSite = I->second;
329 Children.push_back(ChildSite.SiteFuncId);
330 collectInlineSiteChildren(Children, FI, ChildSite);
331 }
332}
333
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000334void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
335 const DILocation *InlinedAt,
336 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000337 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
338 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000339
340 assert(SubprogramToFuncId.count(Site.Inlinee));
341 TypeIndex InlineeIdx = SubprogramToFuncId[Site.Inlinee];
342
343 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000344 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000345 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000346 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000347 OS.AddComment("Record kind: S_INLINESITE");
348 OS.EmitIntValue(SymbolRecordKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000349
Reid Klecknerdac21b42016-02-03 21:15:48 +0000350 OS.AddComment("PtrParent");
351 OS.EmitIntValue(0, 4);
352 OS.AddComment("PtrEnd");
353 OS.EmitIntValue(0, 4);
354 OS.AddComment("Inlinee type index");
355 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000356
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000357 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
358 unsigned StartLineNum = Site.Inlinee->getLine();
359 SmallVector<unsigned, 3> SecondaryFuncIds;
360 collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
361
362 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
David Majnemerc9911f22016-02-02 19:22:34 +0000363 FI.Begin, FI.End, SecondaryFuncIds);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000364
365 OS.EmitLabel(InlineEnd);
366
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000367 for (const LocalVariable &Var : Site.InlinedLocals)
368 emitLocalVariable(Var);
369
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000370 // Recurse on child inlined call sites before closing the scope.
371 for (const DILocation *ChildSite : Site.ChildSites) {
372 auto I = FI.InlineSites.find(ChildSite);
373 assert(I != FI.InlineSites.end() &&
374 "child site not in function inline site map");
375 emitInlinedCallSite(FI, ChildSite, I->second);
376 }
377
378 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000379 OS.AddComment("Record length");
380 OS.EmitIntValue(2, 2); // RecordLength
381 OS.AddComment("Record kind: S_INLINESITE_END");
382 OS.EmitIntValue(SymbolRecordKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000383}
384
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000385static void emitNullTerminatedString(MCStreamer &OS, StringRef S) {
386 SmallString<32> NullTerminatedString(S);
387 if (NullTerminatedString.empty() || NullTerminatedString.back() != '\0')
388 NullTerminatedString.push_back('\0');
389 OS.EmitBytes(NullTerminatedString);
390}
391
Reid Kleckner2214ed82016-01-29 00:49:42 +0000392void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
393 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000394 // For each function there is a separate subsection
395 // which holds the PC to file:line table.
396 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000397 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000398
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000399 StringRef FuncName;
Duncan P. N. Exon Smith2fbe1352015-04-20 22:10:08 +0000400 if (auto *SP = getDISubprogram(GV))
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000401 FuncName = SP->getDisplayName();
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000402
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000403 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000404 if (FuncName.empty())
405 FuncName = GlobalValue::getRealLinkageName(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000406
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000407 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000408 MCSymbol *SymbolsBegin = MMI->getContext().createTempSymbol(),
409 *SymbolsEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000410 OS.AddComment("Symbol subsection for " + Twine(FuncName));
411 OS.EmitIntValue(unsigned(ModuleSubstreamKind::Symbols), 4);
412 OS.AddComment("Subsection size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000413 OS.emitAbsoluteSymbolDiff(SymbolsEnd, SymbolsBegin, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000414 OS.EmitLabel(SymbolsBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000415 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000416 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
417 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000418 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000419 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000420 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000421
Reid Klecknerdac21b42016-02-03 21:15:48 +0000422 OS.AddComment("Record kind: S_GPROC32_ID");
423 OS.EmitIntValue(unsigned(SymbolRecordKind::S_GPROC32_ID), 2);
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000424
David Majnemer30579ec2016-02-02 23:18:23 +0000425 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000426 OS.AddComment("PtrParent");
427 OS.EmitIntValue(0, 4);
428 OS.AddComment("PtrEnd");
429 OS.EmitIntValue(0, 4);
430 OS.AddComment("PtrNext");
431 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000432 // This is the important bit that tells the debugger where the function
433 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000434 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000435 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000436 OS.AddComment("Offset after prologue");
437 OS.EmitIntValue(0, 4);
438 OS.AddComment("Offset before epilogue");
439 OS.EmitIntValue(0, 4);
440 OS.AddComment("Function type index");
441 OS.EmitIntValue(0, 4);
442 OS.AddComment("Function section relative address");
443 OS.EmitCOFFSecRel32(Fn);
444 OS.AddComment("Function section index");
445 OS.EmitCOFFSectionIndex(Fn);
446 OS.AddComment("Flags");
447 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000448 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000449 OS.AddComment("Function name");
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000450 emitNullTerminatedString(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000451 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000452
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000453 for (const LocalVariable &Var : FI.Locals)
454 emitLocalVariable(Var);
455
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000456 // Emit inlined call site information. Only emit functions inlined directly
457 // into the parent function. We'll emit the other sites recursively as part
458 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000459 for (const DILocation *InlinedAt : FI.ChildSites) {
460 auto I = FI.InlineSites.find(InlinedAt);
461 assert(I != FI.InlineSites.end() &&
462 "child site not in function inline site map");
463 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000464 }
465
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000466 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000467 OS.AddComment("Record length");
468 OS.EmitIntValue(0x0002, 2);
469 OS.AddComment("Record kind: S_PROC_ID_END");
470 OS.EmitIntValue(unsigned(SymbolRecordKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000471 }
Reid Klecknerdac21b42016-02-03 21:15:48 +0000472 OS.EmitLabel(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000473 // Every subsection must be aligned to a 4-byte boundary.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000474 OS.EmitValueToAlignment(4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000475
Reid Kleckner2214ed82016-01-29 00:49:42 +0000476 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000477 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000478}
479
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000480void CodeViewDebug::collectVariableInfoFromMMITable() {
481 for (const auto &VI : MMI->getVariableDbgInfo()) {
482 if (!VI.Var)
483 continue;
484 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
485 "Expected inlined-at fields to agree");
486
487 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
488
489 // If variable scope is not found then skip this variable.
490 if (!Scope)
491 continue;
492
493 LocalVariable Var;
494 Var.DIVar = VI.Var;
495
496 // Get the frame register used and the offset.
497 unsigned FrameReg = 0;
498 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
499 const TargetFrameLowering *TFI = TSI.getFrameLowering();
500 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
501 Var.RegisterOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
502 Var.CVRegister = TRI->getCodeViewRegNum(FrameReg);
503
504 // Calculate the label ranges.
505 for (const InsnRange &Range : Scope->getRanges()) {
506 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
507 const MCSymbol *End = getLabelAfterInsn(Range.second);
508 Var.Ranges.push_back({Begin, End});
509 }
510
511 if (VI.Loc->getInlinedAt()) {
512 // This variable was inlined. Associate it with the InlineSite.
513 InlineSite &Site = getInlineSite(VI.Loc);
514 Site.InlinedLocals.emplace_back(std::move(Var));
515 } else {
516 // This variable goes in the main ProcSym.
517 CurFn->Locals.emplace_back(std::move(Var));
518 }
519 }
520}
521
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000522void CodeViewDebug::beginFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000523 assert(!CurFn && "Can't process two functions at once!");
524
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000525 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000526 return;
527
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000528 DebugHandlerBase::beginFunction(MF);
529
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000530 const Function *GV = MF->getFunction();
531 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000532 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +0000533 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000534 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000535
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000536 // Find the end of the function prolog. First known non-DBG_VALUE and
537 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000538 // FIXME: is there a simpler a way to do this? Can we just search
539 // for the first instruction of the function, not the last of the prolog?
540 DebugLoc PrologEndLoc;
541 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000542 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000543 for (const auto &MI : MBB) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000544 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
545 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000546 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000547 break;
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000548 } else if (!MI.isDebugValue()) {
549 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000550 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000551 }
552 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000553
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000554 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000555 if (PrologEndLoc && !EmptyPrologue) {
556 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000557 maybeRecordLocation(FnStartDL, MF);
558 }
559}
560
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000561void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
562 // LocalSym record, see SymbolRecord.h for more info.
563 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
564 *LocalEnd = MMI->getContext().createTempSymbol();
565 OS.AddComment("Record length");
566 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
567 OS.EmitLabel(LocalBegin);
568
569 OS.AddComment("Record kind: S_LOCAL");
570 OS.EmitIntValue(unsigned(SymbolRecordKind::S_LOCAL), 2);
571
572 uint16_t Flags = 0;
573 if (Var.DIVar->isParameter())
574 Flags |= LocalSym::IsParameter;
575
576 OS.AddComment("TypeIndex");
577 OS.EmitIntValue(TypeIndex::Int32().getIndex(), 4);
578 OS.AddComment("Flags");
579 OS.EmitIntValue(Flags, 2);
580 emitNullTerminatedString(OS, Var.DIVar->getName());
581 OS.EmitLabel(LocalEnd);
582
583 // DefRangeRegisterRelSym record, see SymbolRecord.h for more info. Omit the
584 // LocalVariableAddrRange field from the record. The directive will emit that.
585 DefRangeRegisterRelSym Sym{};
586 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
587 Sym.BaseRegister = Var.CVRegister;
588 Sym.Flags = 0; // Unclear what matters here.
589 Sym.BasePointerOffset = Var.RegisterOffset;
590 SmallString<sizeof(Sym) + sizeof(SymKind) - sizeof(LocalVariableAddrRange)>
591 BytePrefix;
592 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
593 sizeof(SymKind));
594 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym),
595 sizeof(Sym) - sizeof(LocalVariableAddrRange));
596
597 OS.EmitCVDefRangeDirective(Var.Ranges, BytePrefix);
598}
599
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000600void CodeViewDebug::endFunction(const MachineFunction *MF) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000601 collectVariableInfoFromMMITable();
602
603 DebugHandlerBase::endFunction(MF);
604
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000605 if (!Asm || !CurFn) // We haven't created any debug info for this function.
606 return;
607
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +0000608 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +0000609 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +0000610 assert(CurFn == &FnDebugInfo[GV]);
611
Reid Kleckner2214ed82016-01-29 00:49:42 +0000612 // Don't emit anything if we don't have any line tables.
613 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +0000614 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000615 CurFn = nullptr;
616 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000617 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000618
619 CurFn->End = Asm->getFunctionEnd();
620
Craig Topper353eda42014-04-24 06:44:33 +0000621 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000622}
623
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000624void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000625 DebugHandlerBase::beginInstruction(MI);
626
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000627 // Ignore DBG_VALUE locations and function prologue.
628 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
629 return;
630 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000631 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000632 return;
633 maybeRecordLocation(DL, Asm->MF);
634}