blob: 13e98c3f99126e8ea14ea9e7a611535fa3806fcd [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)
Zachary Turnerc6d54da2016-09-09 17:46:17 +000043 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), Allocator(),
44 TypeTable(Allocator), CurFn(nullptr) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +000045 // If module doesn't have named metadata anchors or COFF debug section
46 // is not available, skip any debug info related stuff.
47 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
48 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
49 Asm = nullptr;
50 return;
51 }
52
53 // Tell MMI that we have debug info.
54 MMI->setDebugInfoAvailability(true);
55}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000056
Reid Kleckner9533af42016-01-16 00:09:09 +000057StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
58 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000059 if (!Filepath.empty())
60 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000061
Reid Kleckner9533af42016-01-16 00:09:09 +000062 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
63
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000064 // Clang emits directory and relative filename info into the IR, but CodeView
65 // operates on full paths. We could change Clang to emit full paths too, but
66 // that would increase the IR size and probably not needed for other users.
67 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000068 if (Filename.find(':') == 1)
69 Filepath = Filename;
70 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +000071 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000072
73 // Canonicalize the path. We have to do it textually because we may no longer
74 // have access the file in the filesystem.
75 // First, replace all slashes with backslashes.
76 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
77
78 // Remove all "\.\" with "\".
79 size_t Cursor = 0;
80 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
81 Filepath.erase(Cursor, 2);
82
83 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
84 // path should be well-formatted, e.g. start with a drive letter, etc.
85 Cursor = 0;
86 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
87 // Something's wrong if the path starts with "\..\", abort.
88 if (Cursor == 0)
89 break;
90
91 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
92 if (PrevSlash == std::string::npos)
93 // Something's wrong, abort.
94 break;
95
96 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
97 // The next ".." might be following the one we've just erased.
98 Cursor = PrevSlash;
99 }
100
101 // Remove all duplicate backslashes.
102 Cursor = 0;
103 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
104 Filepath.erase(Cursor, 1);
105
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000106 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000107}
108
Reid Kleckner2214ed82016-01-29 00:49:42 +0000109unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
110 unsigned NextId = FileIdMap.size() + 1;
111 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
112 if (Insertion.second) {
113 // We have to compute the full filepath and emit a .cv_file directive.
114 StringRef FullPath = getFullFilepath(F);
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000115 bool Success = OS.EmitCVFileDirective(NextId, FullPath);
116 (void)Success;
117 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000118 }
119 return Insertion.first->second;
120}
121
Reid Kleckner876330d2016-02-12 21:48:30 +0000122CodeViewDebug::InlineSite &
123CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
124 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000125 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
126 InlineSite *Site = &SiteInsertion.first->second;
127 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000128 unsigned ParentFuncId = CurFn->FuncId;
129 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
130 ParentFuncId =
131 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
132 .SiteFuncId;
133
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000134 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000135 OS.EmitCVInlineSiteIdDirective(
136 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
137 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000138 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000139 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000140 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000141 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000142 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000143}
144
David Majnemer6bdc24e2016-07-01 23:12:45 +0000145static StringRef getPrettyScopeName(const DIScope *Scope) {
146 StringRef ScopeName = Scope->getName();
147 if (!ScopeName.empty())
148 return ScopeName;
149
150 switch (Scope->getTag()) {
151 case dwarf::DW_TAG_enumeration_type:
152 case dwarf::DW_TAG_class_type:
153 case dwarf::DW_TAG_structure_type:
154 case dwarf::DW_TAG_union_type:
155 return "<unnamed-tag>";
156 case dwarf::DW_TAG_namespace:
157 return "`anonymous namespace'";
158 }
159
160 return StringRef();
161}
162
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000163static const DISubprogram *getQualifiedNameComponents(
164 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
165 const DISubprogram *ClosestSubprogram = nullptr;
166 while (Scope != nullptr) {
167 if (ClosestSubprogram == nullptr)
168 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000169 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000170 if (!ScopeName.empty())
171 QualifiedNameComponents.push_back(ScopeName);
172 Scope = Scope->getScope().resolve();
173 }
174 return ClosestSubprogram;
175}
176
177static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
178 StringRef TypeName) {
179 std::string FullyQualifiedName;
180 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
181 FullyQualifiedName.append(QualifiedNameComponent);
182 FullyQualifiedName.append("::");
183 }
184 FullyQualifiedName.append(TypeName);
185 return FullyQualifiedName;
186}
187
188static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
189 SmallVector<StringRef, 5> QualifiedNameComponents;
190 getQualifiedNameComponents(Scope, QualifiedNameComponents);
191 return getQualifiedName(QualifiedNameComponents, Name);
192}
193
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000194struct CodeViewDebug::TypeLoweringScope {
195 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
196 ~TypeLoweringScope() {
197 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
198 // inner TypeLoweringScopes don't attempt to emit deferred types.
199 if (CVD.TypeEmissionLevel == 1)
200 CVD.emitDeferredCompleteTypes();
201 --CVD.TypeEmissionLevel;
202 }
203 CodeViewDebug &CVD;
204};
205
David Majnemer6bdc24e2016-07-01 23:12:45 +0000206static std::string getFullyQualifiedName(const DIScope *Ty) {
207 const DIScope *Scope = Ty->getScope().resolve();
208 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
209}
210
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000211TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
212 // No scope means global scope and that uses the zero index.
213 if (!Scope || isa<DIFile>(Scope))
214 return TypeIndex();
215
216 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
217
218 // Check if we've already translated this scope.
219 auto I = TypeIndices.find({Scope, nullptr});
220 if (I != TypeIndices.end())
221 return I->second;
222
223 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000224 std::string ScopeName = getFullyQualifiedName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000225 TypeIndex TI =
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000226 TypeTable.writeKnownType(StringIdRecord(TypeIndex(), ScopeName));
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000227 return recordTypeIndexForDINode(Scope, TI);
228}
229
David Majnemer75c3ebf2016-06-02 17:13:53 +0000230TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000231 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000232
David Majnemer75c3ebf2016-06-02 17:13:53 +0000233 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000234 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000235 if (I != TypeIndices.end())
236 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000237
Reid Klecknerac945e22016-06-17 16:11:20 +0000238 // The display name includes function template arguments. Drop them to match
239 // MSVC.
240 StringRef DisplayName = SP->getDisplayName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000241
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000242 const DIScope *Scope = SP->getScope().resolve();
243 TypeIndex TI;
244 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
245 // If the scope is a DICompositeType, then this must be a method. Member
246 // function types take some special handling, and require access to the
247 // subprogram.
248 TypeIndex ClassType = getTypeIndex(Class);
249 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
250 DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000251 TI = TypeTable.writeKnownType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000252 } else {
253 // Otherwise, this must be a free function.
254 TypeIndex ParentScope = getScopeIndex(Scope);
255 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000256 TI = TypeTable.writeKnownType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000257 }
258
259 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000260}
261
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000262TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
263 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000264 // Always use the method declaration as the key for the function type. The
265 // method declaration contains the this adjustment.
266 if (SP->getDeclaration())
267 SP = SP->getDeclaration();
268 assert(!SP->getDeclaration() && "should use declaration as key");
269
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000270 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
271 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000272 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000273 if (I != TypeIndices.end())
274 return I->second;
275
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000276 // Make sure complete type info for the class is emitted *after* the member
277 // function type, as the complete class type is likely to reference this
278 // member function type.
279 TypeLoweringScope S(*this);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000280 TypeIndex TI =
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000281 lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000282 return recordTypeIndexForDINode(SP, TI, Class);
283}
284
Amjad Aboudacee5682016-07-12 12:06:34 +0000285TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
286 TypeIndex TI,
287 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000288 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000289 (void)InsertResult;
290 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000291 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000292}
293
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000294unsigned CodeViewDebug::getPointerSizeInBytes() {
295 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
296}
297
Reid Kleckner876330d2016-02-12 21:48:30 +0000298void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
299 const DILocation *InlinedAt) {
300 if (InlinedAt) {
301 // This variable was inlined. Associate it with the InlineSite.
302 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
303 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
304 Site.InlinedLocals.emplace_back(Var);
305 } else {
306 // This variable goes in the main ProcSym.
307 CurFn->Locals.emplace_back(Var);
308 }
309}
310
Reid Kleckner829365a2016-02-11 19:41:47 +0000311static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
312 const DILocation *Loc) {
313 auto B = Locs.begin(), E = Locs.end();
314 if (std::find(B, E, Loc) == E)
315 Locs.push_back(Loc);
316}
317
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000318void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000319 const MachineFunction *MF) {
320 // Skip this instruction if it has the same location as the previous one.
321 if (DL == CurFn->LastLoc)
322 return;
323
324 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000325 if (!Scope)
326 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000327
David Majnemerc3340db2016-01-13 01:05:23 +0000328 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000329 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
330 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
331 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000332 return;
333
Reid Kleckner2214ed82016-01-29 00:49:42 +0000334 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
335 if (CI.getStartColumn() != DL.getCol())
336 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000337
Reid Kleckner2214ed82016-01-29 00:49:42 +0000338 if (!CurFn->HaveLineInfo)
339 CurFn->HaveLineInfo = true;
340 unsigned FileId = 0;
341 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
342 FileId = CurFn->LastFileId;
343 else
344 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
345 CurFn->LastLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000346
347 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000348 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000349 const DILocation *Loc = DL.get();
350
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000351 // If this location was actually inlined from somewhere else, give it the ID
352 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000353 FuncId =
354 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000355
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000356 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000357 bool FirstLoc = true;
358 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000359 InlineSite &Site =
360 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000361 if (!FirstLoc)
362 addLocIfNotPresent(Site.ChildSites, Loc);
363 FirstLoc = false;
364 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000365 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000366 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000367 }
368
Reid Klecknerdac21b42016-02-03 21:15:48 +0000369 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000370 /*PrologueEnd=*/false, /*IsStmt=*/false,
371 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000372}
373
Reid Kleckner5d122f82016-05-25 23:16:12 +0000374void CodeViewDebug::emitCodeViewMagicVersion() {
375 OS.EmitValueToAlignment(4);
376 OS.AddComment("Debug section magic");
377 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
378}
379
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000380void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000381 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000382 return;
383
384 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000385
386 // The COFF .debug$S section consists of several subsections, each starting
387 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
388 // of the payload followed by the payload itself. The subsections are 4-byte
389 // aligned.
390
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000391 // Use the generic .debug$S section, and make a subsection for all the inlined
392 // subprograms.
393 switchToDebugSectionForSymbol(nullptr);
Reid Kleckner5d122f82016-05-25 23:16:12 +0000394 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000395
Reid Kleckner2214ed82016-01-29 00:49:42 +0000396 // Emit per-function debug information.
397 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000398 if (!P.first->isDeclarationForLinker())
399 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000400
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000401 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000402 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000403 emitDebugInfoForGlobals();
404
Hans Wennborgb510b452016-06-23 16:33:53 +0000405 // Emit retained types.
406 emitDebugInfoForRetainedTypes();
407
Reid Kleckner5d122f82016-05-25 23:16:12 +0000408 // Switch back to the generic .debug$S section after potentially processing
409 // comdat symbol sections.
410 switchToDebugSectionForSymbol(nullptr);
411
David Majnemer3128b102016-06-15 18:00:01 +0000412 // Emit UDT records for any types used by global variables.
413 if (!GlobalUDTs.empty()) {
414 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
415 emitDebugInfoForUDTs(GlobalUDTs);
416 endCVSubsection(SymbolsEnd);
417 }
418
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000419 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000420 OS.AddComment("File index to string table offset subsection");
421 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000422
423 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000424 OS.AddComment("String table");
425 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000426
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000427 // Emit type information last, so that any types we translate while emitting
428 // function info are included.
429 emitTypeInformation();
430
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000431 clear();
432}
433
David Majnemerb9456a52016-03-14 05:15:09 +0000434static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
435 // Microsoft's linker seems to have trouble with symbol names longer than
436 // 0xffd8 bytes.
437 S = S.substr(0, 0xffd8);
438 SmallString<32> NullTerminatedString(S);
439 NullTerminatedString.push_back('\0');
440 OS.EmitBytes(NullTerminatedString);
441}
442
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000443void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000444 // Do nothing if we have no debug info or if no non-trivial types were emitted
445 // to TypeTable during codegen.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000446 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
Reid Klecknerfbd77872016-03-18 18:54:32 +0000447 if (!CU_Nodes)
448 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000449 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000450 return;
451
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000452 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000453 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000454 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000455
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000456 SmallString<8> CommentPrefix;
457 if (OS.isVerboseAsm()) {
458 CommentPrefix += '\t';
459 CommentPrefix += Asm->MAI->getCommentString();
460 CommentPrefix += ' ';
461 }
462
463 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
Reid Kleckner2280f932016-05-23 20:23:46 +0000464 TypeTable.ForEachRecord(
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000465 [&](TypeIndex Index, StringRef Record) {
466 if (OS.isVerboseAsm()) {
467 // Emit a block comment describing the type record for readability.
468 SmallString<512> CommentBlock;
469 raw_svector_ostream CommentOS(CommentBlock);
470 ScopedPrinter SP(CommentOS);
471 SP.setPrefix(CommentPrefix);
472 CVTD.setPrinter(&SP);
Reid Klecknerc92e9462016-07-01 18:05:56 +0000473 Error E = CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
474 if (E) {
475 logAllUnhandledErrors(std::move(E), errs(), "error: ");
476 llvm_unreachable("produced malformed type record");
477 }
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000478 // emitRawComment will insert its own tab and comment string before
479 // the first line, so strip off our first one. It also prints its own
480 // newline.
481 OS.emitRawComment(
482 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Reid Klecknerc92e9462016-07-01 18:05:56 +0000483 } else {
484#ifndef NDEBUG
485 // Assert that the type data is valid even if we aren't dumping
486 // comments. The MSVC linker doesn't do much type record validation,
487 // so the first link of an invalid type record can succeed while
488 // subsequent links will fail with LNK1285.
Zachary Turnerd66889c2016-07-28 19:12:28 +0000489 ByteStream Stream({Record.bytes_begin(), Record.bytes_end()});
Reid Klecknerc92e9462016-07-01 18:05:56 +0000490 CVTypeArray Types;
491 StreamReader Reader(Stream);
492 Error E = Reader.readArray(Types, Reader.getLength());
493 if (!E) {
494 TypeVisitorCallbacks C;
495 E = CVTypeVisitor(C).visitTypeStream(Types);
496 }
497 if (E) {
498 logAllUnhandledErrors(std::move(E), errs(), "error: ");
499 llvm_unreachable("produced malformed type record");
500 }
501#endif
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000502 }
503 OS.EmitBinaryData(Record);
Reid Kleckner2280f932016-05-23 20:23:46 +0000504 });
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000505}
506
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000507namespace {
508
509static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
510 switch (DWLang) {
511 case dwarf::DW_LANG_C:
512 case dwarf::DW_LANG_C89:
513 case dwarf::DW_LANG_C99:
514 case dwarf::DW_LANG_C11:
515 case dwarf::DW_LANG_ObjC:
516 return SourceLanguage::C;
517 case dwarf::DW_LANG_C_plus_plus:
518 case dwarf::DW_LANG_C_plus_plus_03:
519 case dwarf::DW_LANG_C_plus_plus_11:
520 case dwarf::DW_LANG_C_plus_plus_14:
521 return SourceLanguage::Cpp;
522 case dwarf::DW_LANG_Fortran77:
523 case dwarf::DW_LANG_Fortran90:
524 case dwarf::DW_LANG_Fortran03:
525 case dwarf::DW_LANG_Fortran08:
526 return SourceLanguage::Fortran;
527 case dwarf::DW_LANG_Pascal83:
528 return SourceLanguage::Pascal;
529 case dwarf::DW_LANG_Cobol74:
530 case dwarf::DW_LANG_Cobol85:
531 return SourceLanguage::Cobol;
532 case dwarf::DW_LANG_Java:
533 return SourceLanguage::Java;
534 default:
535 // There's no CodeView representation for this language, and CV doesn't
536 // have an "unknown" option for the language field, so we'll use MASM,
537 // as it's very low level.
538 return SourceLanguage::Masm;
539 }
540}
541
542struct Version {
543 int Part[4];
544};
545
546// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
547// the version number.
548static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000549 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000550 int N = 0;
551 for (const char C : Name) {
552 if (isdigit(C)) {
553 V.Part[N] *= 10;
554 V.Part[N] += C - '0';
555 } else if (C == '.') {
556 ++N;
557 if (N >= 4)
558 return V;
559 } else if (N > 0)
560 return V;
561 }
562 return V;
563}
564
565static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
566 switch (Type) {
567 case Triple::ArchType::x86:
568 return CPUType::Pentium3;
569 case Triple::ArchType::x86_64:
570 return CPUType::X64;
571 case Triple::ArchType::thumb:
572 return CPUType::Thumb;
573 default:
574 report_fatal_error("target architecture doesn't map to a CodeView "
575 "CPUType");
576 }
577}
578
579} // anonymous namespace
580
581void CodeViewDebug::emitCompilerInformation() {
582 MCContext &Context = MMI->getContext();
583 MCSymbol *CompilerBegin = Context.createTempSymbol(),
584 *CompilerEnd = Context.createTempSymbol();
585 OS.AddComment("Record length");
586 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
587 OS.EmitLabel(CompilerBegin);
588 OS.AddComment("Record kind: S_COMPILE3");
589 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
590 uint32_t Flags = 0;
591
592 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
593 const MDNode *Node = *CUs->operands().begin();
594 const auto *CU = cast<DICompileUnit>(Node);
595
596 // The low byte of the flags indicates the source language.
597 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
598 // TODO: Figure out which other flags need to be set.
599
600 OS.AddComment("Flags and language");
601 OS.EmitIntValue(Flags, 4);
602
603 OS.AddComment("CPUType");
604 CPUType CPU =
605 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
606 OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
607
608 StringRef CompilerVersion = CU->getProducer();
609 Version FrontVer = parseVersion(CompilerVersion);
610 OS.AddComment("Frontend version");
611 for (int N = 0; N < 4; ++N)
612 OS.EmitIntValue(FrontVer.Part[N], 2);
613
614 // Some Microsoft tools, like Binscope, expect a backend version number of at
615 // least 8.something, so we'll coerce the LLVM version into a form that
616 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000617 Version BackVer = {{
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000618 1000 * LLVM_VERSION_MAJOR +
619 10 * LLVM_VERSION_MINOR +
620 LLVM_VERSION_PATCH,
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000621 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000622 OS.AddComment("Backend version");
623 for (int N = 0; N < 4; ++N)
624 OS.EmitIntValue(BackVer.Part[N], 2);
625
626 OS.AddComment("Null-terminated compiler version string");
627 emitNullTerminatedSymbolName(OS, CompilerVersion);
628
629 OS.EmitLabel(CompilerEnd);
630}
631
Reid Kleckner5d122f82016-05-25 23:16:12 +0000632void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000633 if (InlinedSubprograms.empty())
634 return;
635
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000636 OS.AddComment("Inlinee lines subsection");
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000637 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000638
639 // We don't provide any extra file info.
640 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000641 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000642 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
643
644 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000645 assert(TypeIndices.count({SP, nullptr}));
646 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000647
David Majnemer30579ec2016-02-02 23:18:23 +0000648 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000649 unsigned FileId = maybeRecordFile(SP->getFile());
650 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
651 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000652 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000653 // The filechecksum table uses 8 byte entries for now, and file ids start at
654 // 1.
655 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000656 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000657 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000658 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000659 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000660 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000661 OS.EmitIntValue(SP->getLine(), 4);
662 }
663
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000664 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000665}
666
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000667void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
668 const DILocation *InlinedAt,
669 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000670 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
671 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000672
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000673 assert(TypeIndices.count({Site.Inlinee, nullptr}));
674 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000675
676 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000677 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000678 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000679 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000680 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000681 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000682
Reid Klecknerdac21b42016-02-03 21:15:48 +0000683 OS.AddComment("PtrParent");
684 OS.EmitIntValue(0, 4);
685 OS.AddComment("PtrEnd");
686 OS.EmitIntValue(0, 4);
687 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000688 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000689
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000690 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
691 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000692
693 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000694 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000695
696 OS.EmitLabel(InlineEnd);
697
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000698 emitLocalVariableList(Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000699
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000700 // Recurse on child inlined call sites before closing the scope.
701 for (const DILocation *ChildSite : Site.ChildSites) {
702 auto I = FI.InlineSites.find(ChildSite);
703 assert(I != FI.InlineSites.end() &&
704 "child site not in function inline site map");
705 emitInlinedCallSite(FI, ChildSite, I->second);
706 }
707
708 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000709 OS.AddComment("Record length");
710 OS.EmitIntValue(2, 2); // RecordLength
711 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000712 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000713}
714
Reid Kleckner5d122f82016-05-25 23:16:12 +0000715void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
716 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
717 // comdat key. A section may be comdat because of -ffunction-sections or
718 // because it is comdat in the IR.
719 MCSectionCOFF *GVSec =
720 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
721 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
722
723 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
724 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
725 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
726
727 OS.SwitchSection(DebugSec);
728
729 // Emit the magic version number if this is the first time we've switched to
730 // this section.
731 if (ComdatDebugSections.insert(DebugSec).second)
732 emitCodeViewMagicVersion();
733}
734
Reid Kleckner2214ed82016-01-29 00:49:42 +0000735void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
736 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000737 // For each function there is a separate subsection
738 // which holds the PC to file:line table.
739 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000740 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000741
Reid Kleckner5d122f82016-05-25 23:16:12 +0000742 // Switch to the to a comdat section, if appropriate.
743 switchToDebugSectionForSymbol(Fn);
744
Reid Klecknerac945e22016-06-17 16:11:20 +0000745 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000746 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000747 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000748 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000749
750 // If we have a display name, build the fully qualified name by walking the
751 // chain of scopes.
David Majnemer67f684e2016-07-28 05:03:22 +0000752 if (!SP->getDisplayName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000753 FuncName =
754 getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000755
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000756 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000757 if (FuncName.empty())
758 FuncName = GlobalValue::getRealLinkageName(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000759
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000760 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000761 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000762 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000763 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000764 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
765 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000766 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000767 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000768 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000769
Reid Kleckner4ad127f2016-09-14 21:49:21 +0000770 if (GV->hasLocalLinkage()) {
771 OS.AddComment("Record kind: S_LPROC32_ID");
772 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
773 } else {
774 OS.AddComment("Record kind: S_GPROC32_ID");
775 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
776 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000777
David Majnemer30579ec2016-02-02 23:18:23 +0000778 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000779 OS.AddComment("PtrParent");
780 OS.EmitIntValue(0, 4);
781 OS.AddComment("PtrEnd");
782 OS.EmitIntValue(0, 4);
783 OS.AddComment("PtrNext");
784 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000785 // This is the important bit that tells the debugger where the function
786 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000787 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000788 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000789 OS.AddComment("Offset after prologue");
790 OS.EmitIntValue(0, 4);
791 OS.AddComment("Offset before epilogue");
792 OS.EmitIntValue(0, 4);
793 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000794 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000795 OS.AddComment("Function section relative address");
796 OS.EmitCOFFSecRel32(Fn);
797 OS.AddComment("Function section index");
798 OS.EmitCOFFSectionIndex(Fn);
799 OS.AddComment("Flags");
800 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000801 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000802 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000803 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000804 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000805 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000806
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000807 emitLocalVariableList(FI.Locals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000808
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000809 // Emit inlined call site information. Only emit functions inlined directly
810 // into the parent function. We'll emit the other sites recursively as part
811 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000812 for (const DILocation *InlinedAt : FI.ChildSites) {
813 auto I = FI.InlineSites.find(InlinedAt);
814 assert(I != FI.InlineSites.end() &&
815 "child site not in function inline site map");
816 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000817 }
818
David Majnemer3128b102016-06-15 18:00:01 +0000819 if (SP != nullptr)
820 emitDebugInfoForUDTs(LocalUDTs);
821
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000822 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000823 OS.AddComment("Record length");
824 OS.EmitIntValue(0x0002, 2);
825 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000826 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000827 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000828 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000829
Reid Kleckner2214ed82016-01-29 00:49:42 +0000830 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000831 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000832}
833
Reid Kleckner876330d2016-02-12 21:48:30 +0000834CodeViewDebug::LocalVarDefRange
835CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
836 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000837 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000838 DR.DataOffset = Offset;
839 assert(DR.DataOffset == Offset && "truncation");
840 DR.StructOffset = 0;
841 DR.CVRegister = CVRegister;
842 return DR;
843}
844
845CodeViewDebug::LocalVarDefRange
846CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
847 LocalVarDefRange DR;
848 DR.InMemory = 0;
849 DR.DataOffset = 0;
850 DR.StructOffset = 0;
851 DR.CVRegister = CVRegister;
852 return DR;
853}
854
855void CodeViewDebug::collectVariableInfoFromMMITable(
856 DenseSet<InlinedVariable> &Processed) {
857 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
858 const TargetFrameLowering *TFI = TSI.getFrameLowering();
859 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
860
861 for (const MachineModuleInfo::VariableDbgInfo &VI :
862 MMI->getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000863 if (!VI.Var)
864 continue;
865 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
866 "Expected inlined-at fields to agree");
867
Reid Kleckner876330d2016-02-12 21:48:30 +0000868 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000869 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
870
871 // If variable scope is not found then skip this variable.
872 if (!Scope)
873 continue;
874
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000875 // Get the frame register used and the offset.
876 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000877 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
878 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000879
880 // Calculate the label ranges.
Reid Kleckner876330d2016-02-12 21:48:30 +0000881 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000882 for (const InsnRange &Range : Scope->getRanges()) {
883 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
884 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000885 End = End ? End : Asm->getFunctionEnd();
886 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000887 }
888
Reid Kleckner876330d2016-02-12 21:48:30 +0000889 LocalVariable Var;
890 Var.DIVar = VI.Var;
891 Var.DefRanges.emplace_back(std::move(DefRange));
892 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
893 }
894}
895
896void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
897 DenseSet<InlinedVariable> Processed;
898 // Grab the variable info that was squirreled away in the MMI side-table.
899 collectVariableInfoFromMMITable(Processed);
900
901 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
902
903 for (const auto &I : DbgValues) {
904 InlinedVariable IV = I.first;
905 if (Processed.count(IV))
906 continue;
907 const DILocalVariable *DIVar = IV.first;
908 const DILocation *InlinedAt = IV.second;
909
910 // Instruction ranges, specifying where IV is accessible.
911 const auto &Ranges = I.second;
912
913 LexicalScope *Scope = nullptr;
914 if (InlinedAt)
915 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
916 else
917 Scope = LScopes.findLexicalScope(DIVar->getScope());
918 // If variable scope is not found then skip this variable.
919 if (!Scope)
920 continue;
921
922 LocalVariable Var;
923 Var.DIVar = DIVar;
924
925 // Calculate the definition ranges.
926 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
927 const InsnRange &Range = *I;
928 const MachineInstr *DVInst = Range.first;
929 assert(DVInst->isDebugValue() && "Invalid History entry");
930 const DIExpression *DIExpr = DVInst->getDebugExpression();
931
932 // Bail if there is a complex DWARF expression for now.
933 if (DIExpr && DIExpr->getNumElements() > 0)
934 continue;
935
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000936 // Bail if operand 0 is not a valid register. This means the variable is a
937 // simple constant, or is described by a complex expression.
938 // FIXME: Find a way to represent constant variables, since they are
939 // relatively common.
940 unsigned Reg =
941 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
942 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +0000943 continue;
944
Reid Kleckner876330d2016-02-12 21:48:30 +0000945 // Handle the two cases we can handle: indirect in memory and in register.
946 bool IsIndirect = DVInst->getOperand(1).isImm();
947 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
948 {
949 LocalVarDefRange DefRange;
950 if (IsIndirect) {
951 int64_t Offset = DVInst->getOperand(1).getImm();
952 DefRange = createDefRangeMem(CVReg, Offset);
953 } else {
954 DefRange = createDefRangeReg(CVReg);
955 }
956 if (Var.DefRanges.empty() ||
957 Var.DefRanges.back().isDifferentLocation(DefRange)) {
958 Var.DefRanges.emplace_back(std::move(DefRange));
959 }
960 }
961
962 // Compute the label range.
963 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
964 const MCSymbol *End = getLabelAfterInsn(Range.second);
965 if (!End) {
966 if (std::next(I) != E)
967 End = getLabelBeforeInsn(std::next(I)->first);
968 else
969 End = Asm->getFunctionEnd();
970 }
971
972 // If the last range end is our begin, just extend the last range.
973 // Otherwise make a new range.
974 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
975 Var.DefRanges.back().Ranges;
976 if (!Ranges.empty() && Ranges.back().second == Begin)
977 Ranges.back().second = End;
978 else
979 Ranges.emplace_back(Begin, End);
980
981 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000982 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000983
984 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000985 }
986}
987
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000988void CodeViewDebug::beginFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000989 assert(!CurFn && "Can't process two functions at once!");
990
David Majnemer67f684e2016-07-28 05:03:22 +0000991 if (!Asm || !MMI->hasDebugInfo() || !MF->getFunction()->getSubprogram())
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000992 return;
993
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000994 DebugHandlerBase::beginFunction(MF);
995
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000996 const Function *GV = MF->getFunction();
997 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000998 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +0000999 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001000 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001001
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001002 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1003
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001004 // Find the end of the function prolog. First known non-DBG_VALUE and
1005 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001006 // FIXME: is there a simpler a way to do this? Can we just search
1007 // for the first instruction of the function, not the last of the prolog?
1008 DebugLoc PrologEndLoc;
1009 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001010 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001011 for (const auto &MI : MBB) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001012 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1013 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001014 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001015 break;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001016 } else if (!MI.isDebugValue()) {
1017 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001018 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001019 }
1020 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001021
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001022 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001023 if (PrologEndLoc && !EmptyPrologue) {
1024 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001025 maybeRecordLocation(FnStartDL, MF);
1026 }
1027}
1028
Hans Wennborg4b63a982016-06-23 22:57:25 +00001029void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001030 // Don't record empty UDTs.
1031 if (Ty->getName().empty())
1032 return;
1033
Hans Wennborg4b63a982016-06-23 22:57:25 +00001034 SmallVector<StringRef, 5> QualifiedNameComponents;
1035 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1036 Ty->getScope().resolve(), QualifiedNameComponents);
1037
1038 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001039 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001040
1041 if (ClosestSubprogram == nullptr)
1042 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1043 else if (ClosestSubprogram == CurrentSubprogram)
1044 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1045
1046 // TODO: What if the ClosestSubprogram is neither null or the current
1047 // subprogram? Currently, the UDT just gets dropped on the floor.
1048 //
1049 // The current behavior is not desirable. To get maximal fidelity, we would
1050 // need to perform all type translation before beginning emission of .debug$S
1051 // and then make LocalUDTs a member of FunctionInfo
1052}
1053
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001054TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001055 // Generic dispatch for lowering an unknown type.
1056 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001057 case dwarf::DW_TAG_array_type:
1058 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001059 case dwarf::DW_TAG_typedef:
1060 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001061 case dwarf::DW_TAG_base_type:
1062 return lowerTypeBasic(cast<DIBasicType>(Ty));
1063 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001064 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1065 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1066 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001067 case dwarf::DW_TAG_reference_type:
1068 case dwarf::DW_TAG_rvalue_reference_type:
1069 return lowerTypePointer(cast<DIDerivedType>(Ty));
1070 case dwarf::DW_TAG_ptr_to_member_type:
1071 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1072 case dwarf::DW_TAG_const_type:
1073 case dwarf::DW_TAG_volatile_type:
1074 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001075 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001076 if (ClassTy) {
1077 // The member function type of a member function pointer has no
1078 // ThisAdjustment.
1079 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1080 /*ThisAdjustment=*/0);
1081 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001082 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001083 case dwarf::DW_TAG_enumeration_type:
1084 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001085 case dwarf::DW_TAG_class_type:
1086 case dwarf::DW_TAG_structure_type:
1087 return lowerTypeClass(cast<DICompositeType>(Ty));
1088 case dwarf::DW_TAG_union_type:
1089 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001090 default:
1091 // Use the null type index.
1092 return TypeIndex();
1093 }
1094}
1095
David Majnemerd065e232016-06-02 06:21:37 +00001096TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001097 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1098 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001099 StringRef TypeName = Ty->getName();
1100
Hans Wennborg4b63a982016-06-23 22:57:25 +00001101 addToUDTs(Ty, UnderlyingTypeIndex);
David Majnemer3128b102016-06-15 18:00:01 +00001102
David Majnemerd065e232016-06-02 06:21:37 +00001103 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001104 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001105 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001106 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001107 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001108 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001109
David Majnemerd065e232016-06-02 06:21:37 +00001110 return UnderlyingTypeIndex;
1111}
1112
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001113TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1114 DITypeRef ElementTypeRef = Ty->getBaseType();
1115 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1116 // IndexType is size_t, which depends on the bitness of the target.
1117 TypeIndex IndexType = Asm->MAI->getPointerSize() == 8
1118 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1119 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001120
1121 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1122
Amjad Aboudacee5682016-07-12 12:06:34 +00001123
Reid Kleckner10762882016-09-09 17:29:36 +00001124 // We want to assert that the element type multiplied by the array lengths
1125 // match the size of the overall array. However, if we don't have complete
1126 // type information for the base type, we can't make this assertion. This
1127 // happens if limited debug info is enabled in this case:
1128 // struct VTableOptzn { VTableOptzn(); virtual ~VTableOptzn(); };
1129 // VTableOptzn array[3];
1130 // The DICompositeType of VTableOptzn will have size zero, and the array will
1131 // have size 3 * sizeof(void*), and we should avoid asserting.
1132 //
1133 // There is a related bug in the front-end where an array of a structure,
1134 // which was declared as incomplete structure first, ends up not getting a
1135 // size assigned to it. (PR28303)
Amjad Aboudacee5682016-07-12 12:06:34 +00001136 // Example:
1137 // struct A(*p)[3];
1138 // struct A { int f; } a[3];
Reid Kleckner10762882016-09-09 17:29:36 +00001139 bool PartiallyIncomplete = false;
1140 if (Ty->getSizeInBits() == 0 || ElementSize == 0) {
1141 PartiallyIncomplete = true;
Amjad Aboudacee5682016-07-12 12:06:34 +00001142 }
1143
1144 // Add subranges to array type.
1145 DINodeArray Elements = Ty->getElements();
1146 for (int i = Elements.size() - 1; i >= 0; --i) {
1147 const DINode *Element = Elements[i];
1148 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1149
1150 const DISubrange *Subrange = cast<DISubrange>(Element);
1151 assert(Subrange->getLowerBound() == 0 &&
1152 "codeview doesn't support subranges with lower bounds");
1153 int64_t Count = Subrange->getCount();
1154
1155 // Variable Length Array (VLA) has Count equal to '-1'.
1156 // Replace with Count '1', assume it is the minimum VLA length.
1157 // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
1158 if (Count == -1) {
1159 Count = 1;
Reid Kleckner10762882016-09-09 17:29:36 +00001160 PartiallyIncomplete = true;
Amjad Aboudacee5682016-07-12 12:06:34 +00001161 }
1162
Amjad Aboudacee5682016-07-12 12:06:34 +00001163 // Update the element size and element type index for subsequent subranges.
1164 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001165
1166 // If this is the outermost array, use the size from the array. It will be
1167 // more accurate if PartiallyIncomplete is true.
1168 uint64_t ArraySize =
1169 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1170
1171 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001172 ElementTypeIndex = TypeTable.writeKnownType(
Reid Kleckner10762882016-09-09 17:29:36 +00001173 ArrayRecord(ElementTypeIndex, IndexType, ArraySize, Name));
Amjad Aboudacee5682016-07-12 12:06:34 +00001174 }
1175
Reid Kleckner10762882016-09-09 17:29:36 +00001176 (void)PartiallyIncomplete;
1177 assert(PartiallyIncomplete || ElementSize == (Ty->getSizeInBits() / 8));
Amjad Aboudacee5682016-07-12 12:06:34 +00001178
1179 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001180}
1181
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001182TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1183 TypeIndex Index;
1184 dwarf::TypeKind Kind;
1185 uint32_t ByteSize;
1186
1187 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001188 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001189
1190 SimpleTypeKind STK = SimpleTypeKind::None;
1191 switch (Kind) {
1192 case dwarf::DW_ATE_address:
1193 // FIXME: Translate
1194 break;
1195 case dwarf::DW_ATE_boolean:
1196 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001197 case 1: STK = SimpleTypeKind::Boolean8; break;
1198 case 2: STK = SimpleTypeKind::Boolean16; break;
1199 case 4: STK = SimpleTypeKind::Boolean32; break;
1200 case 8: STK = SimpleTypeKind::Boolean64; break;
1201 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001202 }
1203 break;
1204 case dwarf::DW_ATE_complex_float:
1205 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001206 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001207 case 4: STK = SimpleTypeKind::Complex32; break;
1208 case 8: STK = SimpleTypeKind::Complex64; break;
1209 case 10: STK = SimpleTypeKind::Complex80; break;
1210 case 16: STK = SimpleTypeKind::Complex128; break;
1211 }
1212 break;
1213 case dwarf::DW_ATE_float:
1214 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001215 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001216 case 4: STK = SimpleTypeKind::Float32; break;
1217 case 6: STK = SimpleTypeKind::Float48; break;
1218 case 8: STK = SimpleTypeKind::Float64; break;
1219 case 10: STK = SimpleTypeKind::Float80; break;
1220 case 16: STK = SimpleTypeKind::Float128; break;
1221 }
1222 break;
1223 case dwarf::DW_ATE_signed:
1224 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001225 case 1: STK = SimpleTypeKind::SByte; break;
1226 case 2: STK = SimpleTypeKind::Int16Short; break;
1227 case 4: STK = SimpleTypeKind::Int32; break;
1228 case 8: STK = SimpleTypeKind::Int64Quad; break;
1229 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001230 }
1231 break;
1232 case dwarf::DW_ATE_unsigned:
1233 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001234 case 1: STK = SimpleTypeKind::Byte; break;
1235 case 2: STK = SimpleTypeKind::UInt16Short; break;
1236 case 4: STK = SimpleTypeKind::UInt32; break;
1237 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1238 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001239 }
1240 break;
1241 case dwarf::DW_ATE_UTF:
1242 switch (ByteSize) {
1243 case 2: STK = SimpleTypeKind::Character16; break;
1244 case 4: STK = SimpleTypeKind::Character32; break;
1245 }
1246 break;
1247 case dwarf::DW_ATE_signed_char:
1248 if (ByteSize == 1)
1249 STK = SimpleTypeKind::SignedCharacter;
1250 break;
1251 case dwarf::DW_ATE_unsigned_char:
1252 if (ByteSize == 1)
1253 STK = SimpleTypeKind::UnsignedCharacter;
1254 break;
1255 default:
1256 break;
1257 }
1258
1259 // Apply some fixups based on the source-level type name.
1260 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1261 STK = SimpleTypeKind::Int32Long;
1262 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1263 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001264 if (STK == SimpleTypeKind::UInt16Short &&
1265 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001266 STK = SimpleTypeKind::WideCharacter;
1267 if ((STK == SimpleTypeKind::SignedCharacter ||
1268 STK == SimpleTypeKind::UnsignedCharacter) &&
1269 Ty->getName() == "char")
1270 STK = SimpleTypeKind::NarrowCharacter;
1271
1272 return TypeIndex(STK);
1273}
1274
1275TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1276 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1277
1278 // Pointers to simple types can use SimpleTypeMode, rather than having a
1279 // dedicated pointer type record.
1280 if (PointeeTI.isSimple() &&
1281 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1282 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1283 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1284 ? SimpleTypeMode::NearPointer64
1285 : SimpleTypeMode::NearPointer32;
1286 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1287 }
1288
1289 PointerKind PK =
1290 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1291 PointerMode PM = PointerMode::Pointer;
1292 switch (Ty->getTag()) {
1293 default: llvm_unreachable("not a pointer tag type");
1294 case dwarf::DW_TAG_pointer_type:
1295 PM = PointerMode::Pointer;
1296 break;
1297 case dwarf::DW_TAG_reference_type:
1298 PM = PointerMode::LValueReference;
1299 break;
1300 case dwarf::DW_TAG_rvalue_reference_type:
1301 PM = PointerMode::RValueReference;
1302 break;
1303 }
1304 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1305 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1306 // do.
1307 PointerOptions PO = PointerOptions::None;
1308 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001309 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001310}
1311
Reid Kleckner6fa15462016-06-17 22:14:39 +00001312static PointerToMemberRepresentation
1313translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1314 // SizeInBytes being zero generally implies that the member pointer type was
1315 // incomplete, which can happen if it is part of a function prototype. In this
1316 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001317 if (IsPMF) {
1318 switch (Flags & DINode::FlagPtrToMemberRep) {
1319 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001320 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1321 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001322 case DINode::FlagSingleInheritance:
1323 return PointerToMemberRepresentation::SingleInheritanceFunction;
1324 case DINode::FlagMultipleInheritance:
1325 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1326 case DINode::FlagVirtualInheritance:
1327 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1328 }
1329 } else {
1330 switch (Flags & DINode::FlagPtrToMemberRep) {
1331 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001332 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1333 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001334 case DINode::FlagSingleInheritance:
1335 return PointerToMemberRepresentation::SingleInheritanceData;
1336 case DINode::FlagMultipleInheritance:
1337 return PointerToMemberRepresentation::MultipleInheritanceData;
1338 case DINode::FlagVirtualInheritance:
1339 return PointerToMemberRepresentation::VirtualInheritanceData;
1340 }
1341 }
1342 llvm_unreachable("invalid ptr to member representation");
1343}
1344
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001345TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1346 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1347 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001348 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001349 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
1350 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001351 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1352 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1353 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001354 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner6fa15462016-06-17 22:14:39 +00001355 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1356 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1357 MemberPointerInfo MPI(
1358 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001359 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001360 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001361}
1362
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001363/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1364/// have a translation, use the NearC convention.
1365static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1366 switch (DwarfCC) {
1367 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1368 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1369 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1370 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1371 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1372 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1373 }
1374 return CallingConvention::NearC;
1375}
1376
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001377TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1378 ModifierOptions Mods = ModifierOptions::None;
1379 bool IsModifier = true;
1380 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001381 while (IsModifier && BaseTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001382 // FIXME: Need to add DWARF tag for __unaligned.
1383 switch (BaseTy->getTag()) {
1384 case dwarf::DW_TAG_const_type:
1385 Mods |= ModifierOptions::Const;
1386 break;
1387 case dwarf::DW_TAG_volatile_type:
1388 Mods |= ModifierOptions::Volatile;
1389 break;
1390 default:
1391 IsModifier = false;
1392 break;
1393 }
1394 if (IsModifier)
1395 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1396 }
1397 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Reid Klecknerdbaa61c2016-08-30 21:48:14 +00001398 return TypeTable.writeKnownType(ModifierRecord(ModifiedTI, Mods));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001399}
1400
David Majnemer75c3ebf2016-06-02 17:13:53 +00001401TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1402 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1403 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1404 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1405
1406 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1407 ArrayRef<TypeIndex> ArgTypeIndices = None;
1408 if (!ReturnAndArgTypeIndices.empty()) {
1409 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1410 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1411 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1412 }
1413
1414 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001415 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001416
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001417 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1418
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001419 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1420 ArgTypeIndices.size(), ArgListIndex);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001421 return TypeTable.writeKnownType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001422}
1423
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001424TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001425 const DIType *ClassTy,
1426 int ThisAdjustment) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001427 // Lower the containing class type.
1428 TypeIndex ClassType = getTypeIndex(ClassTy);
1429
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001430 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1431 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1432 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1433
1434 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1435 ArrayRef<TypeIndex> ArgTypeIndices = None;
1436 if (!ReturnAndArgTypeIndices.empty()) {
1437 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1438 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1439 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1440 }
1441 TypeIndex ThisTypeIndex = TypeIndex::Void();
1442 if (!ArgTypeIndices.empty()) {
1443 ThisTypeIndex = ArgTypeIndices.front();
1444 ArgTypeIndices = ArgTypeIndices.drop_front();
1445 }
1446
1447 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001448 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001449
1450 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1451
1452 // TODO: Need to use the correct values for:
1453 // FunctionOptions
1454 // ThisPointerAdjustment.
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001455 TypeIndex TI = TypeTable.writeKnownType(MemberFunctionRecord(
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001456 ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FunctionOptions::None,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001457 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001458
1459 return TI;
1460}
1461
Reid Kleckner9dac4732016-08-31 15:59:30 +00001462TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
1463 unsigned VSlotCount = Ty->getSizeInBits() / (8 * Asm->MAI->getPointerSize());
1464 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
1465 return TypeTable.writeKnownType(VFTableShapeRecord(Slots));
1466}
1467
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001468static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1469 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001470 case DINode::FlagPrivate: return MemberAccess::Private;
1471 case DINode::FlagPublic: return MemberAccess::Public;
1472 case DINode::FlagProtected: return MemberAccess::Protected;
1473 case 0:
1474 // If there was no explicit access control, provide the default for the tag.
1475 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1476 : MemberAccess::Public;
1477 }
1478 llvm_unreachable("access flags are exclusive");
1479}
1480
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001481static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1482 if (SP->isArtificial())
1483 return MethodOptions::CompilerGenerated;
1484
1485 // FIXME: Handle other MethodOptions.
1486
1487 return MethodOptions::None;
1488}
1489
1490static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1491 bool Introduced) {
1492 switch (SP->getVirtuality()) {
1493 case dwarf::DW_VIRTUALITY_none:
1494 break;
1495 case dwarf::DW_VIRTUALITY_virtual:
1496 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1497 case dwarf::DW_VIRTUALITY_pure_virtual:
1498 return Introduced ? MethodKind::PureIntroducingVirtual
1499 : MethodKind::PureVirtual;
1500 default:
1501 llvm_unreachable("unhandled virtuality case");
1502 }
1503
1504 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1505
1506 return MethodKind::Vanilla;
1507}
1508
Reid Klecknera8d57402016-06-03 15:58:20 +00001509static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1510 switch (Ty->getTag()) {
1511 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1512 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1513 }
1514 llvm_unreachable("unexpected tag");
1515}
1516
Reid Klecknere092dad2016-07-02 00:11:07 +00001517/// Return ClassOptions that should be present on both the forward declaration
1518/// and the defintion of a tag type.
1519static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1520 ClassOptions CO = ClassOptions::None;
1521
1522 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001523 // appear to give every type a linkage name, which may be problematic for us.
1524 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001525 if (!Ty->getIdentifier().empty())
1526 CO |= ClassOptions::HasUniqueName;
1527
1528 // Put the Nested flag on a type if it appears immediately inside a tag type.
1529 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1530 // here. That flag is only set on definitions, and not forward declarations.
1531 const DIScope *ImmediateScope = Ty->getScope().resolve();
1532 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1533 CO |= ClassOptions::Nested;
1534
1535 // Put the Scoped flag on function-local types.
1536 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1537 Scope = Scope->getScope().resolve()) {
1538 if (isa<DISubprogram>(Scope)) {
1539 CO |= ClassOptions::Scoped;
1540 break;
1541 }
1542 }
1543
1544 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001545}
1546
David Majnemer979cb882016-06-16 21:32:16 +00001547TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001548 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001549 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001550 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001551
David Majnemerda9548f2016-06-17 16:13:21 +00001552 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001553 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001554 } else {
1555 FieldListRecordBuilder Fields;
1556 for (const DINode *Element : Ty->getElements()) {
1557 // We assume that the frontend provides all members in source declaration
1558 // order, which is what MSVC does.
1559 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001560 Fields.writeMemberType(EnumeratorRecord(
David Majnemerda9548f2016-06-17 16:13:21 +00001561 MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()),
1562 Enumerator->getName()));
1563 EnumeratorCount++;
1564 }
1565 }
1566 FTI = TypeTable.writeFieldList(Fields);
1567 }
David Majnemer979cb882016-06-16 21:32:16 +00001568
David Majnemer6bdc24e2016-07-01 23:12:45 +00001569 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001570
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001571 return TypeTable.writeKnownType(EnumRecord(EnumeratorCount, CO, FTI, FullName,
1572 Ty->getIdentifier(),
1573 getTypeIndex(Ty->getBaseType())));
David Majnemer979cb882016-06-16 21:32:16 +00001574}
1575
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001576//===----------------------------------------------------------------------===//
1577// ClassInfo
1578//===----------------------------------------------------------------------===//
1579
1580struct llvm::ClassInfo {
1581 struct MemberInfo {
1582 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00001583 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001584 };
1585 // [MemberInfo]
1586 typedef std::vector<MemberInfo> MemberList;
1587
Reid Kleckner156a7232016-06-22 18:31:14 +00001588 typedef TinyPtrVector<const DISubprogram *> MethodsList;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001589 // MethodName -> MethodsList
1590 typedef MapVector<MDString *, MethodsList> MethodsMap;
1591
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001592 /// Base classes.
1593 std::vector<const DIDerivedType *> Inheritance;
1594
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001595 /// Direct members.
1596 MemberList Members;
1597 // Direct overloaded methods gathered by name.
1598 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001599
Reid Kleckner9dac4732016-08-31 15:59:30 +00001600 TypeIndex VShapeTI;
1601
Adrian McCarthy820ca542016-07-06 19:49:51 +00001602 std::vector<const DICompositeType *> NestedClasses;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001603};
1604
1605void CodeViewDebug::clear() {
1606 assert(CurFn == nullptr);
1607 FileIdMap.clear();
1608 FnDebugInfo.clear();
1609 FileToFilepathMap.clear();
1610 LocalUDTs.clear();
1611 GlobalUDTs.clear();
1612 TypeIndices.clear();
1613 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001614}
1615
1616void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1617 const DIDerivedType *DDTy) {
1618 if (!DDTy->getName().empty()) {
1619 Info.Members.push_back({DDTy, 0});
1620 return;
1621 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001622 // An unnamed member must represent a nested struct or union. Add all the
1623 // indirect fields to the current record.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001624 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00001625 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001626 const DIType *Ty = DDTy->getBaseType().resolve();
Reid Kleckner9ff936c2016-06-21 14:56:24 +00001627 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001628 ClassInfo NestedInfo = collectClassInfo(DCTy);
1629 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001630 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001631 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001632}
1633
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001634ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1635 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001636 // Add elements to structure type.
1637 DINodeArray Elements = Ty->getElements();
1638 for (auto *Element : Elements) {
1639 // We assume that the frontend provides all members in source declaration
1640 // order, which is what MSVC does.
1641 if (!Element)
1642 continue;
1643 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001644 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001645 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001646 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001647 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001648 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1649 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001650 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1651 DDTy->getName() == "__vtbl_ptr_type") {
1652 Info.VShapeTI = getTypeIndex(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001653 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1654 // Ignore friend members. It appears that MSVC emitted info about
1655 // friends in the past, but modern versions do not.
1656 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001657 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1658 Info.NestedClasses.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001659 }
1660 // Skip other unrecognized kinds of elements.
1661 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001662 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001663}
1664
Reid Klecknera8d57402016-06-03 15:58:20 +00001665TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1666 // First, construct the forward decl. Don't look into Ty to compute the
1667 // forward decl options, since it might not be available in all TUs.
1668 TypeRecordKind Kind = getRecordKind(Ty);
1669 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001670 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001671 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001672 TypeIndex FwdDeclTI = TypeTable.writeKnownType(ClassRecord(
Reid Klecknera8d57402016-06-03 15:58:20 +00001673 Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(),
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001674 TypeIndex(), TypeIndex(), 0, FullName, Ty->getIdentifier()));
Reid Kleckner643dd832016-06-22 17:15:28 +00001675 if (!Ty->isForwardDecl())
1676 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001677 return FwdDeclTI;
1678}
1679
1680TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1681 // Construct the field list and complete type record.
1682 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00001683 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001684 TypeIndex FieldTI;
1685 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001686 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001687 bool ContainsNestedClass;
1688 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1689 lowerRecordFieldList(Ty);
1690
1691 if (ContainsNestedClass)
1692 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00001693
David Majnemer6bdc24e2016-07-01 23:12:45 +00001694 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001695
Reid Klecknera8d57402016-06-03 15:58:20 +00001696 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00001697
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001698 TypeIndex ClassTI = TypeTable.writeKnownType(ClassRecord(
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001699 Kind, FieldCount, CO, HfaKind::None, WindowsRTClassKind::None, FieldTI,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001700 TypeIndex(), VShapeTI, SizeInBytes, FullName, Ty->getIdentifier()));
Hans Wennborg9a519a02016-06-22 21:22:13 +00001701
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001702 TypeTable.writeKnownType(UdtSourceLineRecord(
1703 ClassTI, TypeTable.writeKnownType(StringIdRecord(
Hans Wennborg9a519a02016-06-22 21:22:13 +00001704 TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1705 Ty->getLine()));
1706
Hans Wennborg4b63a982016-06-23 22:57:25 +00001707 addToUDTs(Ty, ClassTI);
1708
Hans Wennborg9a519a02016-06-22 21:22:13 +00001709 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001710}
1711
1712TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1713 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001714 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001715 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001716 TypeIndex FwdDeclTI = TypeTable.writeKnownType(UnionRecord(
1717 0, CO, HfaKind::None, TypeIndex(), 0, FullName, Ty->getIdentifier()));
Reid Kleckner643dd832016-06-22 17:15:28 +00001718 if (!Ty->isForwardDecl())
1719 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001720 return FwdDeclTI;
1721}
1722
1723TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00001724 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001725 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001726 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001727 bool ContainsNestedClass;
1728 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1729 lowerRecordFieldList(Ty);
1730
1731 if (ContainsNestedClass)
1732 CO |= ClassOptions::ContainsNestedClass;
1733
Reid Klecknera8d57402016-06-03 15:58:20 +00001734 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00001735 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001736
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001737 TypeIndex UnionTI = TypeTable.writeKnownType(
Hans Wennborg9a519a02016-06-22 21:22:13 +00001738 UnionRecord(FieldCount, CO, HfaKind::None, FieldTI, SizeInBytes, FullName,
1739 Ty->getIdentifier()));
1740
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001741 TypeTable.writeKnownType(UdtSourceLineRecord(
1742 UnionTI, TypeTable.writeKnownType(StringIdRecord(
Hans Wennborg9a519a02016-06-22 21:22:13 +00001743 TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1744 Ty->getLine()));
1745
Hans Wennborg4b63a982016-06-23 22:57:25 +00001746 addToUDTs(Ty, UnionTI);
1747
Hans Wennborg9a519a02016-06-22 21:22:13 +00001748 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001749}
1750
Adrian McCarthy820ca542016-07-06 19:49:51 +00001751std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00001752CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1753 // Manually count members. MSVC appears to count everything that generates a
1754 // field list record. Each individual overload in a method overload group
1755 // contributes to this count, even though the overload group is a single field
1756 // list record.
1757 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001758 ClassInfo Info = collectClassInfo(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001759 FieldListRecordBuilder Fields;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001760
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001761 // Create base classes.
1762 for (const DIDerivedType *I : Info.Inheritance) {
1763 if (I->getFlags() & DINode::FlagVirtual) {
1764 // Virtual base.
1765 // FIXME: Emit VBPtrOffset when the frontend provides it.
1766 unsigned VBPtrOffset = 0;
1767 // FIXME: Despite the accessor name, the offset is really in bytes.
1768 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001769 Fields.writeMemberType(VirtualBaseClassRecord(
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001770 translateAccessFlags(Ty->getTag(), I->getFlags()),
1771 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
1772 VBTableIndex));
1773 } else {
1774 assert(I->getOffsetInBits() % 8 == 0 &&
1775 "bases must be on byte boundaries");
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001776 Fields.writeMemberType(BaseClassRecord(
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001777 translateAccessFlags(Ty->getTag(), I->getFlags()),
1778 getTypeIndex(I->getBaseType()), I->getOffsetInBits() / 8));
1779 }
1780 }
1781
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001782 // Create members.
1783 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1784 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1785 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00001786 StringRef MemberName = Member->getName();
1787 MemberAccess Access =
1788 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001789
1790 if (Member->isStaticMember()) {
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001791 Fields.writeMemberType(
David Majnemer9319cbc2016-06-30 03:00:20 +00001792 StaticDataMemberRecord(Access, MemberBaseType, MemberName));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001793 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001794 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00001795 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001796
Reid Kleckner9dac4732016-08-31 15:59:30 +00001797 // Virtual function pointer member.
1798 if ((Member->getFlags() & DINode::FlagArtificial) &&
1799 Member->getName().startswith("_vptr$")) {
1800 Fields.writeMemberType(VFPtrRecord(getTypeIndex(Member->getBaseType())));
1801 MemberCount++;
1802 continue;
1803 }
1804
David Majnemer9319cbc2016-06-30 03:00:20 +00001805 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00001806 uint64_t MemberOffsetInBits =
1807 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001808 if (Member->isBitField()) {
1809 uint64_t StartBitOffset = MemberOffsetInBits;
1810 if (const auto *CI =
1811 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00001812 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001813 }
1814 StartBitOffset -= MemberOffsetInBits;
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001815 MemberBaseType = TypeTable.writeKnownType(BitFieldRecord(
David Majnemer9319cbc2016-06-30 03:00:20 +00001816 MemberBaseType, Member->getSizeInBits(), StartBitOffset));
1817 }
1818 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001819 Fields.writeMemberType(DataMemberRecord(Access, MemberBaseType,
David Majnemer9319cbc2016-06-30 03:00:20 +00001820 MemberOffsetInBytes, MemberName));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001821 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001822 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001823
1824 // Create methods
1825 for (auto &MethodItr : Info.Methods) {
1826 StringRef Name = MethodItr.first->getString();
1827
1828 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00001829 for (const DISubprogram *SP : MethodItr.second) {
1830 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1831 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001832
1833 unsigned VFTableOffset = -1;
1834 if (Introduced)
1835 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1836
1837 Methods.push_back(
1838 OneMethodRecord(MethodType, translateMethodKindFlags(SP, Introduced),
1839 translateMethodOptionFlags(SP),
1840 translateAccessFlags(Ty->getTag(), SP->getFlags()),
1841 VFTableOffset, Name));
1842 MemberCount++;
1843 }
1844 assert(Methods.size() > 0 && "Empty methods map entry");
1845 if (Methods.size() == 1)
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001846 Fields.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001847 else {
1848 TypeIndex MethodList =
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001849 TypeTable.writeKnownType(MethodOverloadListRecord(Methods));
1850 Fields.writeMemberType(
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001851 OverloadedMethodRecord(Methods.size(), MethodList, Name));
1852 }
1853 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001854
1855 // Create nested classes.
1856 for (const DICompositeType *Nested : Info.NestedClasses) {
1857 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001858 Fields.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00001859 MemberCount++;
1860 }
1861
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001862 TypeIndex FieldTI = TypeTable.writeFieldList(Fields);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001863 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Adrian McCarthy820ca542016-07-06 19:49:51 +00001864 !Info.NestedClasses.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00001865}
1866
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001867TypeIndex CodeViewDebug::getVBPTypeIndex() {
1868 if (!VBPType.getIndex()) {
1869 // Make a 'const int *' type.
1870 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001871 TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001872
1873 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1874 : PointerKind::Near32;
1875 PointerMode PM = PointerMode::Pointer;
1876 PointerOptions PO = PointerOptions::None;
1877 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1878
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001879 VBPType = TypeTable.writeKnownType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001880 }
1881
1882 return VBPType;
1883}
1884
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001885TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001886 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001887 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001888
1889 // The null DIType is the void type. Don't try to hash it.
1890 if (!Ty)
1891 return TypeIndex::Void();
1892
Reid Klecknera8d57402016-06-03 15:58:20 +00001893 // Check if we've already translated this type. Don't try to do a
1894 // get-or-create style insertion that caches the hash lookup across the
1895 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001896 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001897 if (I != TypeIndices.end())
1898 return I->second;
1899
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001900 TypeLoweringScope S(*this);
1901 TypeIndex TI = lowerType(Ty, ClassTy);
1902 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00001903}
1904
1905TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1906 const DIType *Ty = TypeRef.resolve();
1907
1908 // The null DIType is the void type. Don't try to hash it.
1909 if (!Ty)
1910 return TypeIndex::Void();
1911
1912 // If this is a non-record type, the complete type index is the same as the
1913 // normal type index. Just call getTypeIndex.
1914 switch (Ty->getTag()) {
1915 case dwarf::DW_TAG_class_type:
1916 case dwarf::DW_TAG_structure_type:
1917 case dwarf::DW_TAG_union_type:
1918 break;
1919 default:
1920 return getTypeIndex(Ty);
1921 }
1922
1923 // Check if we've already translated the complete record type. Lowering a
1924 // complete type should never trigger lowering another complete type, so we
1925 // can reuse the hash table lookup result.
1926 const auto *CTy = cast<DICompositeType>(Ty);
1927 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1928 if (!InsertResult.second)
1929 return InsertResult.first->second;
1930
Reid Kleckner643dd832016-06-22 17:15:28 +00001931 TypeLoweringScope S(*this);
1932
Reid Klecknera8d57402016-06-03 15:58:20 +00001933 // Make sure the forward declaration is emitted first. It's unclear if this
1934 // is necessary, but MSVC does it, and we should follow suit until we can show
1935 // otherwise.
1936 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1937
1938 // Just use the forward decl if we don't have complete type info. This might
1939 // happen if the frontend is using modules and expects the complete definition
1940 // to be emitted elsewhere.
1941 if (CTy->isForwardDecl())
1942 return FwdDeclTI;
1943
1944 TypeIndex TI;
1945 switch (CTy->getTag()) {
1946 case dwarf::DW_TAG_class_type:
1947 case dwarf::DW_TAG_structure_type:
1948 TI = lowerCompleteTypeClass(CTy);
1949 break;
1950 case dwarf::DW_TAG_union_type:
1951 TI = lowerCompleteTypeUnion(CTy);
1952 break;
1953 default:
1954 llvm_unreachable("not a record");
1955 }
1956
1957 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001958 return TI;
1959}
1960
Reid Kleckner643dd832016-06-22 17:15:28 +00001961/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00001962/// and do this until fixpoint, as each complete record type typically
1963/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00001964/// many other record types.
1965void CodeViewDebug::emitDeferredCompleteTypes() {
1966 SmallVector<const DICompositeType *, 4> TypesToEmit;
1967 while (!DeferredCompleteTypes.empty()) {
1968 std::swap(DeferredCompleteTypes, TypesToEmit);
1969 for (const DICompositeType *RecordTy : TypesToEmit)
1970 getCompleteTypeIndex(RecordTy);
1971 TypesToEmit.clear();
1972 }
1973}
1974
Reid Kleckner10dd55c2016-06-24 17:55:40 +00001975void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
1976 // Get the sorted list of parameters and emit them first.
1977 SmallVector<const LocalVariable *, 6> Params;
1978 for (const LocalVariable &L : Locals)
1979 if (L.DIVar->isParameter())
1980 Params.push_back(&L);
1981 std::sort(Params.begin(), Params.end(),
1982 [](const LocalVariable *L, const LocalVariable *R) {
1983 return L->DIVar->getArg() < R->DIVar->getArg();
1984 });
1985 for (const LocalVariable *L : Params)
1986 emitLocalVariable(*L);
1987
1988 // Next emit all non-parameters in the order that we found them.
1989 for (const LocalVariable &L : Locals)
1990 if (!L.DIVar->isParameter())
1991 emitLocalVariable(L);
1992}
1993
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001994void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
1995 // LocalSym record, see SymbolRecord.h for more info.
1996 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
1997 *LocalEnd = MMI->getContext().createTempSymbol();
1998 OS.AddComment("Record length");
1999 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2000 OS.EmitLabel(LocalBegin);
2001
2002 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00002003 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002004
Zachary Turner63a28462016-05-17 23:50:21 +00002005 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002006 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002007 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002008 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002009 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002010
2011 OS.AddComment("TypeIndex");
Reid Klecknera8d57402016-06-03 15:58:20 +00002012 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002013 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002014 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002015 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002016 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002017 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002018 OS.EmitLabel(LocalEnd);
2019
Reid Kleckner876330d2016-02-12 21:48:30 +00002020 // Calculate the on disk prefix of the appropriate def range record. The
2021 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2022 // should be big enough to hold all forms without memory allocation.
2023 SmallString<20> BytePrefix;
2024 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2025 BytePrefix.clear();
2026 // FIXME: Handle bitpieces.
2027 if (DefRange.StructOffset != 0)
2028 continue;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002029
Reid Kleckner876330d2016-02-12 21:48:30 +00002030 if (DefRange.InMemory) {
Zachary Turnera78ecd12016-05-23 18:49:06 +00002031 DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
2032 0, 0, ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00002033 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00002034 BytePrefix +=
2035 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00002036 BytePrefix +=
2037 StringRef(reinterpret_cast<const char *>(&Sym.Header),
2038 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00002039 } else {
2040 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Zachary Turnera78ecd12016-05-23 18:49:06 +00002041 // Unclear what matters here.
2042 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
2043 ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00002044 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
Reid Kleckner876330d2016-02-12 21:48:30 +00002045 BytePrefix +=
2046 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00002047 BytePrefix +=
2048 StringRef(reinterpret_cast<const char *>(&Sym.Header),
2049 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00002050 }
2051 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2052 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002053}
2054
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002055void CodeViewDebug::endFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002056 if (!Asm || !CurFn) // We haven't created any debug info for this function.
2057 return;
2058
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002059 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00002060 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002061 assert(CurFn == &FnDebugInfo[GV]);
2062
Pete Cooperadebb932016-03-11 02:14:16 +00002063 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002064
2065 DebugHandlerBase::endFunction(MF);
2066
Reid Kleckner2214ed82016-01-29 00:49:42 +00002067 // Don't emit anything if we don't have any line tables.
2068 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002069 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002070 CurFn = nullptr;
2071 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002072 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002073
2074 CurFn->End = Asm->getFunctionEnd();
2075
Craig Topper353eda42014-04-24 06:44:33 +00002076 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002077}
2078
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002079void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002080 DebugHandlerBase::beginInstruction(MI);
2081
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002082 // Ignore DBG_VALUE locations and function prologue.
David Majnemer67f684e2016-07-28 05:03:22 +00002083 if (!Asm || !CurFn || MI->isDebugValue() ||
2084 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002085 return;
2086 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00002087 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002088 return;
2089 maybeRecordLocation(DL, Asm->MF);
2090}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002091
2092MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
2093 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2094 *EndLabel = MMI->getContext().createTempSymbol();
2095 OS.EmitIntValue(unsigned(Kind), 4);
2096 OS.AddComment("Subsection size");
2097 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2098 OS.EmitLabel(BeginLabel);
Adrian McCarthyc64acfd2016-09-20 17:20:51 +00002099 if (Kind == ModuleSubstreamKind::Symbols)
2100 emitCompilerInformation();
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002101 return EndLabel;
2102}
2103
2104void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2105 OS.EmitLabel(EndLabel);
2106 // Every subsection must be aligned to a 4-byte boundary.
2107 OS.EmitValueToAlignment(4);
2108}
2109
David Majnemer3128b102016-06-15 18:00:01 +00002110void CodeViewDebug::emitDebugInfoForUDTs(
2111 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
2112 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
2113 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2114 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2115 OS.AddComment("Record length");
2116 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2117 OS.EmitLabel(UDTRecordBegin);
2118
2119 OS.AddComment("Record kind: S_UDT");
2120 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2121
2122 OS.AddComment("Type");
2123 OS.EmitIntValue(UDT.second.getIndex(), 4);
2124
2125 emitNullTerminatedSymbolName(OS, UDT.first);
2126 OS.EmitLabel(UDTRecordEnd);
2127 }
2128}
2129
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002130void CodeViewDebug::emitDebugInfoForGlobals() {
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002131 DenseMap<const DIGlobalVariable *, const GlobalVariable *> GlobalMap;
2132 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
2133 SmallVector<MDNode *, 1> MDs;
2134 GV.getMetadata(LLVMContext::MD_dbg, MDs);
2135 for (MDNode *MD : MDs)
2136 GlobalMap[cast<DIGlobalVariable>(MD)] = &GV;
2137 }
2138
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002139 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2140 for (const MDNode *Node : CUs->operands()) {
2141 const auto *CU = cast<DICompileUnit>(Node);
2142
2143 // First, emit all globals that are not in a comdat in a single symbol
2144 // substream. MSVC doesn't like it if the substream is empty, so only open
2145 // it if we have at least one global to emit.
2146 switchToDebugSectionForSymbol(nullptr);
2147 MCSymbol *EndLabel = nullptr;
2148 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002149 if (const auto *GV = GlobalMap.lookup(G))
David Majnemer577be0f2016-06-15 00:19:52 +00002150 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002151 if (!EndLabel) {
2152 OS.AddComment("Symbol subsection for globals");
2153 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
2154 }
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002155 emitDebugInfoForGlobal(G, GV, Asm->getSymbol(GV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002156 }
2157 }
2158 if (EndLabel)
2159 endCVSubsection(EndLabel);
2160
2161 // Second, emit each global that is in a comdat into its own .debug$S
2162 // section along with its own symbol substream.
2163 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002164 if (const auto *GV = GlobalMap.lookup(G)) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002165 if (GV->hasComdat()) {
2166 MCSymbol *GVSym = Asm->getSymbol(GV);
2167 OS.AddComment("Symbol subsection for " +
2168 Twine(GlobalValue::getRealLinkageName(GV->getName())));
2169 switchToDebugSectionForSymbol(GVSym);
2170 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002171 emitDebugInfoForGlobal(G, GV, GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002172 endCVSubsection(EndLabel);
2173 }
2174 }
2175 }
2176 }
2177}
2178
Hans Wennborgb510b452016-06-23 16:33:53 +00002179void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2180 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2181 for (const MDNode *Node : CUs->operands()) {
2182 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2183 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2184 getTypeIndex(RT);
2185 // FIXME: Add to global/local DTU list.
2186 }
2187 }
2188 }
2189}
2190
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002191void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002192 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002193 MCSymbol *GVSym) {
2194 // DataSym record, see SymbolRecord.h for more info.
2195 // FIXME: Thread local data, etc
2196 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2197 *DataEnd = MMI->getContext().createTempSymbol();
2198 OS.AddComment("Record length");
2199 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2200 OS.EmitLabel(DataBegin);
David Majnemer7abd2692016-07-06 21:07:47 +00002201 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002202 if (GV->isThreadLocal()) {
2203 OS.AddComment("Record kind: S_LTHREAD32");
2204 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2205 } else {
2206 OS.AddComment("Record kind: S_LDATA32");
2207 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2208 }
David Majnemer7abd2692016-07-06 21:07:47 +00002209 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002210 if (GV->isThreadLocal()) {
2211 OS.AddComment("Record kind: S_GTHREAD32");
2212 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2213 } else {
2214 OS.AddComment("Record kind: S_GDATA32");
2215 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2216 }
David Majnemer7abd2692016-07-06 21:07:47 +00002217 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002218 OS.AddComment("Type");
2219 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2220 OS.AddComment("DataOffset");
2221 OS.EmitCOFFSecRel32(GVSym);
2222 OS.AddComment("Segment");
2223 OS.EmitCOFFSectionIndex(GVSym);
2224 OS.AddComment("Name");
2225 emitNullTerminatedSymbolName(OS, DIGV->getName());
2226 OS.EmitLabel(DataEnd);
2227}