blob: e408485627295767f0662d2fe93fe962cb19e664 [file] [log] [blame]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001//===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
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"
Adrian Prantl032d2382017-08-01 21:45:24 +000015#include "DwarfExpression.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000016#include "llvm/ADT/APSInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/DenseSet.h"
20#include "llvm/ADT/MapVector.h"
21#include "llvm/ADT/None.h"
22#include "llvm/ADT/Optional.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/StringRef.h"
Reid Kleckner156a7232016-06-22 18:31:14 +000027#include "llvm/ADT/TinyPtrVector.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000028#include "llvm/ADT/Triple.h"
29#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000030#include "llvm/BinaryFormat/COFF.h"
31#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000032#include "llvm/CodeGen/AsmPrinter.h"
33#include "llvm/CodeGen/LexicalScopes.h"
34#include "llvm/CodeGen/MachineFunction.h"
35#include "llvm/CodeGen/MachineInstr.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineOperand.h"
38#include "llvm/Config/llvm-config.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000039#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000040#include "llvm/DebugInfo/CodeView/CodeView.h"
Zachary Turner8c099fe2017-05-30 16:36:15 +000041#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000042#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000043#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000044#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000045#include "llvm/DebugInfo/CodeView/TypeIndex.h"
46#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000047#include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000048#include "llvm/IR/Constants.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000049#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/DebugInfoMetadata.h"
51#include "llvm/IR/DebugLoc.h"
52#include "llvm/IR/Function.h"
53#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/GlobalVariable.h"
55#include "llvm/IR/Metadata.h"
56#include "llvm/IR/Module.h"
Reid Kleckner46cb48c2016-07-27 16:03:57 +000057#include "llvm/MC/MCAsmInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000058#include "llvm/MC/MCContext.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000059#include "llvm/MC/MCSectionCOFF.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000060#include "llvm/MC/MCStreamer.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000061#include "llvm/MC/MCSymbol.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000062#include "llvm/Support/BinaryByteStream.h"
63#include "llvm/Support/BinaryStreamReader.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000064#include "llvm/Support/Casting.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000065#include "llvm/Support/Compiler.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000066#include "llvm/Support/Endian.h"
67#include "llvm/Support/Error.h"
68#include "llvm/Support/ErrorHandling.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000069#include "llvm/Support/ScopedPrinter.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000070#include "llvm/Support/SMLoc.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000071#include "llvm/Target/TargetFrameLowering.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000072#include "llvm/Target/TargetLoweringObjectFile.h"
73#include "llvm/Target/TargetMachine.h"
Amjad Aboud76c9eb92016-06-18 10:25:07 +000074#include "llvm/Target/TargetRegisterInfo.h"
75#include "llvm/Target/TargetSubtargetInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000076#include <algorithm>
77#include <cassert>
78#include <cctype>
79#include <cstddef>
80#include <cstdint>
81#include <iterator>
82#include <limits>
83#include <string>
84#include <utility>
85#include <vector>
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000086
Reid Klecknerf9c275f2016-02-10 20:55:49 +000087using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000088using namespace llvm::codeview;
89
Reid Klecknerf9c275f2016-02-10 20:55:49 +000090CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
Eugene Zelenkofb69e662017-06-06 22:22:41 +000091 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +000092 // If module doesn't have named metadata anchors or COFF debug section
93 // is not available, skip any debug info related stuff.
94 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
95 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
96 Asm = nullptr;
97 return;
98 }
99
100 // Tell MMI that we have debug info.
101 MMI->setDebugInfoAvailability(true);
102}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000103
Reid Kleckner9533af42016-01-16 00:09:09 +0000104StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
105 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000106 if (!Filepath.empty())
107 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000108
Reid Kleckner9533af42016-01-16 00:09:09 +0000109 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
110
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000111 // Clang emits directory and relative filename info into the IR, but CodeView
112 // operates on full paths. We could change Clang to emit full paths too, but
113 // that would increase the IR size and probably not needed for other users.
114 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000115 if (Filename.find(':') == 1)
116 Filepath = Filename;
117 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +0000118 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000119
120 // Canonicalize the path. We have to do it textually because we may no longer
121 // have access the file in the filesystem.
122 // First, replace all slashes with backslashes.
123 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
124
125 // Remove all "\.\" with "\".
126 size_t Cursor = 0;
127 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
128 Filepath.erase(Cursor, 2);
129
130 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
131 // path should be well-formatted, e.g. start with a drive letter, etc.
132 Cursor = 0;
133 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
134 // Something's wrong if the path starts with "\..\", abort.
135 if (Cursor == 0)
136 break;
137
138 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
139 if (PrevSlash == std::string::npos)
140 // Something's wrong, abort.
141 break;
142
143 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
144 // The next ".." might be following the one we've just erased.
145 Cursor = PrevSlash;
146 }
147
148 // Remove all duplicate backslashes.
149 Cursor = 0;
150 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
151 Filepath.erase(Cursor, 1);
152
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000153 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000154}
155
Reid Kleckner2214ed82016-01-29 00:49:42 +0000156unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
157 unsigned NextId = FileIdMap.size() + 1;
158 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
159 if (Insertion.second) {
160 // We have to compute the full filepath and emit a .cv_file directive.
161 StringRef FullPath = getFullFilepath(F);
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000162 bool Success = OS.EmitCVFileDirective(NextId, FullPath);
163 (void)Success;
164 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000165 }
166 return Insertion.first->second;
167}
168
Reid Kleckner876330d2016-02-12 21:48:30 +0000169CodeViewDebug::InlineSite &
170CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
171 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000172 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
173 InlineSite *Site = &SiteInsertion.first->second;
174 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000175 unsigned ParentFuncId = CurFn->FuncId;
176 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
177 ParentFuncId =
178 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
179 .SiteFuncId;
180
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000181 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000182 OS.EmitCVInlineSiteIdDirective(
183 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
184 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000185 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000186 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000187 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000188 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000189 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000190}
191
David Majnemer6bdc24e2016-07-01 23:12:45 +0000192static StringRef getPrettyScopeName(const DIScope *Scope) {
193 StringRef ScopeName = Scope->getName();
194 if (!ScopeName.empty())
195 return ScopeName;
196
197 switch (Scope->getTag()) {
198 case dwarf::DW_TAG_enumeration_type:
199 case dwarf::DW_TAG_class_type:
200 case dwarf::DW_TAG_structure_type:
201 case dwarf::DW_TAG_union_type:
202 return "<unnamed-tag>";
203 case dwarf::DW_TAG_namespace:
204 return "`anonymous namespace'";
205 }
206
207 return StringRef();
208}
209
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000210static const DISubprogram *getQualifiedNameComponents(
211 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
212 const DISubprogram *ClosestSubprogram = nullptr;
213 while (Scope != nullptr) {
214 if (ClosestSubprogram == nullptr)
215 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000216 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000217 if (!ScopeName.empty())
218 QualifiedNameComponents.push_back(ScopeName);
219 Scope = Scope->getScope().resolve();
220 }
221 return ClosestSubprogram;
222}
223
224static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
225 StringRef TypeName) {
226 std::string FullyQualifiedName;
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000227 for (StringRef QualifiedNameComponent :
228 llvm::reverse(QualifiedNameComponents)) {
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000229 FullyQualifiedName.append(QualifiedNameComponent);
230 FullyQualifiedName.append("::");
231 }
232 FullyQualifiedName.append(TypeName);
233 return FullyQualifiedName;
234}
235
236static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
237 SmallVector<StringRef, 5> QualifiedNameComponents;
238 getQualifiedNameComponents(Scope, QualifiedNameComponents);
239 return getQualifiedName(QualifiedNameComponents, Name);
240}
241
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000242struct CodeViewDebug::TypeLoweringScope {
243 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
244 ~TypeLoweringScope() {
245 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
246 // inner TypeLoweringScopes don't attempt to emit deferred types.
247 if (CVD.TypeEmissionLevel == 1)
248 CVD.emitDeferredCompleteTypes();
249 --CVD.TypeEmissionLevel;
250 }
251 CodeViewDebug &CVD;
252};
253
David Majnemer6bdc24e2016-07-01 23:12:45 +0000254static std::string getFullyQualifiedName(const DIScope *Ty) {
255 const DIScope *Scope = Ty->getScope().resolve();
256 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
257}
258
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000259TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
260 // No scope means global scope and that uses the zero index.
261 if (!Scope || isa<DIFile>(Scope))
262 return TypeIndex();
263
264 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
265
266 // Check if we've already translated this scope.
267 auto I = TypeIndices.find({Scope, nullptr});
268 if (I != TypeIndices.end())
269 return I->second;
270
271 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000272 std::string ScopeName = getFullyQualifiedName(Scope);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000273 StringIdRecord SID(TypeIndex(), ScopeName);
274 auto TI = TypeTable.writeKnownType(SID);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000275 return recordTypeIndexForDINode(Scope, TI);
276}
277
David Majnemer75c3ebf2016-06-02 17:13:53 +0000278TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000279 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000280
David Majnemer75c3ebf2016-06-02 17:13:53 +0000281 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000282 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000283 if (I != TypeIndices.end())
284 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000285
Reid Klecknerac945e22016-06-17 16:11:20 +0000286 // The display name includes function template arguments. Drop them to match
287 // MSVC.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000288 StringRef DisplayName = SP->getName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000289
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000290 const DIScope *Scope = SP->getScope().resolve();
291 TypeIndex TI;
292 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
293 // If the scope is a DICompositeType, then this must be a method. Member
294 // function types take some special handling, and require access to the
295 // subprogram.
296 TypeIndex ClassType = getTypeIndex(Class);
297 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
298 DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000299 TI = TypeTable.writeKnownType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000300 } else {
301 // Otherwise, this must be a free function.
302 TypeIndex ParentScope = getScopeIndex(Scope);
303 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000304 TI = TypeTable.writeKnownType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000305 }
306
307 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000308}
309
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000310TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
311 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000312 // Always use the method declaration as the key for the function type. The
313 // method declaration contains the this adjustment.
314 if (SP->getDeclaration())
315 SP = SP->getDeclaration();
316 assert(!SP->getDeclaration() && "should use declaration as key");
317
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000318 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
319 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000320 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000321 if (I != TypeIndices.end())
322 return I->second;
323
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000324 // Make sure complete type info for the class is emitted *after* the member
325 // function type, as the complete class type is likely to reference this
326 // member function type.
327 TypeLoweringScope S(*this);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000328 TypeIndex TI =
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000329 lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000330 return recordTypeIndexForDINode(SP, TI, Class);
331}
332
Amjad Aboudacee5682016-07-12 12:06:34 +0000333TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
334 TypeIndex TI,
335 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000336 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000337 (void)InsertResult;
338 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000339 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000340}
341
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000342unsigned CodeViewDebug::getPointerSizeInBytes() {
343 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
344}
345
Reid Kleckner876330d2016-02-12 21:48:30 +0000346void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
347 const DILocation *InlinedAt) {
348 if (InlinedAt) {
349 // This variable was inlined. Associate it with the InlineSite.
350 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
351 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
352 Site.InlinedLocals.emplace_back(Var);
353 } else {
354 // This variable goes in the main ProcSym.
355 CurFn->Locals.emplace_back(Var);
356 }
357}
358
Reid Kleckner829365a2016-02-11 19:41:47 +0000359static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
360 const DILocation *Loc) {
361 auto B = Locs.begin(), E = Locs.end();
362 if (std::find(B, E, Loc) == E)
363 Locs.push_back(Loc);
364}
365
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000366void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000367 const MachineFunction *MF) {
368 // Skip this instruction if it has the same location as the previous one.
Reid Kleckner45a74622017-06-30 21:33:44 +0000369 if (!DL || DL == PrevInstLoc)
Reid Kleckner9533af42016-01-16 00:09:09 +0000370 return;
371
372 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000373 if (!Scope)
374 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000375
David Majnemerc3340db2016-01-13 01:05:23 +0000376 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000377 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
378 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
379 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000380 return;
381
Reid Kleckner2214ed82016-01-29 00:49:42 +0000382 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
383 if (CI.getStartColumn() != DL.getCol())
384 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000385
Reid Kleckner2214ed82016-01-29 00:49:42 +0000386 if (!CurFn->HaveLineInfo)
387 CurFn->HaveLineInfo = true;
388 unsigned FileId = 0;
Reid Kleckner45a74622017-06-30 21:33:44 +0000389 if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
Reid Kleckner2214ed82016-01-29 00:49:42 +0000390 FileId = CurFn->LastFileId;
391 else
392 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
Reid Kleckner45a74622017-06-30 21:33:44 +0000393 PrevInstLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000394
395 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000396 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000397 const DILocation *Loc = DL.get();
398
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000399 // If this location was actually inlined from somewhere else, give it the ID
400 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000401 FuncId =
402 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000403
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000404 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000405 bool FirstLoc = true;
406 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000407 InlineSite &Site =
408 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000409 if (!FirstLoc)
410 addLocIfNotPresent(Site.ChildSites, Loc);
411 FirstLoc = false;
412 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000413 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000414 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000415 }
416
Reid Klecknerdac21b42016-02-03 21:15:48 +0000417 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000418 /*PrologueEnd=*/false, /*IsStmt=*/false,
419 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000420}
421
Reid Kleckner5d122f82016-05-25 23:16:12 +0000422void CodeViewDebug::emitCodeViewMagicVersion() {
423 OS.EmitValueToAlignment(4);
424 OS.AddComment("Debug section magic");
425 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
426}
427
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000428void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000429 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000430 return;
431
432 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000433
434 // The COFF .debug$S section consists of several subsections, each starting
435 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
436 // of the payload followed by the payload itself. The subsections are 4-byte
437 // aligned.
438
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000439 // Use the generic .debug$S section, and make a subsection for all the inlined
440 // subprograms.
441 switchToDebugSectionForSymbol(nullptr);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000442
Zachary Turner8c099fe2017-05-30 16:36:15 +0000443 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000444 emitCompilerInformation();
445 endCVSubsection(CompilerInfo);
446
Reid Kleckner5d122f82016-05-25 23:16:12 +0000447 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000448
Reid Kleckner2214ed82016-01-29 00:49:42 +0000449 // Emit per-function debug information.
450 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000451 if (!P.first->isDeclarationForLinker())
452 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000453
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000454 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000455 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000456 emitDebugInfoForGlobals();
457
Hans Wennborgb510b452016-06-23 16:33:53 +0000458 // Emit retained types.
459 emitDebugInfoForRetainedTypes();
460
Reid Kleckner5d122f82016-05-25 23:16:12 +0000461 // Switch back to the generic .debug$S section after potentially processing
462 // comdat symbol sections.
463 switchToDebugSectionForSymbol(nullptr);
464
David Majnemer3128b102016-06-15 18:00:01 +0000465 // Emit UDT records for any types used by global variables.
466 if (!GlobalUDTs.empty()) {
Zachary Turner8c099fe2017-05-30 16:36:15 +0000467 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
David Majnemer3128b102016-06-15 18:00:01 +0000468 emitDebugInfoForUDTs(GlobalUDTs);
469 endCVSubsection(SymbolsEnd);
470 }
471
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000472 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000473 OS.AddComment("File index to string table offset subsection");
474 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000475
476 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000477 OS.AddComment("String table");
478 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000479
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000480 // Emit type information last, so that any types we translate while emitting
481 // function info are included.
482 emitTypeInformation();
483
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000484 clear();
485}
486
David Majnemerb9456a52016-03-14 05:15:09 +0000487static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000488 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
489 // after a fixed length portion of the record. The fixed length portion should
490 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
491 // overall record size is less than the maximum allowed.
492 unsigned MaxFixedRecordLength = 0xF00;
493 SmallString<32> NullTerminatedString(
494 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
David Majnemerb9456a52016-03-14 05:15:09 +0000495 NullTerminatedString.push_back('\0');
496 OS.EmitBytes(NullTerminatedString);
497}
498
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000499void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000500 // Do nothing if we have no debug info or if no non-trivial types were emitted
501 // to TypeTable during codegen.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000502 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
Reid Klecknerfbd77872016-03-18 18:54:32 +0000503 if (!CU_Nodes)
504 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000505 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000506 return;
507
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000508 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000509 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000510 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000511
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000512 SmallString<8> CommentPrefix;
513 if (OS.isVerboseAsm()) {
514 CommentPrefix += '\t';
515 CommentPrefix += Asm->MAI->getCommentString();
516 CommentPrefix += ' ';
517 }
518
Zachary Turner526f4f22017-05-19 19:26:58 +0000519 TypeTableCollection Table(TypeTable.records());
520 Optional<TypeIndex> B = Table.getFirst();
521 while (B) {
522 // This will fail if the record data is invalid.
523 CVType Record = Table.getType(*B);
524
Zachary Turner4efa0a42016-11-08 22:24:53 +0000525 if (OS.isVerboseAsm()) {
526 // Emit a block comment describing the type record for readability.
527 SmallString<512> CommentBlock;
528 raw_svector_ostream CommentOS(CommentBlock);
529 ScopedPrinter SP(CommentOS);
530 SP.setPrefix(CommentPrefix);
Zachary Turner526f4f22017-05-19 19:26:58 +0000531 TypeDumpVisitor TDV(Table, &SP, false);
532
533 Error E = codeview::visitTypeRecord(Record, *B, TDV);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000534 if (E) {
535 logAllUnhandledErrors(std::move(E), errs(), "error: ");
536 llvm_unreachable("produced malformed type record");
537 }
538 // emitRawComment will insert its own tab and comment string before
539 // the first line, so strip off our first one. It also prints its own
540 // newline.
541 OS.emitRawComment(
542 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Zachary Turner4efa0a42016-11-08 22:24:53 +0000543 }
Zachary Turner526f4f22017-05-19 19:26:58 +0000544 OS.EmitBinaryData(Record.str_data());
545 B = Table.getNext(*B);
546 }
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000547}
548
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000549static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
550 switch (DWLang) {
551 case dwarf::DW_LANG_C:
552 case dwarf::DW_LANG_C89:
553 case dwarf::DW_LANG_C99:
554 case dwarf::DW_LANG_C11:
555 case dwarf::DW_LANG_ObjC:
556 return SourceLanguage::C;
557 case dwarf::DW_LANG_C_plus_plus:
558 case dwarf::DW_LANG_C_plus_plus_03:
559 case dwarf::DW_LANG_C_plus_plus_11:
560 case dwarf::DW_LANG_C_plus_plus_14:
561 return SourceLanguage::Cpp;
562 case dwarf::DW_LANG_Fortran77:
563 case dwarf::DW_LANG_Fortran90:
564 case dwarf::DW_LANG_Fortran03:
565 case dwarf::DW_LANG_Fortran08:
566 return SourceLanguage::Fortran;
567 case dwarf::DW_LANG_Pascal83:
568 return SourceLanguage::Pascal;
569 case dwarf::DW_LANG_Cobol74:
570 case dwarf::DW_LANG_Cobol85:
571 return SourceLanguage::Cobol;
572 case dwarf::DW_LANG_Java:
573 return SourceLanguage::Java;
Reid Kleckner898ddf62017-07-24 16:16:42 +0000574 case dwarf::DW_LANG_D:
575 return SourceLanguage::D;
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000576 default:
577 // There's no CodeView representation for this language, and CV doesn't
578 // have an "unknown" option for the language field, so we'll use MASM,
579 // as it's very low level.
580 return SourceLanguage::Masm;
581 }
582}
583
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000584namespace {
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000585struct Version {
586 int Part[4];
587};
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000588} // end anonymous namespace
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000589
590// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
591// the version number.
592static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000593 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000594 int N = 0;
595 for (const char C : Name) {
596 if (isdigit(C)) {
597 V.Part[N] *= 10;
598 V.Part[N] += C - '0';
599 } else if (C == '.') {
600 ++N;
601 if (N >= 4)
602 return V;
603 } else if (N > 0)
604 return V;
605 }
606 return V;
607}
608
609static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
610 switch (Type) {
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000611 case Triple::ArchType::x86:
612 return CPUType::Pentium3;
613 case Triple::ArchType::x86_64:
614 return CPUType::X64;
615 case Triple::ArchType::thumb:
616 return CPUType::Thumb;
617 case Triple::ArchType::aarch64:
618 return CPUType::ARM64;
619 default:
620 report_fatal_error("target architecture doesn't map to a CodeView CPUType");
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000621 }
622}
623
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000624void CodeViewDebug::emitCompilerInformation() {
625 MCContext &Context = MMI->getContext();
626 MCSymbol *CompilerBegin = Context.createTempSymbol(),
627 *CompilerEnd = Context.createTempSymbol();
628 OS.AddComment("Record length");
629 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
630 OS.EmitLabel(CompilerBegin);
631 OS.AddComment("Record kind: S_COMPILE3");
632 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
633 uint32_t Flags = 0;
634
635 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
636 const MDNode *Node = *CUs->operands().begin();
637 const auto *CU = cast<DICompileUnit>(Node);
638
639 // The low byte of the flags indicates the source language.
640 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
641 // TODO: Figure out which other flags need to be set.
642
643 OS.AddComment("Flags and language");
644 OS.EmitIntValue(Flags, 4);
645
646 OS.AddComment("CPUType");
647 CPUType CPU =
648 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
649 OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
650
651 StringRef CompilerVersion = CU->getProducer();
652 Version FrontVer = parseVersion(CompilerVersion);
653 OS.AddComment("Frontend version");
654 for (int N = 0; N < 4; ++N)
655 OS.EmitIntValue(FrontVer.Part[N], 2);
656
657 // Some Microsoft tools, like Binscope, expect a backend version number of at
658 // least 8.something, so we'll coerce the LLVM version into a form that
659 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000660 int Major = 1000 * LLVM_VERSION_MAJOR +
661 10 * LLVM_VERSION_MINOR +
662 LLVM_VERSION_PATCH;
663 // Clamp it for builds that use unusually large version numbers.
664 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
665 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000666 OS.AddComment("Backend version");
667 for (int N = 0; N < 4; ++N)
668 OS.EmitIntValue(BackVer.Part[N], 2);
669
670 OS.AddComment("Null-terminated compiler version string");
671 emitNullTerminatedSymbolName(OS, CompilerVersion);
672
673 OS.EmitLabel(CompilerEnd);
674}
675
Reid Kleckner5d122f82016-05-25 23:16:12 +0000676void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000677 if (InlinedSubprograms.empty())
678 return;
679
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000680 OS.AddComment("Inlinee lines subsection");
Zachary Turner8c099fe2017-05-30 16:36:15 +0000681 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000682
683 // We don't provide any extra file info.
684 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000685 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000686 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
687
688 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000689 assert(TypeIndices.count({SP, nullptr}));
690 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000691
David Majnemer30579ec2016-02-02 23:18:23 +0000692 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000693 unsigned FileId = maybeRecordFile(SP->getFile());
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000694 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000695 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000696 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000697 // The filechecksum table uses 8 byte entries for now, and file ids start at
698 // 1.
699 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000700 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000701 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000702 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000703 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000704 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000705 OS.EmitIntValue(SP->getLine(), 4);
706 }
707
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000708 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000709}
710
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000711void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
712 const DILocation *InlinedAt,
713 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000714 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
715 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000716
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000717 assert(TypeIndices.count({Site.Inlinee, nullptr}));
718 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000719
720 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000721 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000722 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000723 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000724 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000725 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000726
Reid Klecknerdac21b42016-02-03 21:15:48 +0000727 OS.AddComment("PtrParent");
728 OS.EmitIntValue(0, 4);
729 OS.AddComment("PtrEnd");
730 OS.EmitIntValue(0, 4);
731 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000732 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000733
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000734 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
735 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000736
737 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000738 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000739
740 OS.EmitLabel(InlineEnd);
741
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000742 emitLocalVariableList(Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000743
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000744 // Recurse on child inlined call sites before closing the scope.
745 for (const DILocation *ChildSite : Site.ChildSites) {
746 auto I = FI.InlineSites.find(ChildSite);
747 assert(I != FI.InlineSites.end() &&
748 "child site not in function inline site map");
749 emitInlinedCallSite(FI, ChildSite, I->second);
750 }
751
752 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000753 OS.AddComment("Record length");
754 OS.EmitIntValue(2, 2); // RecordLength
755 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000756 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000757}
758
Reid Kleckner5d122f82016-05-25 23:16:12 +0000759void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
760 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
761 // comdat key. A section may be comdat because of -ffunction-sections or
762 // because it is comdat in the IR.
763 MCSectionCOFF *GVSec =
764 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
765 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
766
767 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
768 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
769 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
770
771 OS.SwitchSection(DebugSec);
772
773 // Emit the magic version number if this is the first time we've switched to
774 // this section.
775 if (ComdatDebugSections.insert(DebugSec).second)
776 emitCodeViewMagicVersion();
777}
778
Reid Kleckner2214ed82016-01-29 00:49:42 +0000779void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
780 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000781 // For each function there is a separate subsection
782 // which holds the PC to file:line table.
783 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000784 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000785
Reid Kleckner5d122f82016-05-25 23:16:12 +0000786 // Switch to the to a comdat section, if appropriate.
787 switchToDebugSectionForSymbol(Fn);
788
Reid Klecknerac945e22016-06-17 16:11:20 +0000789 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000790 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000791 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000792 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000793
794 // If we have a display name, build the fully qualified name by walking the
795 // chain of scopes.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000796 if (!SP->getName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000797 FuncName =
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000798 getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000799
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000800 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000801 if (FuncName.empty())
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +0000802 FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000803
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000804 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000805 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Zachary Turner8c099fe2017-05-30 16:36:15 +0000806 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000807 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000808 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
809 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000810 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000811 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000812 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000813
Reid Kleckner4ad127f2016-09-14 21:49:21 +0000814 if (GV->hasLocalLinkage()) {
815 OS.AddComment("Record kind: S_LPROC32_ID");
816 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
817 } else {
818 OS.AddComment("Record kind: S_GPROC32_ID");
819 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
820 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000821
David Majnemer30579ec2016-02-02 23:18:23 +0000822 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000823 OS.AddComment("PtrParent");
824 OS.EmitIntValue(0, 4);
825 OS.AddComment("PtrEnd");
826 OS.EmitIntValue(0, 4);
827 OS.AddComment("PtrNext");
828 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000829 // This is the important bit that tells the debugger where the function
830 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000831 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000832 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000833 OS.AddComment("Offset after prologue");
834 OS.EmitIntValue(0, 4);
835 OS.AddComment("Offset before epilogue");
836 OS.EmitIntValue(0, 4);
837 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000838 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000839 OS.AddComment("Function section relative address");
Keno Fischerf7d84ee2017-01-02 03:00:19 +0000840 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000841 OS.AddComment("Function section index");
842 OS.EmitCOFFSectionIndex(Fn);
843 OS.AddComment("Flags");
844 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000845 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000846 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000847 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000848 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000849 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000850
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000851 emitLocalVariableList(FI.Locals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000852
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000853 // Emit inlined call site information. Only emit functions inlined directly
854 // into the parent function. We'll emit the other sites recursively as part
855 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000856 for (const DILocation *InlinedAt : FI.ChildSites) {
857 auto I = FI.InlineSites.find(InlinedAt);
858 assert(I != FI.InlineSites.end() &&
859 "child site not in function inline site map");
860 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000861 }
862
Reid Klecknere33c94f2017-09-05 20:14:58 +0000863 for (auto Annot : FI.Annotations) {
864 MCSymbol *Label = Annot.first;
865 MDTuple *Strs = cast<MDTuple>(Annot.second);
866 MCSymbol *AnnotBegin = MMI->getContext().createTempSymbol(),
867 *AnnotEnd = MMI->getContext().createTempSymbol();
868 OS.AddComment("Record length");
869 OS.emitAbsoluteSymbolDiff(AnnotEnd, AnnotBegin, 2);
870 OS.EmitLabel(AnnotBegin);
871 OS.AddComment("Record kind: S_ANNOTATION");
872 OS.EmitIntValue(SymbolKind::S_ANNOTATION, 2);
873 OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
874 // FIXME: Make sure we don't overflow the max record size.
875 OS.EmitCOFFSectionIndex(Label);
876 OS.EmitIntValue(Strs->getNumOperands(), 2);
877 for (Metadata *MD : Strs->operands()) {
878 // MDStrings are null terminated, so we can do EmitBytes and get the
879 // nice .asciz directive.
880 StringRef Str = cast<MDString>(MD)->getString();
881 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
882 OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
883 }
884 OS.EmitLabel(AnnotEnd);
885 }
886
David Majnemer3128b102016-06-15 18:00:01 +0000887 if (SP != nullptr)
888 emitDebugInfoForUDTs(LocalUDTs);
889
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000890 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000891 OS.AddComment("Record length");
892 OS.EmitIntValue(0x0002, 2);
893 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000894 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000895 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000896 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000897
Reid Kleckner2214ed82016-01-29 00:49:42 +0000898 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000899 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000900}
901
Reid Kleckner876330d2016-02-12 21:48:30 +0000902CodeViewDebug::LocalVarDefRange
903CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
904 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000905 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000906 DR.DataOffset = Offset;
907 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000908 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000909 DR.StructOffset = 0;
910 DR.CVRegister = CVRegister;
911 return DR;
912}
913
914CodeViewDebug::LocalVarDefRange
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000915CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
916 int Offset, bool IsSubfield,
917 uint16_t StructOffset) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000918 LocalVarDefRange DR;
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000919 DR.InMemory = InMemory;
920 DR.DataOffset = Offset;
921 DR.IsSubfield = IsSubfield;
922 DR.StructOffset = StructOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +0000923 DR.CVRegister = CVRegister;
924 return DR;
925}
926
Matthias Braunef331ef2016-11-30 23:48:50 +0000927void CodeViewDebug::collectVariableInfoFromMFTable(
Reid Kleckner876330d2016-02-12 21:48:30 +0000928 DenseSet<InlinedVariable> &Processed) {
Matthias Braunef331ef2016-11-30 23:48:50 +0000929 const MachineFunction &MF = *Asm->MF;
930 const TargetSubtargetInfo &TSI = MF.getSubtarget();
Reid Kleckner876330d2016-02-12 21:48:30 +0000931 const TargetFrameLowering *TFI = TSI.getFrameLowering();
932 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
933
Matthias Braunef331ef2016-11-30 23:48:50 +0000934 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000935 if (!VI.Var)
936 continue;
937 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
938 "Expected inlined-at fields to agree");
939
Reid Kleckner876330d2016-02-12 21:48:30 +0000940 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000941 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
942
943 // If variable scope is not found then skip this variable.
944 if (!Scope)
945 continue;
946
Reid Klecknerb5fced72017-05-09 19:59:29 +0000947 // If the variable has an attached offset expression, extract it.
948 // FIXME: Try to handle DW_OP_deref as well.
949 int64_t ExprOffset = 0;
950 if (VI.Expr)
951 if (!VI.Expr->extractIfOffset(ExprOffset))
952 continue;
953
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000954 // Get the frame register used and the offset.
955 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000956 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
957 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000958
959 // Calculate the label ranges.
Reid Klecknerb5fced72017-05-09 19:59:29 +0000960 LocalVarDefRange DefRange =
961 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000962 for (const InsnRange &Range : Scope->getRanges()) {
963 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
964 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000965 End = End ? End : Asm->getFunctionEnd();
966 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000967 }
968
Reid Kleckner876330d2016-02-12 21:48:30 +0000969 LocalVariable Var;
970 Var.DIVar = VI.Var;
971 Var.DefRanges.emplace_back(std::move(DefRange));
972 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
973 }
974}
975
Reid Kleckner08f5fd52017-08-31 15:56:49 +0000976static bool canUseReferenceType(const DbgVariableLocation &Loc) {
977 return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
978}
979
980static bool needsReferenceType(const DbgVariableLocation &Loc) {
981 return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
982}
983
Bob Haarman223303c2017-08-29 20:59:25 +0000984void CodeViewDebug::calculateRanges(
985 LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
986 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
987
Reid Kleckner08f5fd52017-08-31 15:56:49 +0000988 // Calculate the definition ranges.
Bob Haarman223303c2017-08-29 20:59:25 +0000989 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
990 const InsnRange &Range = *I;
991 const MachineInstr *DVInst = Range.first;
992 assert(DVInst->isDebugValue() && "Invalid History entry");
993 // FIXME: Find a way to represent constant variables, since they are
994 // relatively common.
Bob Haarman1a4cbbe2017-08-30 17:50:21 +0000995 Optional<DbgVariableLocation> Location =
996 DbgVariableLocation::extractFromMachineInstruction(*DVInst);
997 if (!Location)
Bob Haarmana88bce12017-08-29 21:01:55 +0000998 continue;
Bob Haarman223303c2017-08-29 20:59:25 +0000999
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001000 // CodeView can only express variables in register and variables in memory
1001 // at a constant offset from a register. However, for variables passed
1002 // indirectly by pointer, it is common for that pointer to be spilled to a
1003 // stack location. For the special case of one offseted load followed by a
1004 // zero offset load (a pointer spilled to the stack), we change the type of
1005 // the local variable from a value type to a reference type. This tricks the
1006 // debugger into doing the load for us.
1007 if (Var.UseReferenceType) {
1008 // We're using a reference type. Drop the last zero offset load.
1009 if (canUseReferenceType(*Location))
1010 Location->LoadChain.pop_back();
1011 else
1012 continue;
1013 } else if (needsReferenceType(*Location)) {
1014 // This location can't be expressed without switching to a reference type.
1015 // Start over using that.
1016 Var.UseReferenceType = true;
Bob Haarman223303c2017-08-29 20:59:25 +00001017 Var.DefRanges.clear();
1018 calculateRanges(Var, Ranges);
1019 return;
1020 }
1021
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001022 // We can only handle a register or an offseted load of a register.
1023 if (Location->Register == 0 || Location->LoadChain.size() > 1)
Bob Haarman223303c2017-08-29 20:59:25 +00001024 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001025 {
1026 LocalVarDefRange DR;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001027 DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001028 DR.InMemory = !Location->LoadChain.empty();
1029 DR.DataOffset =
1030 !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001031 if (Location->FragmentInfo) {
Bob Haarman223303c2017-08-29 20:59:25 +00001032 DR.IsSubfield = true;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001033 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
Bob Haarman223303c2017-08-29 20:59:25 +00001034 } else {
1035 DR.IsSubfield = false;
1036 DR.StructOffset = 0;
1037 }
1038
1039 if (Var.DefRanges.empty() ||
1040 Var.DefRanges.back().isDifferentLocation(DR)) {
1041 Var.DefRanges.emplace_back(std::move(DR));
1042 }
1043 }
1044
1045 // Compute the label range.
1046 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1047 const MCSymbol *End = getLabelAfterInsn(Range.second);
1048 if (!End) {
1049 // This range is valid until the next overlapping bitpiece. In the
1050 // common case, ranges will not be bitpieces, so they will overlap.
1051 auto J = std::next(I);
1052 const DIExpression *DIExpr = DVInst->getDebugExpression();
1053 while (J != E &&
1054 !fragmentsOverlap(DIExpr, J->first->getDebugExpression()))
1055 ++J;
1056 if (J != E)
1057 End = getLabelBeforeInsn(J->first);
1058 else
1059 End = Asm->getFunctionEnd();
1060 }
1061
1062 // If the last range end is our begin, just extend the last range.
1063 // Otherwise make a new range.
1064 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1065 Var.DefRanges.back().Ranges;
1066 if (!R.empty() && R.back().second == Begin)
1067 R.back().second = End;
1068 else
1069 R.emplace_back(Begin, End);
1070
1071 // FIXME: Do more range combining.
1072 }
1073}
1074
Reid Kleckner876330d2016-02-12 21:48:30 +00001075void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
1076 DenseSet<InlinedVariable> Processed;
1077 // Grab the variable info that was squirreled away in the MMI side-table.
Matthias Braunef331ef2016-11-30 23:48:50 +00001078 collectVariableInfoFromMFTable(Processed);
Reid Kleckner876330d2016-02-12 21:48:30 +00001079
Reid Kleckner876330d2016-02-12 21:48:30 +00001080 for (const auto &I : DbgValues) {
1081 InlinedVariable IV = I.first;
1082 if (Processed.count(IV))
1083 continue;
1084 const DILocalVariable *DIVar = IV.first;
1085 const DILocation *InlinedAt = IV.second;
1086
1087 // Instruction ranges, specifying where IV is accessible.
1088 const auto &Ranges = I.second;
1089
1090 LexicalScope *Scope = nullptr;
1091 if (InlinedAt)
1092 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1093 else
1094 Scope = LScopes.findLexicalScope(DIVar->getScope());
1095 // If variable scope is not found then skip this variable.
1096 if (!Scope)
1097 continue;
1098
1099 LocalVariable Var;
1100 Var.DIVar = DIVar;
1101
Bob Haarman223303c2017-08-29 20:59:25 +00001102 calculateRanges(Var, Ranges);
Reid Kleckner876330d2016-02-12 21:48:30 +00001103 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001104 }
1105}
1106
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001107void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001108 const Function *GV = MF->getFunction();
1109 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001110 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +00001111 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001112 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001113
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001114 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1115
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001116 // Find the end of the function prolog. First known non-DBG_VALUE and
1117 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001118 // FIXME: is there a simpler a way to do this? Can we just search
1119 // for the first instruction of the function, not the last of the prolog?
1120 DebugLoc PrologEndLoc;
1121 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001122 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001123 for (const auto &MI : MBB) {
Adrian Prantlfb31da12017-05-22 20:47:09 +00001124 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001125 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001126 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001127 break;
Adrian Prantlfb31da12017-05-22 20:47:09 +00001128 } else if (!MI.isMetaInstruction()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001129 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001130 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001131 }
1132 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001133
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001134 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001135 if (PrologEndLoc && !EmptyPrologue) {
1136 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001137 maybeRecordLocation(FnStartDL, MF);
1138 }
1139}
1140
Zachary Turnera7b04172017-08-28 18:49:04 +00001141static bool shouldEmitUdt(const DIType *T) {
1142 while (true) {
1143 if (!T || T->isForwardDecl())
1144 return false;
1145
1146 const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1147 if (!DT)
1148 return true;
1149 T = DT->getBaseType().resolve();
1150 }
1151 return true;
1152}
1153
1154void CodeViewDebug::addToUDTs(const DIType *Ty) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001155 // Don't record empty UDTs.
1156 if (Ty->getName().empty())
1157 return;
Zachary Turnera7b04172017-08-28 18:49:04 +00001158 if (!shouldEmitUdt(Ty))
1159 return;
Reid Klecknerad56ea32016-07-01 22:24:51 +00001160
Hans Wennborg4b63a982016-06-23 22:57:25 +00001161 SmallVector<StringRef, 5> QualifiedNameComponents;
1162 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1163 Ty->getScope().resolve(), QualifiedNameComponents);
1164
1165 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001166 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001167
Zachary Turnera7b04172017-08-28 18:49:04 +00001168 if (ClosestSubprogram == nullptr) {
1169 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1170 } else if (ClosestSubprogram == CurrentSubprogram) {
1171 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1172 }
Hans Wennborg4b63a982016-06-23 22:57:25 +00001173
1174 // TODO: What if the ClosestSubprogram is neither null or the current
1175 // subprogram? Currently, the UDT just gets dropped on the floor.
1176 //
1177 // The current behavior is not desirable. To get maximal fidelity, we would
1178 // need to perform all type translation before beginning emission of .debug$S
1179 // and then make LocalUDTs a member of FunctionInfo
1180}
1181
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001182TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001183 // Generic dispatch for lowering an unknown type.
1184 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001185 case dwarf::DW_TAG_array_type:
1186 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001187 case dwarf::DW_TAG_typedef:
1188 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001189 case dwarf::DW_TAG_base_type:
1190 return lowerTypeBasic(cast<DIBasicType>(Ty));
1191 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001192 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1193 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1194 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001195 case dwarf::DW_TAG_reference_type:
1196 case dwarf::DW_TAG_rvalue_reference_type:
1197 return lowerTypePointer(cast<DIDerivedType>(Ty));
1198 case dwarf::DW_TAG_ptr_to_member_type:
1199 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1200 case dwarf::DW_TAG_const_type:
1201 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001202 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001203 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001204 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001205 if (ClassTy) {
1206 // The member function type of a member function pointer has no
1207 // ThisAdjustment.
1208 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1209 /*ThisAdjustment=*/0);
1210 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001211 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001212 case dwarf::DW_TAG_enumeration_type:
1213 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001214 case dwarf::DW_TAG_class_type:
1215 case dwarf::DW_TAG_structure_type:
1216 return lowerTypeClass(cast<DICompositeType>(Ty));
1217 case dwarf::DW_TAG_union_type:
1218 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001219 default:
1220 // Use the null type index.
1221 return TypeIndex();
1222 }
1223}
1224
David Majnemerd065e232016-06-02 06:21:37 +00001225TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001226 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1227 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001228 StringRef TypeName = Ty->getName();
1229
Zachary Turnera7b04172017-08-28 18:49:04 +00001230 addToUDTs(Ty);
David Majnemer3128b102016-06-15 18:00:01 +00001231
David Majnemerd065e232016-06-02 06:21:37 +00001232 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001233 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001234 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001235 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001236 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001237 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001238
David Majnemerd065e232016-06-02 06:21:37 +00001239 return UnderlyingTypeIndex;
1240}
1241
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001242TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1243 DITypeRef ElementTypeRef = Ty->getBaseType();
1244 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1245 // IndexType is size_t, which depends on the bitness of the target.
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001246 TypeIndex IndexType = Asm->TM.getPointerSize() == 8
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001247 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1248 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001249
1250 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1251
Amjad Aboudacee5682016-07-12 12:06:34 +00001252 // Add subranges to array type.
1253 DINodeArray Elements = Ty->getElements();
1254 for (int i = Elements.size() - 1; i >= 0; --i) {
1255 const DINode *Element = Elements[i];
1256 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1257
1258 const DISubrange *Subrange = cast<DISubrange>(Element);
1259 assert(Subrange->getLowerBound() == 0 &&
1260 "codeview doesn't support subranges with lower bounds");
1261 int64_t Count = Subrange->getCount();
1262
1263 // Variable Length Array (VLA) has Count equal to '-1'.
1264 // Replace with Count '1', assume it is the minimum VLA length.
1265 // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
Reid Kleckner6b78e162017-03-24 23:28:42 +00001266 if (Count == -1)
Amjad Aboudacee5682016-07-12 12:06:34 +00001267 Count = 1;
Amjad Aboudacee5682016-07-12 12:06:34 +00001268
Amjad Aboudacee5682016-07-12 12:06:34 +00001269 // Update the element size and element type index for subsequent subranges.
1270 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001271
1272 // If this is the outermost array, use the size from the array. It will be
Reid Kleckner6b78e162017-03-24 23:28:42 +00001273 // more accurate if we had a VLA or an incomplete element type size.
Reid Kleckner10762882016-09-09 17:29:36 +00001274 uint64_t ArraySize =
1275 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1276
1277 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner4efa0a42016-11-08 22:24:53 +00001278 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1279 ElementTypeIndex = TypeTable.writeKnownType(AR);
Amjad Aboudacee5682016-07-12 12:06:34 +00001280 }
1281
Amjad Aboudacee5682016-07-12 12:06:34 +00001282 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001283}
1284
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001285TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1286 TypeIndex Index;
1287 dwarf::TypeKind Kind;
1288 uint32_t ByteSize;
1289
1290 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001291 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001292
1293 SimpleTypeKind STK = SimpleTypeKind::None;
1294 switch (Kind) {
1295 case dwarf::DW_ATE_address:
1296 // FIXME: Translate
1297 break;
1298 case dwarf::DW_ATE_boolean:
1299 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001300 case 1: STK = SimpleTypeKind::Boolean8; break;
1301 case 2: STK = SimpleTypeKind::Boolean16; break;
1302 case 4: STK = SimpleTypeKind::Boolean32; break;
1303 case 8: STK = SimpleTypeKind::Boolean64; break;
1304 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001305 }
1306 break;
1307 case dwarf::DW_ATE_complex_float:
1308 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001309 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001310 case 4: STK = SimpleTypeKind::Complex32; break;
1311 case 8: STK = SimpleTypeKind::Complex64; break;
1312 case 10: STK = SimpleTypeKind::Complex80; break;
1313 case 16: STK = SimpleTypeKind::Complex128; break;
1314 }
1315 break;
1316 case dwarf::DW_ATE_float:
1317 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001318 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001319 case 4: STK = SimpleTypeKind::Float32; break;
1320 case 6: STK = SimpleTypeKind::Float48; break;
1321 case 8: STK = SimpleTypeKind::Float64; break;
1322 case 10: STK = SimpleTypeKind::Float80; break;
1323 case 16: STK = SimpleTypeKind::Float128; break;
1324 }
1325 break;
1326 case dwarf::DW_ATE_signed:
1327 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001328 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1329 case 2: STK = SimpleTypeKind::Int16Short; break;
1330 case 4: STK = SimpleTypeKind::Int32; break;
1331 case 8: STK = SimpleTypeKind::Int64Quad; break;
1332 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001333 }
1334 break;
1335 case dwarf::DW_ATE_unsigned:
1336 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001337 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1338 case 2: STK = SimpleTypeKind::UInt16Short; break;
1339 case 4: STK = SimpleTypeKind::UInt32; break;
1340 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1341 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001342 }
1343 break;
1344 case dwarf::DW_ATE_UTF:
1345 switch (ByteSize) {
1346 case 2: STK = SimpleTypeKind::Character16; break;
1347 case 4: STK = SimpleTypeKind::Character32; break;
1348 }
1349 break;
1350 case dwarf::DW_ATE_signed_char:
1351 if (ByteSize == 1)
1352 STK = SimpleTypeKind::SignedCharacter;
1353 break;
1354 case dwarf::DW_ATE_unsigned_char:
1355 if (ByteSize == 1)
1356 STK = SimpleTypeKind::UnsignedCharacter;
1357 break;
1358 default:
1359 break;
1360 }
1361
1362 // Apply some fixups based on the source-level type name.
1363 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1364 STK = SimpleTypeKind::Int32Long;
1365 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1366 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001367 if (STK == SimpleTypeKind::UInt16Short &&
1368 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001369 STK = SimpleTypeKind::WideCharacter;
1370 if ((STK == SimpleTypeKind::SignedCharacter ||
1371 STK == SimpleTypeKind::UnsignedCharacter) &&
1372 Ty->getName() == "char")
1373 STK = SimpleTypeKind::NarrowCharacter;
1374
1375 return TypeIndex(STK);
1376}
1377
1378TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1379 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1380
1381 // Pointers to simple types can use SimpleTypeMode, rather than having a
1382 // dedicated pointer type record.
1383 if (PointeeTI.isSimple() &&
1384 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1385 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1386 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1387 ? SimpleTypeMode::NearPointer64
1388 : SimpleTypeMode::NearPointer32;
1389 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1390 }
1391
1392 PointerKind PK =
1393 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1394 PointerMode PM = PointerMode::Pointer;
1395 switch (Ty->getTag()) {
1396 default: llvm_unreachable("not a pointer tag type");
1397 case dwarf::DW_TAG_pointer_type:
1398 PM = PointerMode::Pointer;
1399 break;
1400 case dwarf::DW_TAG_reference_type:
1401 PM = PointerMode::LValueReference;
1402 break;
1403 case dwarf::DW_TAG_rvalue_reference_type:
1404 PM = PointerMode::RValueReference;
1405 break;
1406 }
1407 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1408 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1409 // do.
1410 PointerOptions PO = PointerOptions::None;
1411 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001412 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001413}
1414
Reid Kleckner6fa15462016-06-17 22:14:39 +00001415static PointerToMemberRepresentation
1416translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1417 // SizeInBytes being zero generally implies that the member pointer type was
1418 // incomplete, which can happen if it is part of a function prototype. In this
1419 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001420 if (IsPMF) {
1421 switch (Flags & DINode::FlagPtrToMemberRep) {
1422 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001423 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1424 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001425 case DINode::FlagSingleInheritance:
1426 return PointerToMemberRepresentation::SingleInheritanceFunction;
1427 case DINode::FlagMultipleInheritance:
1428 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1429 case DINode::FlagVirtualInheritance:
1430 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1431 }
1432 } else {
1433 switch (Flags & DINode::FlagPtrToMemberRep) {
1434 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001435 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1436 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001437 case DINode::FlagSingleInheritance:
1438 return PointerToMemberRepresentation::SingleInheritanceData;
1439 case DINode::FlagMultipleInheritance:
1440 return PointerToMemberRepresentation::MultipleInheritanceData;
1441 case DINode::FlagVirtualInheritance:
1442 return PointerToMemberRepresentation::VirtualInheritanceData;
1443 }
1444 }
1445 llvm_unreachable("invalid ptr to member representation");
1446}
1447
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001448TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1449 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1450 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001451 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001452 PointerKind PK = Asm->TM.getPointerSize() == 8 ? PointerKind::Near64
1453 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001454 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1455 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1456 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001457 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner6fa15462016-06-17 22:14:39 +00001458 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1459 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1460 MemberPointerInfo MPI(
1461 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001462 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001463 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001464}
1465
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001466/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1467/// have a translation, use the NearC convention.
1468static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1469 switch (DwarfCC) {
1470 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1471 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1472 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1473 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1474 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1475 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1476 }
1477 return CallingConvention::NearC;
1478}
1479
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001480TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1481 ModifierOptions Mods = ModifierOptions::None;
1482 bool IsModifier = true;
1483 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001484 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001485 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001486 switch (BaseTy->getTag()) {
1487 case dwarf::DW_TAG_const_type:
1488 Mods |= ModifierOptions::Const;
1489 break;
1490 case dwarf::DW_TAG_volatile_type:
1491 Mods |= ModifierOptions::Volatile;
1492 break;
1493 default:
1494 IsModifier = false;
1495 break;
1496 }
1497 if (IsModifier)
1498 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1499 }
1500 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001501 ModifierRecord MR(ModifiedTI, Mods);
1502 return TypeTable.writeKnownType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001503}
1504
David Majnemer75c3ebf2016-06-02 17:13:53 +00001505TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1506 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1507 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1508 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1509
1510 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1511 ArrayRef<TypeIndex> ArgTypeIndices = None;
1512 if (!ReturnAndArgTypeIndices.empty()) {
1513 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1514 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1515 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1516 }
1517
1518 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001519 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001520
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001521 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1522
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001523 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1524 ArgTypeIndices.size(), ArgListIndex);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001525 return TypeTable.writeKnownType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001526}
1527
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001528TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001529 const DIType *ClassTy,
1530 int ThisAdjustment) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001531 // Lower the containing class type.
1532 TypeIndex ClassType = getTypeIndex(ClassTy);
1533
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001534 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1535 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1536 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1537
1538 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1539 ArrayRef<TypeIndex> ArgTypeIndices = None;
1540 if (!ReturnAndArgTypeIndices.empty()) {
1541 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1542 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1543 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1544 }
1545 TypeIndex ThisTypeIndex = TypeIndex::Void();
1546 if (!ArgTypeIndices.empty()) {
1547 ThisTypeIndex = ArgTypeIndices.front();
1548 ArgTypeIndices = ArgTypeIndices.drop_front();
1549 }
1550
1551 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001552 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001553
1554 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1555
1556 // TODO: Need to use the correct values for:
1557 // FunctionOptions
1558 // ThisPointerAdjustment.
Zachary Turner4efa0a42016-11-08 22:24:53 +00001559 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
1560 FunctionOptions::None, ArgTypeIndices.size(),
1561 ArgListIndex, ThisAdjustment);
1562 TypeIndex TI = TypeTable.writeKnownType(MFR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001563
1564 return TI;
1565}
1566
Reid Kleckner9dac4732016-08-31 15:59:30 +00001567TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001568 unsigned VSlotCount =
1569 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
Reid Kleckner9dac4732016-08-31 15:59:30 +00001570 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001571
1572 VFTableShapeRecord VFTSR(Slots);
1573 return TypeTable.writeKnownType(VFTSR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001574}
1575
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001576static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1577 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001578 case DINode::FlagPrivate: return MemberAccess::Private;
1579 case DINode::FlagPublic: return MemberAccess::Public;
1580 case DINode::FlagProtected: return MemberAccess::Protected;
1581 case 0:
1582 // If there was no explicit access control, provide the default for the tag.
1583 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1584 : MemberAccess::Public;
1585 }
1586 llvm_unreachable("access flags are exclusive");
1587}
1588
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001589static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1590 if (SP->isArtificial())
1591 return MethodOptions::CompilerGenerated;
1592
1593 // FIXME: Handle other MethodOptions.
1594
1595 return MethodOptions::None;
1596}
1597
1598static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1599 bool Introduced) {
1600 switch (SP->getVirtuality()) {
1601 case dwarf::DW_VIRTUALITY_none:
1602 break;
1603 case dwarf::DW_VIRTUALITY_virtual:
1604 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1605 case dwarf::DW_VIRTUALITY_pure_virtual:
1606 return Introduced ? MethodKind::PureIntroducingVirtual
1607 : MethodKind::PureVirtual;
1608 default:
1609 llvm_unreachable("unhandled virtuality case");
1610 }
1611
1612 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1613
1614 return MethodKind::Vanilla;
1615}
1616
Reid Klecknera8d57402016-06-03 15:58:20 +00001617static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1618 switch (Ty->getTag()) {
1619 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1620 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1621 }
1622 llvm_unreachable("unexpected tag");
1623}
1624
Reid Klecknere092dad2016-07-02 00:11:07 +00001625/// Return ClassOptions that should be present on both the forward declaration
1626/// and the defintion of a tag type.
1627static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1628 ClassOptions CO = ClassOptions::None;
1629
1630 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001631 // appear to give every type a linkage name, which may be problematic for us.
1632 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001633 if (!Ty->getIdentifier().empty())
1634 CO |= ClassOptions::HasUniqueName;
1635
1636 // Put the Nested flag on a type if it appears immediately inside a tag type.
1637 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1638 // here. That flag is only set on definitions, and not forward declarations.
1639 const DIScope *ImmediateScope = Ty->getScope().resolve();
1640 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1641 CO |= ClassOptions::Nested;
1642
1643 // Put the Scoped flag on function-local types.
1644 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1645 Scope = Scope->getScope().resolve()) {
1646 if (isa<DISubprogram>(Scope)) {
1647 CO |= ClassOptions::Scoped;
1648 break;
1649 }
1650 }
1651
1652 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001653}
1654
David Majnemer979cb882016-06-16 21:32:16 +00001655TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001656 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001657 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001658 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001659
David Majnemerda9548f2016-06-17 16:13:21 +00001660 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001661 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001662 } else {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001663 FieldListRecordBuilder FLRB(TypeTable);
1664
1665 FLRB.begin();
David Majnemerda9548f2016-06-17 16:13:21 +00001666 for (const DINode *Element : Ty->getElements()) {
1667 // We assume that the frontend provides all members in source declaration
1668 // order, which is what MSVC does.
1669 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001670 EnumeratorRecord ER(MemberAccess::Public,
1671 APSInt::getUnsigned(Enumerator->getValue()),
1672 Enumerator->getName());
1673 FLRB.writeMemberType(ER);
David Majnemerda9548f2016-06-17 16:13:21 +00001674 EnumeratorCount++;
1675 }
1676 }
Zachary Turner7f97c362017-05-25 21:15:37 +00001677 FTI = FLRB.end(true);
David Majnemerda9548f2016-06-17 16:13:21 +00001678 }
David Majnemer979cb882016-06-16 21:32:16 +00001679
David Majnemer6bdc24e2016-07-01 23:12:45 +00001680 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001681
Zachary Turner4efa0a42016-11-08 22:24:53 +00001682 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
1683 getTypeIndex(Ty->getBaseType()));
1684 return TypeTable.writeKnownType(ER);
David Majnemer979cb882016-06-16 21:32:16 +00001685}
1686
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001687//===----------------------------------------------------------------------===//
1688// ClassInfo
1689//===----------------------------------------------------------------------===//
1690
1691struct llvm::ClassInfo {
1692 struct MemberInfo {
1693 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00001694 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001695 };
1696 // [MemberInfo]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001697 using MemberList = std::vector<MemberInfo>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001698
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001699 using MethodsList = TinyPtrVector<const DISubprogram *>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001700 // MethodName -> MethodsList
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001701 using MethodsMap = MapVector<MDString *, MethodsList>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001702
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001703 /// Base classes.
1704 std::vector<const DIDerivedType *> Inheritance;
1705
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001706 /// Direct members.
1707 MemberList Members;
1708 // Direct overloaded methods gathered by name.
1709 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001710
Reid Kleckner9dac4732016-08-31 15:59:30 +00001711 TypeIndex VShapeTI;
1712
Reid Klecknere2e82062017-08-08 20:30:14 +00001713 std::vector<const DIType *> NestedTypes;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001714};
1715
1716void CodeViewDebug::clear() {
1717 assert(CurFn == nullptr);
1718 FileIdMap.clear();
1719 FnDebugInfo.clear();
1720 FileToFilepathMap.clear();
1721 LocalUDTs.clear();
1722 GlobalUDTs.clear();
1723 TypeIndices.clear();
1724 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001725}
1726
1727void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1728 const DIDerivedType *DDTy) {
1729 if (!DDTy->getName().empty()) {
1730 Info.Members.push_back({DDTy, 0});
1731 return;
1732 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001733 // An unnamed member must represent a nested struct or union. Add all the
1734 // indirect fields to the current record.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001735 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00001736 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001737 const DIType *Ty = DDTy->getBaseType().resolve();
Reid Kleckner9ff936c2016-06-21 14:56:24 +00001738 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001739 ClassInfo NestedInfo = collectClassInfo(DCTy);
1740 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001741 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001742 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001743}
1744
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001745ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1746 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001747 // Add elements to structure type.
1748 DINodeArray Elements = Ty->getElements();
1749 for (auto *Element : Elements) {
1750 // We assume that the frontend provides all members in source declaration
1751 // order, which is what MSVC does.
1752 if (!Element)
1753 continue;
1754 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001755 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001756 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001757 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001758 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001759 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1760 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001761 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1762 DDTy->getName() == "__vtbl_ptr_type") {
1763 Info.VShapeTI = getTypeIndex(DDTy);
Reid Klecknere2e82062017-08-08 20:30:14 +00001764 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
1765 Info.NestedTypes.push_back(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001766 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1767 // Ignore friend members. It appears that MSVC emitted info about
1768 // friends in the past, but modern versions do not.
1769 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001770 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
Reid Klecknere2e82062017-08-08 20:30:14 +00001771 Info.NestedTypes.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001772 }
1773 // Skip other unrecognized kinds of elements.
1774 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001775 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001776}
1777
Reid Klecknera8d57402016-06-03 15:58:20 +00001778TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1779 // First, construct the forward decl. Don't look into Ty to compute the
1780 // forward decl options, since it might not be available in all TUs.
1781 TypeRecordKind Kind = getRecordKind(Ty);
1782 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001783 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001784 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001785 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
1786 FullName, Ty->getIdentifier());
1787 TypeIndex FwdDeclTI = TypeTable.writeKnownType(CR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001788 if (!Ty->isForwardDecl())
1789 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001790 return FwdDeclTI;
1791}
1792
1793TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1794 // Construct the field list and complete type record.
1795 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00001796 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001797 TypeIndex FieldTI;
1798 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001799 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001800 bool ContainsNestedClass;
1801 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1802 lowerRecordFieldList(Ty);
1803
1804 if (ContainsNestedClass)
1805 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00001806
David Majnemer6bdc24e2016-07-01 23:12:45 +00001807 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001808
Reid Klecknera8d57402016-06-03 15:58:20 +00001809 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00001810
Zachary Turner4efa0a42016-11-08 22:24:53 +00001811 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
1812 SizeInBytes, FullName, Ty->getIdentifier());
1813 TypeIndex ClassTI = TypeTable.writeKnownType(CR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001814
Saleem Abdulrasool87f03382017-05-03 21:39:01 +00001815 if (const auto *File = Ty->getFile()) {
1816 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
1817 TypeIndex SIDI = TypeTable.writeKnownType(SIDR);
1818 UdtSourceLineRecord USLR(ClassTI, SIDI, Ty->getLine());
1819 TypeTable.writeKnownType(USLR);
1820 }
Hans Wennborg9a519a02016-06-22 21:22:13 +00001821
Zachary Turnera7b04172017-08-28 18:49:04 +00001822 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001823
Hans Wennborg9a519a02016-06-22 21:22:13 +00001824 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001825}
1826
1827TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1828 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001829 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001830 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001831 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
1832 TypeIndex FwdDeclTI = TypeTable.writeKnownType(UR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001833 if (!Ty->isForwardDecl())
1834 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001835 return FwdDeclTI;
1836}
1837
1838TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00001839 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001840 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001841 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001842 bool ContainsNestedClass;
1843 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1844 lowerRecordFieldList(Ty);
1845
1846 if (ContainsNestedClass)
1847 CO |= ClassOptions::ContainsNestedClass;
1848
Reid Klecknera8d57402016-06-03 15:58:20 +00001849 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00001850 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001851
Zachary Turner4efa0a42016-11-08 22:24:53 +00001852 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
1853 Ty->getIdentifier());
1854 TypeIndex UnionTI = TypeTable.writeKnownType(UR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001855
Zachary Turner4efa0a42016-11-08 22:24:53 +00001856 StringIdRecord SIR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
1857 TypeIndex SIRI = TypeTable.writeKnownType(SIR);
1858 UdtSourceLineRecord USLR(UnionTI, SIRI, Ty->getLine());
1859 TypeTable.writeKnownType(USLR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001860
Zachary Turnera7b04172017-08-28 18:49:04 +00001861 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001862
Hans Wennborg9a519a02016-06-22 21:22:13 +00001863 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001864}
1865
Adrian McCarthy820ca542016-07-06 19:49:51 +00001866std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00001867CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1868 // Manually count members. MSVC appears to count everything that generates a
1869 // field list record. Each individual overload in a method overload group
1870 // contributes to this count, even though the overload group is a single field
1871 // list record.
1872 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001873 ClassInfo Info = collectClassInfo(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001874 FieldListRecordBuilder FLBR(TypeTable);
1875 FLBR.begin();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001876
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001877 // Create base classes.
1878 for (const DIDerivedType *I : Info.Inheritance) {
1879 if (I->getFlags() & DINode::FlagVirtual) {
1880 // Virtual base.
1881 // FIXME: Emit VBPtrOffset when the frontend provides it.
1882 unsigned VBPtrOffset = 0;
1883 // FIXME: Despite the accessor name, the offset is really in bytes.
1884 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00001885 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
1886 ? TypeRecordKind::IndirectVirtualBaseClass
1887 : TypeRecordKind::VirtualBaseClass;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001888 VirtualBaseClassRecord VBCR(
Bob Haarman26a87bd2016-10-25 22:11:52 +00001889 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001890 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
Zachary Turner4efa0a42016-11-08 22:24:53 +00001891 VBTableIndex);
1892
1893 FLBR.writeMemberType(VBCR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001894 } else {
1895 assert(I->getOffsetInBits() % 8 == 0 &&
1896 "bases must be on byte boundaries");
Zachary Turner4efa0a42016-11-08 22:24:53 +00001897 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
1898 getTypeIndex(I->getBaseType()),
1899 I->getOffsetInBits() / 8);
1900 FLBR.writeMemberType(BCR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001901 }
1902 }
1903
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001904 // Create members.
1905 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1906 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1907 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00001908 StringRef MemberName = Member->getName();
1909 MemberAccess Access =
1910 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001911
1912 if (Member->isStaticMember()) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001913 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
1914 FLBR.writeMemberType(SDMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001915 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001916 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00001917 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001918
Reid Kleckner9dac4732016-08-31 15:59:30 +00001919 // Virtual function pointer member.
1920 if ((Member->getFlags() & DINode::FlagArtificial) &&
1921 Member->getName().startswith("_vptr$")) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001922 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
1923 FLBR.writeMemberType(VFPR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001924 MemberCount++;
1925 continue;
1926 }
1927
David Majnemer9319cbc2016-06-30 03:00:20 +00001928 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00001929 uint64_t MemberOffsetInBits =
1930 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001931 if (Member->isBitField()) {
1932 uint64_t StartBitOffset = MemberOffsetInBits;
1933 if (const auto *CI =
1934 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00001935 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001936 }
1937 StartBitOffset -= MemberOffsetInBits;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001938 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
1939 StartBitOffset);
1940 MemberBaseType = TypeTable.writeKnownType(BFR);
David Majnemer9319cbc2016-06-30 03:00:20 +00001941 }
1942 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001943 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
1944 MemberName);
1945 FLBR.writeMemberType(DMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001946 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001947 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001948
1949 // Create methods
1950 for (auto &MethodItr : Info.Methods) {
1951 StringRef Name = MethodItr.first->getString();
1952
1953 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00001954 for (const DISubprogram *SP : MethodItr.second) {
1955 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1956 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001957
1958 unsigned VFTableOffset = -1;
1959 if (Introduced)
1960 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1961
Zachary Turner7251ede2016-11-02 17:05:19 +00001962 Methods.push_back(OneMethodRecord(
1963 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
1964 translateMethodKindFlags(SP, Introduced),
1965 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001966 MemberCount++;
1967 }
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001968 assert(!Methods.empty() && "Empty methods map entry");
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001969 if (Methods.size() == 1)
Zachary Turner4efa0a42016-11-08 22:24:53 +00001970 FLBR.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001971 else {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001972 MethodOverloadListRecord MOLR(Methods);
1973 TypeIndex MethodList = TypeTable.writeKnownType(MOLR);
1974 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
1975 FLBR.writeMemberType(OMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001976 }
1977 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001978
1979 // Create nested classes.
Reid Klecknere2e82062017-08-08 20:30:14 +00001980 for (const DIType *Nested : Info.NestedTypes) {
Adrian McCarthy820ca542016-07-06 19:49:51 +00001981 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner4efa0a42016-11-08 22:24:53 +00001982 FLBR.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00001983 MemberCount++;
1984 }
1985
Zachary Turner7f97c362017-05-25 21:15:37 +00001986 TypeIndex FieldTI = FLBR.end(true);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001987 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Reid Klecknere2e82062017-08-08 20:30:14 +00001988 !Info.NestedTypes.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00001989}
1990
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001991TypeIndex CodeViewDebug::getVBPTypeIndex() {
1992 if (!VBPType.getIndex()) {
1993 // Make a 'const int *' type.
1994 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001995 TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001996
1997 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1998 : PointerKind::Near32;
1999 PointerMode PM = PointerMode::Pointer;
2000 PointerOptions PO = PointerOptions::None;
2001 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
2002
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00002003 VBPType = TypeTable.writeKnownType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002004 }
2005
2006 return VBPType;
2007}
2008
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002009TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002010 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002011 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002012
2013 // The null DIType is the void type. Don't try to hash it.
2014 if (!Ty)
2015 return TypeIndex::Void();
2016
Reid Klecknera8d57402016-06-03 15:58:20 +00002017 // Check if we've already translated this type. Don't try to do a
2018 // get-or-create style insertion that caches the hash lookup across the
2019 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002020 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002021 if (I != TypeIndices.end())
2022 return I->second;
2023
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002024 TypeLoweringScope S(*this);
2025 TypeIndex TI = lowerType(Ty, ClassTy);
2026 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002027}
2028
Bob Haarman223303c2017-08-29 20:59:25 +00002029TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
2030 DIType *Ty = TypeRef.resolve();
2031 PointerRecord PR(getTypeIndex(Ty),
2032 getPointerSizeInBytes() == 8 ? PointerKind::Near64
2033 : PointerKind::Near32,
2034 PointerMode::LValueReference, PointerOptions::None,
2035 Ty->getSizeInBits() / 8);
2036 return TypeTable.writeKnownType(PR);
2037}
2038
Reid Klecknera8d57402016-06-03 15:58:20 +00002039TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
2040 const DIType *Ty = TypeRef.resolve();
2041
2042 // The null DIType is the void type. Don't try to hash it.
2043 if (!Ty)
2044 return TypeIndex::Void();
2045
2046 // If this is a non-record type, the complete type index is the same as the
2047 // normal type index. Just call getTypeIndex.
2048 switch (Ty->getTag()) {
2049 case dwarf::DW_TAG_class_type:
2050 case dwarf::DW_TAG_structure_type:
2051 case dwarf::DW_TAG_union_type:
2052 break;
2053 default:
2054 return getTypeIndex(Ty);
2055 }
2056
2057 // Check if we've already translated the complete record type. Lowering a
2058 // complete type should never trigger lowering another complete type, so we
2059 // can reuse the hash table lookup result.
2060 const auto *CTy = cast<DICompositeType>(Ty);
2061 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2062 if (!InsertResult.second)
2063 return InsertResult.first->second;
2064
Reid Kleckner643dd832016-06-22 17:15:28 +00002065 TypeLoweringScope S(*this);
2066
Reid Klecknera8d57402016-06-03 15:58:20 +00002067 // Make sure the forward declaration is emitted first. It's unclear if this
2068 // is necessary, but MSVC does it, and we should follow suit until we can show
2069 // otherwise.
2070 TypeIndex FwdDeclTI = getTypeIndex(CTy);
2071
2072 // Just use the forward decl if we don't have complete type info. This might
2073 // happen if the frontend is using modules and expects the complete definition
2074 // to be emitted elsewhere.
2075 if (CTy->isForwardDecl())
2076 return FwdDeclTI;
2077
2078 TypeIndex TI;
2079 switch (CTy->getTag()) {
2080 case dwarf::DW_TAG_class_type:
2081 case dwarf::DW_TAG_structure_type:
2082 TI = lowerCompleteTypeClass(CTy);
2083 break;
2084 case dwarf::DW_TAG_union_type:
2085 TI = lowerCompleteTypeUnion(CTy);
2086 break;
2087 default:
2088 llvm_unreachable("not a record");
2089 }
2090
2091 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002092 return TI;
2093}
2094
Reid Kleckner643dd832016-06-22 17:15:28 +00002095/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00002096/// and do this until fixpoint, as each complete record type typically
2097/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00002098/// many other record types.
2099void CodeViewDebug::emitDeferredCompleteTypes() {
2100 SmallVector<const DICompositeType *, 4> TypesToEmit;
2101 while (!DeferredCompleteTypes.empty()) {
2102 std::swap(DeferredCompleteTypes, TypesToEmit);
2103 for (const DICompositeType *RecordTy : TypesToEmit)
2104 getCompleteTypeIndex(RecordTy);
2105 TypesToEmit.clear();
2106 }
2107}
2108
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002109void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
2110 // Get the sorted list of parameters and emit them first.
2111 SmallVector<const LocalVariable *, 6> Params;
2112 for (const LocalVariable &L : Locals)
2113 if (L.DIVar->isParameter())
2114 Params.push_back(&L);
2115 std::sort(Params.begin(), Params.end(),
2116 [](const LocalVariable *L, const LocalVariable *R) {
2117 return L->DIVar->getArg() < R->DIVar->getArg();
2118 });
2119 for (const LocalVariable *L : Params)
2120 emitLocalVariable(*L);
2121
2122 // Next emit all non-parameters in the order that we found them.
2123 for (const LocalVariable &L : Locals)
2124 if (!L.DIVar->isParameter())
2125 emitLocalVariable(L);
2126}
2127
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002128void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
2129 // LocalSym record, see SymbolRecord.h for more info.
2130 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2131 *LocalEnd = MMI->getContext().createTempSymbol();
2132 OS.AddComment("Record length");
2133 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2134 OS.EmitLabel(LocalBegin);
2135
2136 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00002137 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002138
Zachary Turner63a28462016-05-17 23:50:21 +00002139 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002140 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002141 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002142 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002143 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002144
2145 OS.AddComment("TypeIndex");
Reid Kleckner08f5fd52017-08-31 15:56:49 +00002146 TypeIndex TI = Var.UseReferenceType
2147 ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2148 : getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002149 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002150 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002151 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002152 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002153 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002154 OS.EmitLabel(LocalEnd);
2155
Reid Kleckner876330d2016-02-12 21:48:30 +00002156 // Calculate the on disk prefix of the appropriate def range record. The
2157 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2158 // should be big enough to hold all forms without memory allocation.
2159 SmallString<20> BytePrefix;
2160 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2161 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002162 if (DefRange.InMemory) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002163 uint16_t RegRelFlags = 0;
2164 if (DefRange.IsSubfield) {
2165 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2166 (DefRange.StructOffset
2167 << DefRangeRegisterRelSym::OffsetInParentShift);
2168 }
Zachary Turner46225b12016-12-16 22:48:14 +00002169 DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
2170 Sym.Hdr.Register = DefRange.CVRegister;
2171 Sym.Hdr.Flags = RegRelFlags;
2172 Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +00002173 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00002174 BytePrefix +=
2175 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00002176 BytePrefix +=
Zachary Turner46225b12016-12-16 22:48:14 +00002177 StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
Reid Kleckner876330d2016-02-12 21:48:30 +00002178 } else {
2179 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002180 if (DefRange.IsSubfield) {
2181 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002182 DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
2183 Sym.Hdr.Register = DefRange.CVRegister;
2184 Sym.Hdr.MayHaveNoName = 0;
2185 Sym.Hdr.OffsetInParent = DefRange.StructOffset;
2186
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002187 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2188 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2189 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002190 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2191 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002192 } else {
2193 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002194 DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
2195 Sym.Hdr.Register = DefRange.CVRegister;
2196 Sym.Hdr.MayHaveNoName = 0;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002197 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2198 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2199 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002200 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2201 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002202 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002203 }
2204 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2205 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002206}
2207
David Blaikieb2fbb4b2017-02-16 18:48:33 +00002208void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002209 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00002210 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002211 assert(CurFn == &FnDebugInfo[GV]);
2212
Pete Cooperadebb932016-03-11 02:14:16 +00002213 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002214
Reid Kleckner2214ed82016-01-29 00:49:42 +00002215 // Don't emit anything if we don't have any line tables.
2216 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002217 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002218 CurFn = nullptr;
2219 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002220 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002221
Reid Klecknere33c94f2017-09-05 20:14:58 +00002222 CurFn->Annotations = MF->getCodeViewAnnotations();
2223
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002224 CurFn->End = Asm->getFunctionEnd();
2225
Craig Topper353eda42014-04-24 06:44:33 +00002226 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002227}
2228
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002229void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002230 DebugHandlerBase::beginInstruction(MI);
2231
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002232 // Ignore DBG_VALUE locations and function prologue.
David Majnemer67f684e2016-07-28 05:03:22 +00002233 if (!Asm || !CurFn || MI->isDebugValue() ||
2234 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002235 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002236
2237 // If the first instruction of a new MBB has no location, find the first
2238 // instruction with a location and use that.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002239 DebugLoc DL = MI->getDebugLoc();
Reid Kleckner45a74622017-06-30 21:33:44 +00002240 if (!DL && MI->getParent() != PrevInstBB) {
2241 for (const auto &NextMI : *MI->getParent()) {
Reid Kleckner2de471d2017-07-31 21:03:08 +00002242 if (NextMI.isDebugValue())
2243 continue;
Reid Kleckner45a74622017-06-30 21:33:44 +00002244 DL = NextMI.getDebugLoc();
2245 if (DL)
2246 break;
2247 }
2248 }
2249 PrevInstBB = MI->getParent();
2250
2251 // If we still don't have a debug location, don't record a location.
2252 if (!DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002253 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002254
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002255 maybeRecordLocation(DL, Asm->MF);
2256}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002257
Zachary Turner8c099fe2017-05-30 16:36:15 +00002258MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002259 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2260 *EndLabel = MMI->getContext().createTempSymbol();
2261 OS.EmitIntValue(unsigned(Kind), 4);
2262 OS.AddComment("Subsection size");
2263 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2264 OS.EmitLabel(BeginLabel);
2265 return EndLabel;
2266}
2267
2268void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2269 OS.EmitLabel(EndLabel);
2270 // Every subsection must be aligned to a 4-byte boundary.
2271 OS.EmitValueToAlignment(4);
2272}
2273
David Majnemer3128b102016-06-15 18:00:01 +00002274void CodeViewDebug::emitDebugInfoForUDTs(
Zachary Turnera7b04172017-08-28 18:49:04 +00002275 ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2276 for (const auto &UDT : UDTs) {
2277 const DIType *T = UDT.second;
2278 assert(shouldEmitUdt(T));
2279
David Majnemer3128b102016-06-15 18:00:01 +00002280 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2281 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2282 OS.AddComment("Record length");
2283 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2284 OS.EmitLabel(UDTRecordBegin);
2285
2286 OS.AddComment("Record kind: S_UDT");
2287 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2288
2289 OS.AddComment("Type");
Zachary Turnera7b04172017-08-28 18:49:04 +00002290 OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
David Majnemer3128b102016-06-15 18:00:01 +00002291
2292 emitNullTerminatedSymbolName(OS, UDT.first);
2293 OS.EmitLabel(UDTRecordEnd);
2294 }
2295}
2296
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002297void CodeViewDebug::emitDebugInfoForGlobals() {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002298 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2299 GlobalMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002300 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002301 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2302 GV.getDebugInfo(GVEs);
2303 for (const auto *GVE : GVEs)
2304 GlobalMap[GVE] = &GV;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002305 }
2306
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002307 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2308 for (const MDNode *Node : CUs->operands()) {
2309 const auto *CU = cast<DICompileUnit>(Node);
2310
2311 // First, emit all globals that are not in a comdat in a single symbol
2312 // substream. MSVC doesn't like it if the substream is empty, so only open
2313 // it if we have at least one global to emit.
2314 switchToDebugSectionForSymbol(nullptr);
2315 MCSymbol *EndLabel = nullptr;
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002316 for (const auto *GVE : CU->getGlobalVariables()) {
2317 if (const auto *GV = GlobalMap.lookup(GVE))
David Majnemer577be0f2016-06-15 00:19:52 +00002318 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002319 if (!EndLabel) {
2320 OS.AddComment("Symbol subsection for globals");
Zachary Turner8c099fe2017-05-30 16:36:15 +00002321 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002322 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002323 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2324 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002325 }
2326 }
2327 if (EndLabel)
2328 endCVSubsection(EndLabel);
2329
2330 // Second, emit each global that is in a comdat into its own .debug$S
2331 // section along with its own symbol substream.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002332 for (const auto *GVE : CU->getGlobalVariables()) {
2333 if (const auto *GV = GlobalMap.lookup(GVE)) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002334 if (GV->hasComdat()) {
2335 MCSymbol *GVSym = Asm->getSymbol(GV);
2336 OS.AddComment("Symbol subsection for " +
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00002337 Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002338 switchToDebugSectionForSymbol(GVSym);
Zachary Turner8c099fe2017-05-30 16:36:15 +00002339 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002340 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2341 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002342 endCVSubsection(EndLabel);
2343 }
2344 }
2345 }
2346 }
2347}
2348
Hans Wennborgb510b452016-06-23 16:33:53 +00002349void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2350 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2351 for (const MDNode *Node : CUs->operands()) {
2352 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2353 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2354 getTypeIndex(RT);
2355 // FIXME: Add to global/local DTU list.
2356 }
2357 }
2358 }
2359}
2360
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002361void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002362 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002363 MCSymbol *GVSym) {
2364 // DataSym record, see SymbolRecord.h for more info.
2365 // FIXME: Thread local data, etc
2366 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2367 *DataEnd = MMI->getContext().createTempSymbol();
2368 OS.AddComment("Record length");
2369 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2370 OS.EmitLabel(DataBegin);
David Majnemer7abd2692016-07-06 21:07:47 +00002371 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002372 if (GV->isThreadLocal()) {
2373 OS.AddComment("Record kind: S_LTHREAD32");
2374 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2375 } else {
2376 OS.AddComment("Record kind: S_LDATA32");
2377 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2378 }
David Majnemer7abd2692016-07-06 21:07:47 +00002379 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002380 if (GV->isThreadLocal()) {
2381 OS.AddComment("Record kind: S_GTHREAD32");
2382 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2383 } else {
2384 OS.AddComment("Record kind: S_GDATA32");
2385 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2386 }
David Majnemer7abd2692016-07-06 21:07:47 +00002387 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002388 OS.AddComment("Type");
2389 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2390 OS.AddComment("DataOffset");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00002391 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002392 OS.AddComment("Segment");
2393 OS.EmitCOFFSectionIndex(GVSym);
2394 OS.AddComment("Name");
2395 emitNullTerminatedSymbolName(OS, DIGV->getName());
2396 OS.EmitLabel(DataEnd);
2397}