blob: 52d7b45d37b571f62ea8d30fae51b35bbd7adb19 [file] [log] [blame]
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001//===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp --*- C++ -*--===//
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Reid Kleckner70f5bc92016-01-14 19:25:04 +000010// This file contains support for writing Microsoft CodeView debug info.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000011//
12//===----------------------------------------------------------------------===//
13
Reid Kleckner70f5bc92016-01-14 19:25:04 +000014#include "CodeViewDebug.h"
Reid Kleckner156a7232016-06-22 18:31:14 +000015#include "llvm/ADT/TinyPtrVector.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000016#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000017#include "llvm/DebugInfo/CodeView/CodeView.h"
Reid Klecknera8d57402016-06-03 15:58:20 +000018#include "llvm/DebugInfo/CodeView/FieldListRecordBuilder.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000019#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000020#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000021#include "llvm/DebugInfo/CodeView/TypeDumper.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000022#include "llvm/DebugInfo/CodeView/TypeIndex.h"
23#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000024#include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
Zachary Turnera3225b02016-07-29 20:56:36 +000025#include "llvm/DebugInfo/MSF/ByteStream.h"
26#include "llvm/DebugInfo/MSF/StreamReader.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000027#include "llvm/IR/Constants.h"
Reid Kleckner46cb48c2016-07-27 16:03:57 +000028#include "llvm/MC/MCAsmInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000029#include "llvm/MC/MCExpr.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000030#include "llvm/MC/MCSectionCOFF.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000031#include "llvm/MC/MCSymbol.h"
32#include "llvm/Support/COFF.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000033#include "llvm/Support/ScopedPrinter.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000034#include "llvm/Target/TargetFrameLowering.h"
Amjad Aboud76c9eb92016-06-18 10:25:07 +000035#include "llvm/Target/TargetRegisterInfo.h"
36#include "llvm/Target/TargetSubtargetInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000037
Reid Klecknerf9c275f2016-02-10 20:55:49 +000038using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000039using namespace llvm::codeview;
Zachary Turnerbac69d32016-07-22 19:56:05 +000040using namespace llvm::msf;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000041
Reid Klecknerf9c275f2016-02-10 20:55:49 +000042CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
43 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
44 // If module doesn't have named metadata anchors or COFF debug section
45 // is not available, skip any debug info related stuff.
46 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
47 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
48 Asm = nullptr;
49 return;
50 }
51
52 // Tell MMI that we have debug info.
53 MMI->setDebugInfoAvailability(true);
54}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000055
Reid Kleckner9533af42016-01-16 00:09:09 +000056StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
57 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000058 if (!Filepath.empty())
59 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000060
Reid Kleckner9533af42016-01-16 00:09:09 +000061 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
62
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000063 // Clang emits directory and relative filename info into the IR, but CodeView
64 // operates on full paths. We could change Clang to emit full paths too, but
65 // that would increase the IR size and probably not needed for other users.
66 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000067 if (Filename.find(':') == 1)
68 Filepath = Filename;
69 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +000070 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000071
72 // Canonicalize the path. We have to do it textually because we may no longer
73 // have access the file in the filesystem.
74 // First, replace all slashes with backslashes.
75 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
76
77 // Remove all "\.\" with "\".
78 size_t Cursor = 0;
79 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
80 Filepath.erase(Cursor, 2);
81
82 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
83 // path should be well-formatted, e.g. start with a drive letter, etc.
84 Cursor = 0;
85 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
86 // Something's wrong if the path starts with "\..\", abort.
87 if (Cursor == 0)
88 break;
89
90 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
91 if (PrevSlash == std::string::npos)
92 // Something's wrong, abort.
93 break;
94
95 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
96 // The next ".." might be following the one we've just erased.
97 Cursor = PrevSlash;
98 }
99
100 // Remove all duplicate backslashes.
101 Cursor = 0;
102 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
103 Filepath.erase(Cursor, 1);
104
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000105 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000106}
107
Reid Kleckner2214ed82016-01-29 00:49:42 +0000108unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
109 unsigned NextId = FileIdMap.size() + 1;
110 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
111 if (Insertion.second) {
112 // We have to compute the full filepath and emit a .cv_file directive.
113 StringRef FullPath = getFullFilepath(F);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000114 NextId = OS.EmitCVFileDirective(NextId, FullPath);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000115 assert(NextId == FileIdMap.size() && ".cv_file directive failed");
116 }
117 return Insertion.first->second;
118}
119
Reid Kleckner876330d2016-02-12 21:48:30 +0000120CodeViewDebug::InlineSite &
121CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
122 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000123 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
124 InlineSite *Site = &SiteInsertion.first->second;
125 if (SiteInsertion.second) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000126 Site->SiteFuncId = NextFuncId++;
Reid Kleckner876330d2016-02-12 21:48:30 +0000127 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000128 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000129 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000130 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000131 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000132}
133
David Majnemer6bdc24e2016-07-01 23:12:45 +0000134static StringRef getPrettyScopeName(const DIScope *Scope) {
135 StringRef ScopeName = Scope->getName();
136 if (!ScopeName.empty())
137 return ScopeName;
138
139 switch (Scope->getTag()) {
140 case dwarf::DW_TAG_enumeration_type:
141 case dwarf::DW_TAG_class_type:
142 case dwarf::DW_TAG_structure_type:
143 case dwarf::DW_TAG_union_type:
144 return "<unnamed-tag>";
145 case dwarf::DW_TAG_namespace:
146 return "`anonymous namespace'";
147 }
148
149 return StringRef();
150}
151
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000152static const DISubprogram *getQualifiedNameComponents(
153 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
154 const DISubprogram *ClosestSubprogram = nullptr;
155 while (Scope != nullptr) {
156 if (ClosestSubprogram == nullptr)
157 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000158 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000159 if (!ScopeName.empty())
160 QualifiedNameComponents.push_back(ScopeName);
161 Scope = Scope->getScope().resolve();
162 }
163 return ClosestSubprogram;
164}
165
166static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
167 StringRef TypeName) {
168 std::string FullyQualifiedName;
169 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
170 FullyQualifiedName.append(QualifiedNameComponent);
171 FullyQualifiedName.append("::");
172 }
173 FullyQualifiedName.append(TypeName);
174 return FullyQualifiedName;
175}
176
177static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
178 SmallVector<StringRef, 5> QualifiedNameComponents;
179 getQualifiedNameComponents(Scope, QualifiedNameComponents);
180 return getQualifiedName(QualifiedNameComponents, Name);
181}
182
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000183struct CodeViewDebug::TypeLoweringScope {
184 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
185 ~TypeLoweringScope() {
186 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
187 // inner TypeLoweringScopes don't attempt to emit deferred types.
188 if (CVD.TypeEmissionLevel == 1)
189 CVD.emitDeferredCompleteTypes();
190 --CVD.TypeEmissionLevel;
191 }
192 CodeViewDebug &CVD;
193};
194
David Majnemer6bdc24e2016-07-01 23:12:45 +0000195static std::string getFullyQualifiedName(const DIScope *Ty) {
196 const DIScope *Scope = Ty->getScope().resolve();
197 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
198}
199
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000200TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
201 // No scope means global scope and that uses the zero index.
202 if (!Scope || isa<DIFile>(Scope))
203 return TypeIndex();
204
205 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
206
207 // Check if we've already translated this scope.
208 auto I = TypeIndices.find({Scope, nullptr});
209 if (I != TypeIndices.end())
210 return I->second;
211
212 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000213 std::string ScopeName = getFullyQualifiedName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000214 TypeIndex TI =
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000215 TypeTable.writeKnownType(StringIdRecord(TypeIndex(), ScopeName));
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000216 return recordTypeIndexForDINode(Scope, TI);
217}
218
David Majnemer75c3ebf2016-06-02 17:13:53 +0000219TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000220 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000221
David Majnemer75c3ebf2016-06-02 17:13:53 +0000222 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000223 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000224 if (I != TypeIndices.end())
225 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000226
Reid Klecknerac945e22016-06-17 16:11:20 +0000227 // The display name includes function template arguments. Drop them to match
228 // MSVC.
229 StringRef DisplayName = SP->getDisplayName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000230
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000231 const DIScope *Scope = SP->getScope().resolve();
232 TypeIndex TI;
233 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
234 // If the scope is a DICompositeType, then this must be a method. Member
235 // function types take some special handling, and require access to the
236 // subprogram.
237 TypeIndex ClassType = getTypeIndex(Class);
238 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
239 DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000240 TI = TypeTable.writeKnownType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000241 } else {
242 // Otherwise, this must be a free function.
243 TypeIndex ParentScope = getScopeIndex(Scope);
244 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000245 TI = TypeTable.writeKnownType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000246 }
247
248 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000249}
250
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000251TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
252 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000253 // Always use the method declaration as the key for the function type. The
254 // method declaration contains the this adjustment.
255 if (SP->getDeclaration())
256 SP = SP->getDeclaration();
257 assert(!SP->getDeclaration() && "should use declaration as key");
258
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000259 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
260 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000261 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000262 if (I != TypeIndices.end())
263 return I->second;
264
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000265 // Make sure complete type info for the class is emitted *after* the member
266 // function type, as the complete class type is likely to reference this
267 // member function type.
268 TypeLoweringScope S(*this);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000269 TypeIndex TI =
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000270 lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000271 return recordTypeIndexForDINode(SP, TI, Class);
272}
273
Amjad Aboudacee5682016-07-12 12:06:34 +0000274TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
275 TypeIndex TI,
276 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000277 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000278 (void)InsertResult;
279 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000280 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000281}
282
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000283unsigned CodeViewDebug::getPointerSizeInBytes() {
284 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
285}
286
Reid Kleckner876330d2016-02-12 21:48:30 +0000287void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
288 const DILocation *InlinedAt) {
289 if (InlinedAt) {
290 // This variable was inlined. Associate it with the InlineSite.
291 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
292 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
293 Site.InlinedLocals.emplace_back(Var);
294 } else {
295 // This variable goes in the main ProcSym.
296 CurFn->Locals.emplace_back(Var);
297 }
298}
299
Reid Kleckner829365a2016-02-11 19:41:47 +0000300static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
301 const DILocation *Loc) {
302 auto B = Locs.begin(), E = Locs.end();
303 if (std::find(B, E, Loc) == E)
304 Locs.push_back(Loc);
305}
306
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000307void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000308 const MachineFunction *MF) {
309 // Skip this instruction if it has the same location as the previous one.
310 if (DL == CurFn->LastLoc)
311 return;
312
313 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000314 if (!Scope)
315 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000316
David Majnemerc3340db2016-01-13 01:05:23 +0000317 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000318 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
319 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
320 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000321 return;
322
Reid Kleckner2214ed82016-01-29 00:49:42 +0000323 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
324 if (CI.getStartColumn() != DL.getCol())
325 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000326
Reid Kleckner2214ed82016-01-29 00:49:42 +0000327 if (!CurFn->HaveLineInfo)
328 CurFn->HaveLineInfo = true;
329 unsigned FileId = 0;
330 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
331 FileId = CurFn->LastFileId;
332 else
333 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
334 CurFn->LastLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000335
336 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000337 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000338 const DILocation *Loc = DL.get();
339
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000340 // If this location was actually inlined from somewhere else, give it the ID
341 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000342 FuncId =
343 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000344
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000345 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000346 bool FirstLoc = true;
347 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000348 InlineSite &Site =
349 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000350 if (!FirstLoc)
351 addLocIfNotPresent(Site.ChildSites, Loc);
352 FirstLoc = false;
353 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000354 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000355 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000356 }
357
Reid Klecknerdac21b42016-02-03 21:15:48 +0000358 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
359 /*PrologueEnd=*/false,
360 /*IsStmt=*/false, DL->getFilename());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000361}
362
Reid Kleckner5d122f82016-05-25 23:16:12 +0000363void CodeViewDebug::emitCodeViewMagicVersion() {
364 OS.EmitValueToAlignment(4);
365 OS.AddComment("Debug section magic");
366 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
367}
368
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000369void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000370 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000371 return;
372
373 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000374
375 // The COFF .debug$S section consists of several subsections, each starting
376 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
377 // of the payload followed by the payload itself. The subsections are 4-byte
378 // aligned.
379
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000380 // Use the generic .debug$S section, and make a subsection for all the inlined
381 // subprograms.
382 switchToDebugSectionForSymbol(nullptr);
Reid Kleckner5d122f82016-05-25 23:16:12 +0000383 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000384
Reid Kleckner2214ed82016-01-29 00:49:42 +0000385 // Emit per-function debug information.
386 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000387 if (!P.first->isDeclarationForLinker())
388 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000389
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000390 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000391 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000392 emitDebugInfoForGlobals();
393
Hans Wennborgb510b452016-06-23 16:33:53 +0000394 // Emit retained types.
395 emitDebugInfoForRetainedTypes();
396
Reid Kleckner5d122f82016-05-25 23:16:12 +0000397 // Switch back to the generic .debug$S section after potentially processing
398 // comdat symbol sections.
399 switchToDebugSectionForSymbol(nullptr);
400
David Majnemer3128b102016-06-15 18:00:01 +0000401 // Emit UDT records for any types used by global variables.
402 if (!GlobalUDTs.empty()) {
403 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
404 emitDebugInfoForUDTs(GlobalUDTs);
405 endCVSubsection(SymbolsEnd);
406 }
407
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000408 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000409 OS.AddComment("File index to string table offset subsection");
410 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000411
412 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000413 OS.AddComment("String table");
414 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000415
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000416 // Emit type information last, so that any types we translate while emitting
417 // function info are included.
418 emitTypeInformation();
419
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000420 clear();
421}
422
David Majnemerb9456a52016-03-14 05:15:09 +0000423static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
424 // Microsoft's linker seems to have trouble with symbol names longer than
425 // 0xffd8 bytes.
426 S = S.substr(0, 0xffd8);
427 SmallString<32> NullTerminatedString(S);
428 NullTerminatedString.push_back('\0');
429 OS.EmitBytes(NullTerminatedString);
430}
431
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000432void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000433 // Do nothing if we have no debug info or if no non-trivial types were emitted
434 // to TypeTable during codegen.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000435 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
Reid Klecknerfbd77872016-03-18 18:54:32 +0000436 if (!CU_Nodes)
437 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000438 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000439 return;
440
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000441 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000442 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000443 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000444
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000445 SmallString<8> CommentPrefix;
446 if (OS.isVerboseAsm()) {
447 CommentPrefix += '\t';
448 CommentPrefix += Asm->MAI->getCommentString();
449 CommentPrefix += ' ';
450 }
451
452 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
Reid Kleckner2280f932016-05-23 20:23:46 +0000453 TypeTable.ForEachRecord(
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000454 [&](TypeIndex Index, StringRef Record) {
455 if (OS.isVerboseAsm()) {
456 // Emit a block comment describing the type record for readability.
457 SmallString<512> CommentBlock;
458 raw_svector_ostream CommentOS(CommentBlock);
459 ScopedPrinter SP(CommentOS);
460 SP.setPrefix(CommentPrefix);
461 CVTD.setPrinter(&SP);
Reid Klecknerc92e9462016-07-01 18:05:56 +0000462 Error E = CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
463 if (E) {
464 logAllUnhandledErrors(std::move(E), errs(), "error: ");
465 llvm_unreachable("produced malformed type record");
466 }
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000467 // emitRawComment will insert its own tab and comment string before
468 // the first line, so strip off our first one. It also prints its own
469 // newline.
470 OS.emitRawComment(
471 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Reid Klecknerc92e9462016-07-01 18:05:56 +0000472 } else {
473#ifndef NDEBUG
474 // Assert that the type data is valid even if we aren't dumping
475 // comments. The MSVC linker doesn't do much type record validation,
476 // so the first link of an invalid type record can succeed while
477 // subsequent links will fail with LNK1285.
Zachary Turnerd66889c2016-07-28 19:12:28 +0000478 ByteStream Stream({Record.bytes_begin(), Record.bytes_end()});
Reid Klecknerc92e9462016-07-01 18:05:56 +0000479 CVTypeArray Types;
480 StreamReader Reader(Stream);
481 Error E = Reader.readArray(Types, Reader.getLength());
482 if (!E) {
483 TypeVisitorCallbacks C;
484 E = CVTypeVisitor(C).visitTypeStream(Types);
485 }
486 if (E) {
487 logAllUnhandledErrors(std::move(E), errs(), "error: ");
488 llvm_unreachable("produced malformed type record");
489 }
490#endif
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000491 }
492 OS.EmitBinaryData(Record);
Reid Kleckner2280f932016-05-23 20:23:46 +0000493 });
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000494}
495
Reid Kleckner5d122f82016-05-25 23:16:12 +0000496void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000497 if (InlinedSubprograms.empty())
498 return;
499
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000500 OS.AddComment("Inlinee lines subsection");
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000501 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000502
503 // We don't provide any extra file info.
504 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000505 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000506 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
507
508 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000509 assert(TypeIndices.count({SP, nullptr}));
510 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000511
David Majnemer30579ec2016-02-02 23:18:23 +0000512 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000513 unsigned FileId = maybeRecordFile(SP->getFile());
514 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
515 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000516 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000517 // The filechecksum table uses 8 byte entries for now, and file ids start at
518 // 1.
519 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000520 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000521 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000522 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000523 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000524 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000525 OS.EmitIntValue(SP->getLine(), 4);
526 }
527
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000528 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000529}
530
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000531void CodeViewDebug::collectInlineSiteChildren(
532 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
533 const InlineSite &Site) {
534 for (const DILocation *ChildSiteLoc : Site.ChildSites) {
535 auto I = FI.InlineSites.find(ChildSiteLoc);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000536 const InlineSite &ChildSite = I->second;
537 Children.push_back(ChildSite.SiteFuncId);
538 collectInlineSiteChildren(Children, FI, ChildSite);
539 }
540}
541
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000542void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
543 const DILocation *InlinedAt,
544 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000545 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
546 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000547
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000548 assert(TypeIndices.count({Site.Inlinee, nullptr}));
549 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000550
551 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000552 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000553 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000554 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000555 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000556 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000557
Reid Klecknerdac21b42016-02-03 21:15:48 +0000558 OS.AddComment("PtrParent");
559 OS.EmitIntValue(0, 4);
560 OS.AddComment("PtrEnd");
561 OS.EmitIntValue(0, 4);
562 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000563 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000564
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000565 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
566 unsigned StartLineNum = Site.Inlinee->getLine();
567 SmallVector<unsigned, 3> SecondaryFuncIds;
568 collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
569
570 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
David Majnemerc9911f22016-02-02 19:22:34 +0000571 FI.Begin, FI.End, SecondaryFuncIds);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000572
573 OS.EmitLabel(InlineEnd);
574
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000575 emitLocalVariableList(Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000576
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000577 // Recurse on child inlined call sites before closing the scope.
578 for (const DILocation *ChildSite : Site.ChildSites) {
579 auto I = FI.InlineSites.find(ChildSite);
580 assert(I != FI.InlineSites.end() &&
581 "child site not in function inline site map");
582 emitInlinedCallSite(FI, ChildSite, I->second);
583 }
584
585 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000586 OS.AddComment("Record length");
587 OS.EmitIntValue(2, 2); // RecordLength
588 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000589 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000590}
591
Reid Kleckner5d122f82016-05-25 23:16:12 +0000592void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
593 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
594 // comdat key. A section may be comdat because of -ffunction-sections or
595 // because it is comdat in the IR.
596 MCSectionCOFF *GVSec =
597 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
598 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
599
600 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
601 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
602 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
603
604 OS.SwitchSection(DebugSec);
605
606 // Emit the magic version number if this is the first time we've switched to
607 // this section.
608 if (ComdatDebugSections.insert(DebugSec).second)
609 emitCodeViewMagicVersion();
610}
611
Reid Kleckner2214ed82016-01-29 00:49:42 +0000612void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
613 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000614 // For each function there is a separate subsection
615 // which holds the PC to file:line table.
616 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000617 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000618
Reid Kleckner5d122f82016-05-25 23:16:12 +0000619 // Switch to the to a comdat section, if appropriate.
620 switchToDebugSectionForSymbol(Fn);
621
Reid Klecknerac945e22016-06-17 16:11:20 +0000622 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000623 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000624 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000625 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000626
627 // If we have a display name, build the fully qualified name by walking the
628 // chain of scopes.
David Majnemer67f684e2016-07-28 05:03:22 +0000629 if (!SP->getDisplayName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000630 FuncName =
631 getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000632
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000633 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000634 if (FuncName.empty())
635 FuncName = GlobalValue::getRealLinkageName(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000636
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000637 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000638 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000639 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000640 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000641 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
642 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000643 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000644 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000645 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000646
David Majnemer7abd2692016-07-06 21:07:47 +0000647 if (GV->hasLocalLinkage()) {
648 OS.AddComment("Record kind: S_LPROC32_ID");
649 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
650 } else {
Reid Klecknerdac21b42016-02-03 21:15:48 +0000651 OS.AddComment("Record kind: S_GPROC32_ID");
Zachary Turner63a28462016-05-17 23:50:21 +0000652 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
David Majnemer7abd2692016-07-06 21:07:47 +0000653 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000654
David Majnemer30579ec2016-02-02 23:18:23 +0000655 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000656 OS.AddComment("PtrParent");
657 OS.EmitIntValue(0, 4);
658 OS.AddComment("PtrEnd");
659 OS.EmitIntValue(0, 4);
660 OS.AddComment("PtrNext");
661 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000662 // This is the important bit that tells the debugger where the function
663 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000664 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000665 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000666 OS.AddComment("Offset after prologue");
667 OS.EmitIntValue(0, 4);
668 OS.AddComment("Offset before epilogue");
669 OS.EmitIntValue(0, 4);
670 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000671 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000672 OS.AddComment("Function section relative address");
673 OS.EmitCOFFSecRel32(Fn);
674 OS.AddComment("Function section index");
675 OS.EmitCOFFSectionIndex(Fn);
676 OS.AddComment("Flags");
677 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000678 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000679 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000680 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000681 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000682 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000683
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000684 emitLocalVariableList(FI.Locals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000685
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000686 // Emit inlined call site information. Only emit functions inlined directly
687 // into the parent function. We'll emit the other sites recursively as part
688 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000689 for (const DILocation *InlinedAt : FI.ChildSites) {
690 auto I = FI.InlineSites.find(InlinedAt);
691 assert(I != FI.InlineSites.end() &&
692 "child site not in function inline site map");
693 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000694 }
695
David Majnemer3128b102016-06-15 18:00:01 +0000696 if (SP != nullptr)
697 emitDebugInfoForUDTs(LocalUDTs);
698
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000699 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000700 OS.AddComment("Record length");
701 OS.EmitIntValue(0x0002, 2);
702 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000703 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000704 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000705 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000706
Reid Kleckner2214ed82016-01-29 00:49:42 +0000707 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000708 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000709}
710
Reid Kleckner876330d2016-02-12 21:48:30 +0000711CodeViewDebug::LocalVarDefRange
712CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
713 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000714 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000715 DR.DataOffset = Offset;
716 assert(DR.DataOffset == Offset && "truncation");
717 DR.StructOffset = 0;
718 DR.CVRegister = CVRegister;
719 return DR;
720}
721
722CodeViewDebug::LocalVarDefRange
723CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
724 LocalVarDefRange DR;
725 DR.InMemory = 0;
726 DR.DataOffset = 0;
727 DR.StructOffset = 0;
728 DR.CVRegister = CVRegister;
729 return DR;
730}
731
732void CodeViewDebug::collectVariableInfoFromMMITable(
733 DenseSet<InlinedVariable> &Processed) {
734 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
735 const TargetFrameLowering *TFI = TSI.getFrameLowering();
736 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
737
738 for (const MachineModuleInfo::VariableDbgInfo &VI :
739 MMI->getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000740 if (!VI.Var)
741 continue;
742 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
743 "Expected inlined-at fields to agree");
744
Reid Kleckner876330d2016-02-12 21:48:30 +0000745 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000746 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
747
748 // If variable scope is not found then skip this variable.
749 if (!Scope)
750 continue;
751
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000752 // Get the frame register used and the offset.
753 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000754 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
755 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000756
757 // Calculate the label ranges.
Reid Kleckner876330d2016-02-12 21:48:30 +0000758 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000759 for (const InsnRange &Range : Scope->getRanges()) {
760 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
761 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000762 End = End ? End : Asm->getFunctionEnd();
763 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000764 }
765
Reid Kleckner876330d2016-02-12 21:48:30 +0000766 LocalVariable Var;
767 Var.DIVar = VI.Var;
768 Var.DefRanges.emplace_back(std::move(DefRange));
769 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
770 }
771}
772
773void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
774 DenseSet<InlinedVariable> Processed;
775 // Grab the variable info that was squirreled away in the MMI side-table.
776 collectVariableInfoFromMMITable(Processed);
777
778 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
779
780 for (const auto &I : DbgValues) {
781 InlinedVariable IV = I.first;
782 if (Processed.count(IV))
783 continue;
784 const DILocalVariable *DIVar = IV.first;
785 const DILocation *InlinedAt = IV.second;
786
787 // Instruction ranges, specifying where IV is accessible.
788 const auto &Ranges = I.second;
789
790 LexicalScope *Scope = nullptr;
791 if (InlinedAt)
792 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
793 else
794 Scope = LScopes.findLexicalScope(DIVar->getScope());
795 // If variable scope is not found then skip this variable.
796 if (!Scope)
797 continue;
798
799 LocalVariable Var;
800 Var.DIVar = DIVar;
801
802 // Calculate the definition ranges.
803 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
804 const InsnRange &Range = *I;
805 const MachineInstr *DVInst = Range.first;
806 assert(DVInst->isDebugValue() && "Invalid History entry");
807 const DIExpression *DIExpr = DVInst->getDebugExpression();
808
809 // Bail if there is a complex DWARF expression for now.
810 if (DIExpr && DIExpr->getNumElements() > 0)
811 continue;
812
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000813 // Bail if operand 0 is not a valid register. This means the variable is a
814 // simple constant, or is described by a complex expression.
815 // FIXME: Find a way to represent constant variables, since they are
816 // relatively common.
817 unsigned Reg =
818 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
819 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +0000820 continue;
821
Reid Kleckner876330d2016-02-12 21:48:30 +0000822 // Handle the two cases we can handle: indirect in memory and in register.
823 bool IsIndirect = DVInst->getOperand(1).isImm();
824 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
825 {
826 LocalVarDefRange DefRange;
827 if (IsIndirect) {
828 int64_t Offset = DVInst->getOperand(1).getImm();
829 DefRange = createDefRangeMem(CVReg, Offset);
830 } else {
831 DefRange = createDefRangeReg(CVReg);
832 }
833 if (Var.DefRanges.empty() ||
834 Var.DefRanges.back().isDifferentLocation(DefRange)) {
835 Var.DefRanges.emplace_back(std::move(DefRange));
836 }
837 }
838
839 // Compute the label range.
840 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
841 const MCSymbol *End = getLabelAfterInsn(Range.second);
842 if (!End) {
843 if (std::next(I) != E)
844 End = getLabelBeforeInsn(std::next(I)->first);
845 else
846 End = Asm->getFunctionEnd();
847 }
848
849 // If the last range end is our begin, just extend the last range.
850 // Otherwise make a new range.
851 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
852 Var.DefRanges.back().Ranges;
853 if (!Ranges.empty() && Ranges.back().second == Begin)
854 Ranges.back().second = End;
855 else
856 Ranges.emplace_back(Begin, End);
857
858 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000859 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000860
861 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000862 }
863}
864
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000865void CodeViewDebug::beginFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000866 assert(!CurFn && "Can't process two functions at once!");
867
David Majnemer67f684e2016-07-28 05:03:22 +0000868 if (!Asm || !MMI->hasDebugInfo() || !MF->getFunction()->getSubprogram())
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000869 return;
870
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000871 DebugHandlerBase::beginFunction(MF);
872
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000873 const Function *GV = MF->getFunction();
874 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000875 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +0000876 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000877 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000878
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000879 // Find the end of the function prolog. First known non-DBG_VALUE and
880 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000881 // FIXME: is there a simpler a way to do this? Can we just search
882 // for the first instruction of the function, not the last of the prolog?
883 DebugLoc PrologEndLoc;
884 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000885 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000886 for (const auto &MI : MBB) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000887 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
888 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000889 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000890 break;
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000891 } else if (!MI.isDebugValue()) {
892 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000893 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000894 }
895 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000896
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000897 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000898 if (PrologEndLoc && !EmptyPrologue) {
899 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000900 maybeRecordLocation(FnStartDL, MF);
901 }
902}
903
Hans Wennborg4b63a982016-06-23 22:57:25 +0000904void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
Reid Klecknerad56ea32016-07-01 22:24:51 +0000905 // Don't record empty UDTs.
906 if (Ty->getName().empty())
907 return;
908
Hans Wennborg4b63a982016-06-23 22:57:25 +0000909 SmallVector<StringRef, 5> QualifiedNameComponents;
910 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
911 Ty->getScope().resolve(), QualifiedNameComponents);
912
913 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +0000914 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +0000915
916 if (ClosestSubprogram == nullptr)
917 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
918 else if (ClosestSubprogram == CurrentSubprogram)
919 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
920
921 // TODO: What if the ClosestSubprogram is neither null or the current
922 // subprogram? Currently, the UDT just gets dropped on the floor.
923 //
924 // The current behavior is not desirable. To get maximal fidelity, we would
925 // need to perform all type translation before beginning emission of .debug$S
926 // and then make LocalUDTs a member of FunctionInfo
927}
928
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000929TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000930 // Generic dispatch for lowering an unknown type.
931 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +0000932 case dwarf::DW_TAG_array_type:
933 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +0000934 case dwarf::DW_TAG_typedef:
935 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000936 case dwarf::DW_TAG_base_type:
937 return lowerTypeBasic(cast<DIBasicType>(Ty));
938 case dwarf::DW_TAG_pointer_type:
939 case dwarf::DW_TAG_reference_type:
940 case dwarf::DW_TAG_rvalue_reference_type:
941 return lowerTypePointer(cast<DIDerivedType>(Ty));
942 case dwarf::DW_TAG_ptr_to_member_type:
943 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
944 case dwarf::DW_TAG_const_type:
945 case dwarf::DW_TAG_volatile_type:
946 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +0000947 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000948 if (ClassTy) {
949 // The member function type of a member function pointer has no
950 // ThisAdjustment.
951 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
952 /*ThisAdjustment=*/0);
953 }
David Majnemer75c3ebf2016-06-02 17:13:53 +0000954 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +0000955 case dwarf::DW_TAG_enumeration_type:
956 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +0000957 case dwarf::DW_TAG_class_type:
958 case dwarf::DW_TAG_structure_type:
959 return lowerTypeClass(cast<DICompositeType>(Ty));
960 case dwarf::DW_TAG_union_type:
961 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000962 default:
963 // Use the null type index.
964 return TypeIndex();
965 }
966}
967
David Majnemerd065e232016-06-02 06:21:37 +0000968TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +0000969 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
970 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +0000971 StringRef TypeName = Ty->getName();
972
Hans Wennborg4b63a982016-06-23 22:57:25 +0000973 addToUDTs(Ty, UnderlyingTypeIndex);
David Majnemer3128b102016-06-15 18:00:01 +0000974
David Majnemerd065e232016-06-02 06:21:37 +0000975 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +0000976 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +0000977 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +0000978 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +0000979 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +0000980 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +0000981
David Majnemerd065e232016-06-02 06:21:37 +0000982 return UnderlyingTypeIndex;
983}
984
Adrian McCarthyf3c3c132016-06-08 18:22:59 +0000985TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
986 DITypeRef ElementTypeRef = Ty->getBaseType();
987 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
988 // IndexType is size_t, which depends on the bitness of the target.
989 TypeIndex IndexType = Asm->MAI->getPointerSize() == 8
990 ? TypeIndex(SimpleTypeKind::UInt64Quad)
991 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +0000992
993 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
994
995 bool UndefinedSubrange = false;
996
997 // FIXME:
998 // There is a bug in the front-end where an array of a structure, which was
999 // declared as incomplete structure first, ends up not getting a size assigned
1000 // to it. (PR28303)
1001 // Example:
1002 // struct A(*p)[3];
1003 // struct A { int f; } a[3];
1004 //
1005 // This needs to be fixed in the front-end, but in the meantime we don't want
1006 // to trigger an assertion because of this.
1007 if (Ty->getSizeInBits() == 0) {
1008 UndefinedSubrange = true;
1009 }
1010
1011 // Add subranges to array type.
1012 DINodeArray Elements = Ty->getElements();
1013 for (int i = Elements.size() - 1; i >= 0; --i) {
1014 const DINode *Element = Elements[i];
1015 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1016
1017 const DISubrange *Subrange = cast<DISubrange>(Element);
1018 assert(Subrange->getLowerBound() == 0 &&
1019 "codeview doesn't support subranges with lower bounds");
1020 int64_t Count = Subrange->getCount();
1021
1022 // Variable Length Array (VLA) has Count equal to '-1'.
1023 // Replace with Count '1', assume it is the minimum VLA length.
1024 // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
1025 if (Count == -1) {
1026 Count = 1;
1027 UndefinedSubrange = true;
1028 }
1029
1030 StringRef Name = (i == 0) ? Ty->getName() : "";
1031 // Update the element size and element type index for subsequent subranges.
1032 ElementSize *= Count;
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001033 ElementTypeIndex = TypeTable.writeKnownType(
Amjad Aboudacee5682016-07-12 12:06:34 +00001034 ArrayRecord(ElementTypeIndex, IndexType, ElementSize, Name));
1035 }
1036
1037 (void)UndefinedSubrange;
1038 assert(UndefinedSubrange || ElementSize == (Ty->getSizeInBits() / 8));
1039
1040 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001041}
1042
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001043TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1044 TypeIndex Index;
1045 dwarf::TypeKind Kind;
1046 uint32_t ByteSize;
1047
1048 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001049 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001050
1051 SimpleTypeKind STK = SimpleTypeKind::None;
1052 switch (Kind) {
1053 case dwarf::DW_ATE_address:
1054 // FIXME: Translate
1055 break;
1056 case dwarf::DW_ATE_boolean:
1057 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001058 case 1: STK = SimpleTypeKind::Boolean8; break;
1059 case 2: STK = SimpleTypeKind::Boolean16; break;
1060 case 4: STK = SimpleTypeKind::Boolean32; break;
1061 case 8: STK = SimpleTypeKind::Boolean64; break;
1062 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001063 }
1064 break;
1065 case dwarf::DW_ATE_complex_float:
1066 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001067 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001068 case 4: STK = SimpleTypeKind::Complex32; break;
1069 case 8: STK = SimpleTypeKind::Complex64; break;
1070 case 10: STK = SimpleTypeKind::Complex80; break;
1071 case 16: STK = SimpleTypeKind::Complex128; break;
1072 }
1073 break;
1074 case dwarf::DW_ATE_float:
1075 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001076 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001077 case 4: STK = SimpleTypeKind::Float32; break;
1078 case 6: STK = SimpleTypeKind::Float48; break;
1079 case 8: STK = SimpleTypeKind::Float64; break;
1080 case 10: STK = SimpleTypeKind::Float80; break;
1081 case 16: STK = SimpleTypeKind::Float128; break;
1082 }
1083 break;
1084 case dwarf::DW_ATE_signed:
1085 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001086 case 1: STK = SimpleTypeKind::SByte; break;
1087 case 2: STK = SimpleTypeKind::Int16Short; break;
1088 case 4: STK = SimpleTypeKind::Int32; break;
1089 case 8: STK = SimpleTypeKind::Int64Quad; break;
1090 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001091 }
1092 break;
1093 case dwarf::DW_ATE_unsigned:
1094 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001095 case 1: STK = SimpleTypeKind::Byte; break;
1096 case 2: STK = SimpleTypeKind::UInt16Short; break;
1097 case 4: STK = SimpleTypeKind::UInt32; break;
1098 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1099 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001100 }
1101 break;
1102 case dwarf::DW_ATE_UTF:
1103 switch (ByteSize) {
1104 case 2: STK = SimpleTypeKind::Character16; break;
1105 case 4: STK = SimpleTypeKind::Character32; break;
1106 }
1107 break;
1108 case dwarf::DW_ATE_signed_char:
1109 if (ByteSize == 1)
1110 STK = SimpleTypeKind::SignedCharacter;
1111 break;
1112 case dwarf::DW_ATE_unsigned_char:
1113 if (ByteSize == 1)
1114 STK = SimpleTypeKind::UnsignedCharacter;
1115 break;
1116 default:
1117 break;
1118 }
1119
1120 // Apply some fixups based on the source-level type name.
1121 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1122 STK = SimpleTypeKind::Int32Long;
1123 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1124 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001125 if (STK == SimpleTypeKind::UInt16Short &&
1126 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001127 STK = SimpleTypeKind::WideCharacter;
1128 if ((STK == SimpleTypeKind::SignedCharacter ||
1129 STK == SimpleTypeKind::UnsignedCharacter) &&
1130 Ty->getName() == "char")
1131 STK = SimpleTypeKind::NarrowCharacter;
1132
1133 return TypeIndex(STK);
1134}
1135
1136TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1137 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1138
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001139 // While processing the type being pointed to it is possible we already
1140 // created this pointer type. If so, we check here and return the existing
1141 // pointer type.
1142 auto I = TypeIndices.find({Ty, nullptr});
1143 if (I != TypeIndices.end())
1144 return I->second;
1145
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001146 // Pointers to simple types can use SimpleTypeMode, rather than having a
1147 // dedicated pointer type record.
1148 if (PointeeTI.isSimple() &&
1149 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1150 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1151 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1152 ? SimpleTypeMode::NearPointer64
1153 : SimpleTypeMode::NearPointer32;
1154 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1155 }
1156
1157 PointerKind PK =
1158 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1159 PointerMode PM = PointerMode::Pointer;
1160 switch (Ty->getTag()) {
1161 default: llvm_unreachable("not a pointer tag type");
1162 case dwarf::DW_TAG_pointer_type:
1163 PM = PointerMode::Pointer;
1164 break;
1165 case dwarf::DW_TAG_reference_type:
1166 PM = PointerMode::LValueReference;
1167 break;
1168 case dwarf::DW_TAG_rvalue_reference_type:
1169 PM = PointerMode::RValueReference;
1170 break;
1171 }
1172 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1173 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1174 // do.
1175 PointerOptions PO = PointerOptions::None;
1176 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001177 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001178}
1179
Reid Kleckner6fa15462016-06-17 22:14:39 +00001180static PointerToMemberRepresentation
1181translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1182 // SizeInBytes being zero generally implies that the member pointer type was
1183 // incomplete, which can happen if it is part of a function prototype. In this
1184 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001185 if (IsPMF) {
1186 switch (Flags & DINode::FlagPtrToMemberRep) {
1187 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001188 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1189 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001190 case DINode::FlagSingleInheritance:
1191 return PointerToMemberRepresentation::SingleInheritanceFunction;
1192 case DINode::FlagMultipleInheritance:
1193 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1194 case DINode::FlagVirtualInheritance:
1195 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1196 }
1197 } else {
1198 switch (Flags & DINode::FlagPtrToMemberRep) {
1199 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001200 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1201 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001202 case DINode::FlagSingleInheritance:
1203 return PointerToMemberRepresentation::SingleInheritanceData;
1204 case DINode::FlagMultipleInheritance:
1205 return PointerToMemberRepresentation::MultipleInheritanceData;
1206 case DINode::FlagVirtualInheritance:
1207 return PointerToMemberRepresentation::VirtualInheritanceData;
1208 }
1209 }
1210 llvm_unreachable("invalid ptr to member representation");
1211}
1212
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001213TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1214 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1215 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001216 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001217 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
1218 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001219 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1220 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1221 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001222 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner6fa15462016-06-17 22:14:39 +00001223 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1224 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1225 MemberPointerInfo MPI(
1226 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001227 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001228 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001229}
1230
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001231/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1232/// have a translation, use the NearC convention.
1233static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1234 switch (DwarfCC) {
1235 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1236 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1237 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1238 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1239 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1240 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1241 }
1242 return CallingConvention::NearC;
1243}
1244
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001245TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1246 ModifierOptions Mods = ModifierOptions::None;
1247 bool IsModifier = true;
1248 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001249 while (IsModifier && BaseTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001250 // FIXME: Need to add DWARF tag for __unaligned.
1251 switch (BaseTy->getTag()) {
1252 case dwarf::DW_TAG_const_type:
1253 Mods |= ModifierOptions::Const;
1254 break;
1255 case dwarf::DW_TAG_volatile_type:
1256 Mods |= ModifierOptions::Volatile;
1257 break;
1258 default:
1259 IsModifier = false;
1260 break;
1261 }
1262 if (IsModifier)
1263 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1264 }
1265 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001266
1267 // While processing the type being pointed to, it is possible we already
1268 // created this modifier type. If so, we check here and return the existing
1269 // modifier type.
1270 auto I = TypeIndices.find({Ty, nullptr});
1271 if (I != TypeIndices.end())
1272 return I->second;
1273
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001274 ModifierRecord MR(ModifiedTI, Mods);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001275 return TypeTable.writeKnownType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001276}
1277
David Majnemer75c3ebf2016-06-02 17:13:53 +00001278TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1279 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1280 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1281 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1282
1283 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1284 ArrayRef<TypeIndex> ArgTypeIndices = None;
1285 if (!ReturnAndArgTypeIndices.empty()) {
1286 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1287 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1288 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1289 }
1290
1291 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001292 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001293
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001294 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1295
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001296 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1297 ArgTypeIndices.size(), ArgListIndex);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001298 return TypeTable.writeKnownType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001299}
1300
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001301TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001302 const DIType *ClassTy,
1303 int ThisAdjustment) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001304 // Lower the containing class type.
1305 TypeIndex ClassType = getTypeIndex(ClassTy);
1306
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001307 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1308 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1309 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1310
1311 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1312 ArrayRef<TypeIndex> ArgTypeIndices = None;
1313 if (!ReturnAndArgTypeIndices.empty()) {
1314 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1315 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1316 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1317 }
1318 TypeIndex ThisTypeIndex = TypeIndex::Void();
1319 if (!ArgTypeIndices.empty()) {
1320 ThisTypeIndex = ArgTypeIndices.front();
1321 ArgTypeIndices = ArgTypeIndices.drop_front();
1322 }
1323
1324 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001325 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001326
1327 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1328
1329 // TODO: Need to use the correct values for:
1330 // FunctionOptions
1331 // ThisPointerAdjustment.
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001332 TypeIndex TI = TypeTable.writeKnownType(MemberFunctionRecord(
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001333 ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FunctionOptions::None,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001334 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001335
1336 return TI;
1337}
1338
1339static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1340 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001341 case DINode::FlagPrivate: return MemberAccess::Private;
1342 case DINode::FlagPublic: return MemberAccess::Public;
1343 case DINode::FlagProtected: return MemberAccess::Protected;
1344 case 0:
1345 // If there was no explicit access control, provide the default for the tag.
1346 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1347 : MemberAccess::Public;
1348 }
1349 llvm_unreachable("access flags are exclusive");
1350}
1351
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001352static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1353 if (SP->isArtificial())
1354 return MethodOptions::CompilerGenerated;
1355
1356 // FIXME: Handle other MethodOptions.
1357
1358 return MethodOptions::None;
1359}
1360
1361static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1362 bool Introduced) {
1363 switch (SP->getVirtuality()) {
1364 case dwarf::DW_VIRTUALITY_none:
1365 break;
1366 case dwarf::DW_VIRTUALITY_virtual:
1367 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1368 case dwarf::DW_VIRTUALITY_pure_virtual:
1369 return Introduced ? MethodKind::PureIntroducingVirtual
1370 : MethodKind::PureVirtual;
1371 default:
1372 llvm_unreachable("unhandled virtuality case");
1373 }
1374
1375 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1376
1377 return MethodKind::Vanilla;
1378}
1379
Reid Klecknera8d57402016-06-03 15:58:20 +00001380static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1381 switch (Ty->getTag()) {
1382 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1383 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1384 }
1385 llvm_unreachable("unexpected tag");
1386}
1387
Reid Klecknere092dad2016-07-02 00:11:07 +00001388/// Return ClassOptions that should be present on both the forward declaration
1389/// and the defintion of a tag type.
1390static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1391 ClassOptions CO = ClassOptions::None;
1392
1393 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001394 // appear to give every type a linkage name, which may be problematic for us.
1395 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001396 if (!Ty->getIdentifier().empty())
1397 CO |= ClassOptions::HasUniqueName;
1398
1399 // Put the Nested flag on a type if it appears immediately inside a tag type.
1400 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1401 // here. That flag is only set on definitions, and not forward declarations.
1402 const DIScope *ImmediateScope = Ty->getScope().resolve();
1403 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1404 CO |= ClassOptions::Nested;
1405
1406 // Put the Scoped flag on function-local types.
1407 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1408 Scope = Scope->getScope().resolve()) {
1409 if (isa<DISubprogram>(Scope)) {
1410 CO |= ClassOptions::Scoped;
1411 break;
1412 }
1413 }
1414
1415 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001416}
1417
David Majnemer979cb882016-06-16 21:32:16 +00001418TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001419 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001420 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001421 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001422
David Majnemerda9548f2016-06-17 16:13:21 +00001423 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001424 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001425 } else {
1426 FieldListRecordBuilder Fields;
1427 for (const DINode *Element : Ty->getElements()) {
1428 // We assume that the frontend provides all members in source declaration
1429 // order, which is what MSVC does.
1430 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001431 Fields.writeMemberType(EnumeratorRecord(
David Majnemerda9548f2016-06-17 16:13:21 +00001432 MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()),
1433 Enumerator->getName()));
1434 EnumeratorCount++;
1435 }
1436 }
1437 FTI = TypeTable.writeFieldList(Fields);
1438 }
David Majnemer979cb882016-06-16 21:32:16 +00001439
David Majnemer6bdc24e2016-07-01 23:12:45 +00001440 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001441
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001442 return TypeTable.writeKnownType(EnumRecord(EnumeratorCount, CO, FTI, FullName,
1443 Ty->getIdentifier(),
1444 getTypeIndex(Ty->getBaseType())));
David Majnemer979cb882016-06-16 21:32:16 +00001445}
1446
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001447//===----------------------------------------------------------------------===//
1448// ClassInfo
1449//===----------------------------------------------------------------------===//
1450
1451struct llvm::ClassInfo {
1452 struct MemberInfo {
1453 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00001454 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001455 };
1456 // [MemberInfo]
1457 typedef std::vector<MemberInfo> MemberList;
1458
Reid Kleckner156a7232016-06-22 18:31:14 +00001459 typedef TinyPtrVector<const DISubprogram *> MethodsList;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001460 // MethodName -> MethodsList
1461 typedef MapVector<MDString *, MethodsList> MethodsMap;
1462
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001463 /// Base classes.
1464 std::vector<const DIDerivedType *> Inheritance;
1465
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001466 /// Direct members.
1467 MemberList Members;
1468 // Direct overloaded methods gathered by name.
1469 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001470
1471 std::vector<const DICompositeType *> NestedClasses;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001472};
1473
1474void CodeViewDebug::clear() {
1475 assert(CurFn == nullptr);
1476 FileIdMap.clear();
1477 FnDebugInfo.clear();
1478 FileToFilepathMap.clear();
1479 LocalUDTs.clear();
1480 GlobalUDTs.clear();
1481 TypeIndices.clear();
1482 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001483}
1484
1485void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1486 const DIDerivedType *DDTy) {
1487 if (!DDTy->getName().empty()) {
1488 Info.Members.push_back({DDTy, 0});
1489 return;
1490 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001491 // An unnamed member must represent a nested struct or union. Add all the
1492 // indirect fields to the current record.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001493 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00001494 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001495 const DIType *Ty = DDTy->getBaseType().resolve();
Reid Kleckner9ff936c2016-06-21 14:56:24 +00001496 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001497 ClassInfo NestedInfo = collectClassInfo(DCTy);
1498 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001499 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001500 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001501}
1502
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001503ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1504 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001505 // Add elements to structure type.
1506 DINodeArray Elements = Ty->getElements();
1507 for (auto *Element : Elements) {
1508 // We assume that the frontend provides all members in source declaration
1509 // order, which is what MSVC does.
1510 if (!Element)
1511 continue;
1512 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001513 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001514 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001515 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001516 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001517 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1518 Info.Inheritance.push_back(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001519 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1520 // Ignore friend members. It appears that MSVC emitted info about
1521 // friends in the past, but modern versions do not.
1522 }
1523 // FIXME: Get Clang to emit function virtual table here and handle it.
Adrian McCarthy820ca542016-07-06 19:49:51 +00001524 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1525 Info.NestedClasses.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001526 }
1527 // Skip other unrecognized kinds of elements.
1528 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001529 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001530}
1531
Reid Klecknera8d57402016-06-03 15:58:20 +00001532TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1533 // First, construct the forward decl. Don't look into Ty to compute the
1534 // forward decl options, since it might not be available in all TUs.
1535 TypeRecordKind Kind = getRecordKind(Ty);
1536 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001537 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001538 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001539 TypeIndex FwdDeclTI = TypeTable.writeKnownType(ClassRecord(
Reid Klecknera8d57402016-06-03 15:58:20 +00001540 Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(),
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001541 TypeIndex(), TypeIndex(), 0, FullName, Ty->getIdentifier()));
Reid Kleckner643dd832016-06-22 17:15:28 +00001542 if (!Ty->isForwardDecl())
1543 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001544 return FwdDeclTI;
1545}
1546
1547TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1548 // Construct the field list and complete type record.
1549 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00001550 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001551 TypeIndex FieldTI;
1552 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001553 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001554 bool ContainsNestedClass;
1555 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1556 lowerRecordFieldList(Ty);
1557
1558 if (ContainsNestedClass)
1559 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00001560
David Majnemer6bdc24e2016-07-01 23:12:45 +00001561 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001562
Reid Klecknera8d57402016-06-03 15:58:20 +00001563 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00001564
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001565 TypeIndex ClassTI = TypeTable.writeKnownType(ClassRecord(
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001566 Kind, FieldCount, CO, HfaKind::None, WindowsRTClassKind::None, FieldTI,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001567 TypeIndex(), VShapeTI, SizeInBytes, FullName, Ty->getIdentifier()));
Hans Wennborg9a519a02016-06-22 21:22:13 +00001568
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001569 TypeTable.writeKnownType(UdtSourceLineRecord(
1570 ClassTI, TypeTable.writeKnownType(StringIdRecord(
Hans Wennborg9a519a02016-06-22 21:22:13 +00001571 TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1572 Ty->getLine()));
1573
Hans Wennborg4b63a982016-06-23 22:57:25 +00001574 addToUDTs(Ty, ClassTI);
1575
Hans Wennborg9a519a02016-06-22 21:22:13 +00001576 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001577}
1578
1579TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1580 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001581 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001582 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001583 TypeIndex FwdDeclTI = TypeTable.writeKnownType(UnionRecord(
1584 0, CO, HfaKind::None, TypeIndex(), 0, FullName, Ty->getIdentifier()));
Reid Kleckner643dd832016-06-22 17:15:28 +00001585 if (!Ty->isForwardDecl())
1586 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001587 return FwdDeclTI;
1588}
1589
1590TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00001591 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001592 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001593 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001594 bool ContainsNestedClass;
1595 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1596 lowerRecordFieldList(Ty);
1597
1598 if (ContainsNestedClass)
1599 CO |= ClassOptions::ContainsNestedClass;
1600
Reid Klecknera8d57402016-06-03 15:58:20 +00001601 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00001602 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001603
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001604 TypeIndex UnionTI = TypeTable.writeKnownType(
Hans Wennborg9a519a02016-06-22 21:22:13 +00001605 UnionRecord(FieldCount, CO, HfaKind::None, FieldTI, SizeInBytes, FullName,
1606 Ty->getIdentifier()));
1607
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001608 TypeTable.writeKnownType(UdtSourceLineRecord(
1609 UnionTI, TypeTable.writeKnownType(StringIdRecord(
Hans Wennborg9a519a02016-06-22 21:22:13 +00001610 TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1611 Ty->getLine()));
1612
Hans Wennborg4b63a982016-06-23 22:57:25 +00001613 addToUDTs(Ty, UnionTI);
1614
Hans Wennborg9a519a02016-06-22 21:22:13 +00001615 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001616}
1617
Adrian McCarthy820ca542016-07-06 19:49:51 +00001618std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00001619CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1620 // Manually count members. MSVC appears to count everything that generates a
1621 // field list record. Each individual overload in a method overload group
1622 // contributes to this count, even though the overload group is a single field
1623 // list record.
1624 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001625 ClassInfo Info = collectClassInfo(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001626 FieldListRecordBuilder Fields;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001627
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001628 // Create base classes.
1629 for (const DIDerivedType *I : Info.Inheritance) {
1630 if (I->getFlags() & DINode::FlagVirtual) {
1631 // Virtual base.
1632 // FIXME: Emit VBPtrOffset when the frontend provides it.
1633 unsigned VBPtrOffset = 0;
1634 // FIXME: Despite the accessor name, the offset is really in bytes.
1635 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001636 Fields.writeMemberType(VirtualBaseClassRecord(
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001637 translateAccessFlags(Ty->getTag(), I->getFlags()),
1638 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
1639 VBTableIndex));
1640 } else {
1641 assert(I->getOffsetInBits() % 8 == 0 &&
1642 "bases must be on byte boundaries");
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001643 Fields.writeMemberType(BaseClassRecord(
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001644 translateAccessFlags(Ty->getTag(), I->getFlags()),
1645 getTypeIndex(I->getBaseType()), I->getOffsetInBits() / 8));
1646 }
1647 }
1648
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001649 // Create members.
1650 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1651 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1652 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00001653 StringRef MemberName = Member->getName();
1654 MemberAccess Access =
1655 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001656
1657 if (Member->isStaticMember()) {
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001658 Fields.writeMemberType(
David Majnemer9319cbc2016-06-30 03:00:20 +00001659 StaticDataMemberRecord(Access, MemberBaseType, MemberName));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001660 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001661 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00001662 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001663
David Majnemer9319cbc2016-06-30 03:00:20 +00001664 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00001665 uint64_t MemberOffsetInBits =
1666 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001667 if (Member->isBitField()) {
1668 uint64_t StartBitOffset = MemberOffsetInBits;
1669 if (const auto *CI =
1670 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00001671 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001672 }
1673 StartBitOffset -= MemberOffsetInBits;
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001674 MemberBaseType = TypeTable.writeKnownType(BitFieldRecord(
David Majnemer9319cbc2016-06-30 03:00:20 +00001675 MemberBaseType, Member->getSizeInBits(), StartBitOffset));
1676 }
1677 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001678 Fields.writeMemberType(DataMemberRecord(Access, MemberBaseType,
David Majnemer9319cbc2016-06-30 03:00:20 +00001679 MemberOffsetInBytes, MemberName));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001680 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001681 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001682
1683 // Create methods
1684 for (auto &MethodItr : Info.Methods) {
1685 StringRef Name = MethodItr.first->getString();
1686
1687 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00001688 for (const DISubprogram *SP : MethodItr.second) {
1689 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1690 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001691
1692 unsigned VFTableOffset = -1;
1693 if (Introduced)
1694 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1695
1696 Methods.push_back(
1697 OneMethodRecord(MethodType, translateMethodKindFlags(SP, Introduced),
1698 translateMethodOptionFlags(SP),
1699 translateAccessFlags(Ty->getTag(), SP->getFlags()),
1700 VFTableOffset, Name));
1701 MemberCount++;
1702 }
1703 assert(Methods.size() > 0 && "Empty methods map entry");
1704 if (Methods.size() == 1)
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001705 Fields.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001706 else {
1707 TypeIndex MethodList =
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001708 TypeTable.writeKnownType(MethodOverloadListRecord(Methods));
1709 Fields.writeMemberType(
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001710 OverloadedMethodRecord(Methods.size(), MethodList, Name));
1711 }
1712 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001713
1714 // Create nested classes.
1715 for (const DICompositeType *Nested : Info.NestedClasses) {
1716 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001717 Fields.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00001718 MemberCount++;
1719 }
1720
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001721 TypeIndex FieldTI = TypeTable.writeFieldList(Fields);
Adrian McCarthy820ca542016-07-06 19:49:51 +00001722 return std::make_tuple(FieldTI, TypeIndex(), MemberCount,
1723 !Info.NestedClasses.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00001724}
1725
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001726TypeIndex CodeViewDebug::getVBPTypeIndex() {
1727 if (!VBPType.getIndex()) {
1728 // Make a 'const int *' type.
1729 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001730 TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001731
1732 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1733 : PointerKind::Near32;
1734 PointerMode PM = PointerMode::Pointer;
1735 PointerOptions PO = PointerOptions::None;
1736 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1737
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001738 VBPType = TypeTable.writeKnownType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001739 }
1740
1741 return VBPType;
1742}
1743
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001744TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001745 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001746 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001747
1748 // The null DIType is the void type. Don't try to hash it.
1749 if (!Ty)
1750 return TypeIndex::Void();
1751
Reid Klecknera8d57402016-06-03 15:58:20 +00001752 // Check if we've already translated this type. Don't try to do a
1753 // get-or-create style insertion that caches the hash lookup across the
1754 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001755 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001756 if (I != TypeIndices.end())
1757 return I->second;
1758
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001759 TypeLoweringScope S(*this);
1760 TypeIndex TI = lowerType(Ty, ClassTy);
1761 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00001762}
1763
1764TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1765 const DIType *Ty = TypeRef.resolve();
1766
1767 // The null DIType is the void type. Don't try to hash it.
1768 if (!Ty)
1769 return TypeIndex::Void();
1770
1771 // If this is a non-record type, the complete type index is the same as the
1772 // normal type index. Just call getTypeIndex.
1773 switch (Ty->getTag()) {
1774 case dwarf::DW_TAG_class_type:
1775 case dwarf::DW_TAG_structure_type:
1776 case dwarf::DW_TAG_union_type:
1777 break;
1778 default:
1779 return getTypeIndex(Ty);
1780 }
1781
1782 // Check if we've already translated the complete record type. Lowering a
1783 // complete type should never trigger lowering another complete type, so we
1784 // can reuse the hash table lookup result.
1785 const auto *CTy = cast<DICompositeType>(Ty);
1786 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1787 if (!InsertResult.second)
1788 return InsertResult.first->second;
1789
Reid Kleckner643dd832016-06-22 17:15:28 +00001790 TypeLoweringScope S(*this);
1791
Reid Klecknera8d57402016-06-03 15:58:20 +00001792 // Make sure the forward declaration is emitted first. It's unclear if this
1793 // is necessary, but MSVC does it, and we should follow suit until we can show
1794 // otherwise.
1795 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1796
1797 // Just use the forward decl if we don't have complete type info. This might
1798 // happen if the frontend is using modules and expects the complete definition
1799 // to be emitted elsewhere.
1800 if (CTy->isForwardDecl())
1801 return FwdDeclTI;
1802
1803 TypeIndex TI;
1804 switch (CTy->getTag()) {
1805 case dwarf::DW_TAG_class_type:
1806 case dwarf::DW_TAG_structure_type:
1807 TI = lowerCompleteTypeClass(CTy);
1808 break;
1809 case dwarf::DW_TAG_union_type:
1810 TI = lowerCompleteTypeUnion(CTy);
1811 break;
1812 default:
1813 llvm_unreachable("not a record");
1814 }
1815
1816 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001817 return TI;
1818}
1819
Reid Kleckner643dd832016-06-22 17:15:28 +00001820/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00001821/// and do this until fixpoint, as each complete record type typically
1822/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00001823/// many other record types.
1824void CodeViewDebug::emitDeferredCompleteTypes() {
1825 SmallVector<const DICompositeType *, 4> TypesToEmit;
1826 while (!DeferredCompleteTypes.empty()) {
1827 std::swap(DeferredCompleteTypes, TypesToEmit);
1828 for (const DICompositeType *RecordTy : TypesToEmit)
1829 getCompleteTypeIndex(RecordTy);
1830 TypesToEmit.clear();
1831 }
1832}
1833
Reid Kleckner10dd55c2016-06-24 17:55:40 +00001834void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
1835 // Get the sorted list of parameters and emit them first.
1836 SmallVector<const LocalVariable *, 6> Params;
1837 for (const LocalVariable &L : Locals)
1838 if (L.DIVar->isParameter())
1839 Params.push_back(&L);
1840 std::sort(Params.begin(), Params.end(),
1841 [](const LocalVariable *L, const LocalVariable *R) {
1842 return L->DIVar->getArg() < R->DIVar->getArg();
1843 });
1844 for (const LocalVariable *L : Params)
1845 emitLocalVariable(*L);
1846
1847 // Next emit all non-parameters in the order that we found them.
1848 for (const LocalVariable &L : Locals)
1849 if (!L.DIVar->isParameter())
1850 emitLocalVariable(L);
1851}
1852
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001853void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
1854 // LocalSym record, see SymbolRecord.h for more info.
1855 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
1856 *LocalEnd = MMI->getContext().createTempSymbol();
1857 OS.AddComment("Record length");
1858 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
1859 OS.EmitLabel(LocalBegin);
1860
1861 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00001862 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001863
Zachary Turner63a28462016-05-17 23:50:21 +00001864 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001865 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00001866 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00001867 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00001868 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001869
1870 OS.AddComment("TypeIndex");
Reid Klecknera8d57402016-06-03 15:58:20 +00001871 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001872 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001873 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00001874 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00001875 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00001876 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001877 OS.EmitLabel(LocalEnd);
1878
Reid Kleckner876330d2016-02-12 21:48:30 +00001879 // Calculate the on disk prefix of the appropriate def range record. The
1880 // records and on disk formats are described in SymbolRecords.h. BytePrefix
1881 // should be big enough to hold all forms without memory allocation.
1882 SmallString<20> BytePrefix;
1883 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
1884 BytePrefix.clear();
1885 // FIXME: Handle bitpieces.
1886 if (DefRange.StructOffset != 0)
1887 continue;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001888
Reid Kleckner876330d2016-02-12 21:48:30 +00001889 if (DefRange.InMemory) {
Zachary Turnera78ecd12016-05-23 18:49:06 +00001890 DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
1891 0, 0, ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001892 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00001893 BytePrefix +=
1894 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001895 BytePrefix +=
1896 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1897 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001898 } else {
1899 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Zachary Turnera78ecd12016-05-23 18:49:06 +00001900 // Unclear what matters here.
1901 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
1902 ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001903 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
Reid Kleckner876330d2016-02-12 21:48:30 +00001904 BytePrefix +=
1905 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001906 BytePrefix +=
1907 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1908 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001909 }
1910 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
1911 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001912}
1913
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001914void CodeViewDebug::endFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001915 if (!Asm || !CurFn) // We haven't created any debug info for this function.
1916 return;
1917
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001918 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00001919 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001920 assert(CurFn == &FnDebugInfo[GV]);
1921
Pete Cooperadebb932016-03-11 02:14:16 +00001922 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00001923
1924 DebugHandlerBase::endFunction(MF);
1925
Reid Kleckner2214ed82016-01-29 00:49:42 +00001926 // Don't emit anything if we don't have any line tables.
1927 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001928 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001929 CurFn = nullptr;
1930 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00001931 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001932
1933 CurFn->End = Asm->getFunctionEnd();
1934
Craig Topper353eda42014-04-24 06:44:33 +00001935 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001936}
1937
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001938void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001939 DebugHandlerBase::beginInstruction(MI);
1940
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001941 // Ignore DBG_VALUE locations and function prologue.
David Majnemer67f684e2016-07-28 05:03:22 +00001942 if (!Asm || !CurFn || MI->isDebugValue() ||
1943 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001944 return;
1945 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001946 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001947 return;
1948 maybeRecordLocation(DL, Asm->MF);
1949}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001950
1951MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
1952 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
1953 *EndLabel = MMI->getContext().createTempSymbol();
1954 OS.EmitIntValue(unsigned(Kind), 4);
1955 OS.AddComment("Subsection size");
1956 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
1957 OS.EmitLabel(BeginLabel);
1958 return EndLabel;
1959}
1960
1961void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
1962 OS.EmitLabel(EndLabel);
1963 // Every subsection must be aligned to a 4-byte boundary.
1964 OS.EmitValueToAlignment(4);
1965}
1966
David Majnemer3128b102016-06-15 18:00:01 +00001967void CodeViewDebug::emitDebugInfoForUDTs(
1968 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
1969 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
1970 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
1971 *UDTRecordEnd = MMI->getContext().createTempSymbol();
1972 OS.AddComment("Record length");
1973 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
1974 OS.EmitLabel(UDTRecordBegin);
1975
1976 OS.AddComment("Record kind: S_UDT");
1977 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
1978
1979 OS.AddComment("Type");
1980 OS.EmitIntValue(UDT.second.getIndex(), 4);
1981
1982 emitNullTerminatedSymbolName(OS, UDT.first);
1983 OS.EmitLabel(UDTRecordEnd);
1984 }
1985}
1986
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001987void CodeViewDebug::emitDebugInfoForGlobals() {
1988 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
1989 for (const MDNode *Node : CUs->operands()) {
1990 const auto *CU = cast<DICompileUnit>(Node);
1991
1992 // First, emit all globals that are not in a comdat in a single symbol
1993 // substream. MSVC doesn't like it if the substream is empty, so only open
1994 // it if we have at least one global to emit.
1995 switchToDebugSectionForSymbol(nullptr);
1996 MCSymbol *EndLabel = nullptr;
1997 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Reid Kleckner6d1d2752016-06-09 00:29:00 +00001998 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
David Majnemer577be0f2016-06-15 00:19:52 +00001999 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002000 if (!EndLabel) {
2001 OS.AddComment("Symbol subsection for globals");
2002 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
2003 }
2004 emitDebugInfoForGlobal(G, Asm->getSymbol(GV));
2005 }
Reid Kleckner6d1d2752016-06-09 00:29:00 +00002006 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002007 }
2008 if (EndLabel)
2009 endCVSubsection(EndLabel);
2010
2011 // Second, emit each global that is in a comdat into its own .debug$S
2012 // section along with its own symbol substream.
2013 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Reid Kleckner6d1d2752016-06-09 00:29:00 +00002014 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002015 if (GV->hasComdat()) {
2016 MCSymbol *GVSym = Asm->getSymbol(GV);
2017 OS.AddComment("Symbol subsection for " +
2018 Twine(GlobalValue::getRealLinkageName(GV->getName())));
2019 switchToDebugSectionForSymbol(GVSym);
2020 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
2021 emitDebugInfoForGlobal(G, GVSym);
2022 endCVSubsection(EndLabel);
2023 }
2024 }
2025 }
2026 }
2027}
2028
Hans Wennborgb510b452016-06-23 16:33:53 +00002029void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2030 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2031 for (const MDNode *Node : CUs->operands()) {
2032 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2033 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2034 getTypeIndex(RT);
2035 // FIXME: Add to global/local DTU list.
2036 }
2037 }
2038 }
2039}
2040
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002041void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
2042 MCSymbol *GVSym) {
2043 // DataSym record, see SymbolRecord.h for more info.
2044 // FIXME: Thread local data, etc
2045 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2046 *DataEnd = MMI->getContext().createTempSymbol();
2047 OS.AddComment("Record length");
2048 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2049 OS.EmitLabel(DataBegin);
David Majnemera54fe1a2016-07-07 05:14:21 +00002050 const auto *GV = cast<GlobalVariable>(DIGV->getVariable());
David Majnemer7abd2692016-07-06 21:07:47 +00002051 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002052 if (GV->isThreadLocal()) {
2053 OS.AddComment("Record kind: S_LTHREAD32");
2054 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2055 } else {
2056 OS.AddComment("Record kind: S_LDATA32");
2057 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2058 }
David Majnemer7abd2692016-07-06 21:07:47 +00002059 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002060 if (GV->isThreadLocal()) {
2061 OS.AddComment("Record kind: S_GTHREAD32");
2062 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2063 } else {
2064 OS.AddComment("Record kind: S_GDATA32");
2065 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2066 }
David Majnemer7abd2692016-07-06 21:07:47 +00002067 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002068 OS.AddComment("Type");
2069 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2070 OS.AddComment("DataOffset");
2071 OS.EmitCOFFSecRel32(GVSym);
2072 OS.AddComment("Segment");
2073 OS.EmitCOFFSectionIndex(GVSym);
2074 OS.AddComment("Name");
2075 emitNullTerminatedSymbolName(OS, DIGV->getName());
2076 OS.EmitLabel(DataEnd);
2077}