blob: 51a5d06b954dcf71e8014a92fb463314e1f99d9a [file] [log] [blame]
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001//===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp --*- C++ -*--===//
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Reid Kleckner70f5bc92016-01-14 19:25:04 +000010// This file contains support for writing Microsoft CodeView debug info.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000011//
12//===----------------------------------------------------------------------===//
13
Reid Kleckner70f5bc92016-01-14 19:25:04 +000014#include "CodeViewDebug.h"
Reid Kleckner156a7232016-06-22 18:31:14 +000015#include "llvm/ADT/TinyPtrVector.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000016#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000017#include "llvm/DebugInfo/CodeView/CodeView.h"
Reid Klecknera8d57402016-06-03 15:58:20 +000018#include "llvm/DebugInfo/CodeView/FieldListRecordBuilder.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000019#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000020#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000021#include "llvm/DebugInfo/CodeView/TypeDumper.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000022#include "llvm/DebugInfo/CodeView/TypeIndex.h"
23#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000024#include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
Zachary Turnera3225b02016-07-29 20:56:36 +000025#include "llvm/DebugInfo/MSF/ByteStream.h"
26#include "llvm/DebugInfo/MSF/StreamReader.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000027#include "llvm/IR/Constants.h"
Reid Kleckner46cb48c2016-07-27 16:03:57 +000028#include "llvm/MC/MCAsmInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000029#include "llvm/MC/MCExpr.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000030#include "llvm/MC/MCSectionCOFF.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000031#include "llvm/MC/MCSymbol.h"
32#include "llvm/Support/COFF.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000033#include "llvm/Support/ScopedPrinter.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000034#include "llvm/Target/TargetFrameLowering.h"
Amjad Aboud76c9eb92016-06-18 10:25:07 +000035#include "llvm/Target/TargetRegisterInfo.h"
36#include "llvm/Target/TargetSubtargetInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000037
Reid Klecknerf9c275f2016-02-10 20:55:49 +000038using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000039using namespace llvm::codeview;
Zachary Turnerbac69d32016-07-22 19:56:05 +000040using namespace llvm::msf;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000041
Reid Klecknerf9c275f2016-02-10 20:55:49 +000042CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
43 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
44 // If module doesn't have named metadata anchors or COFF debug section
45 // is not available, skip any debug info related stuff.
46 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
47 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
48 Asm = nullptr;
49 return;
50 }
51
52 // Tell MMI that we have debug info.
53 MMI->setDebugInfoAvailability(true);
54}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000055
Reid Kleckner9533af42016-01-16 00:09:09 +000056StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
57 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000058 if (!Filepath.empty())
59 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000060
Reid Kleckner9533af42016-01-16 00:09:09 +000061 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
62
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000063 // Clang emits directory and relative filename info into the IR, but CodeView
64 // operates on full paths. We could change Clang to emit full paths too, but
65 // that would increase the IR size and probably not needed for other users.
66 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000067 if (Filename.find(':') == 1)
68 Filepath = Filename;
69 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +000070 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000071
72 // Canonicalize the path. We have to do it textually because we may no longer
73 // have access the file in the filesystem.
74 // First, replace all slashes with backslashes.
75 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
76
77 // Remove all "\.\" with "\".
78 size_t Cursor = 0;
79 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
80 Filepath.erase(Cursor, 2);
81
82 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
83 // path should be well-formatted, e.g. start with a drive letter, etc.
84 Cursor = 0;
85 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
86 // Something's wrong if the path starts with "\..\", abort.
87 if (Cursor == 0)
88 break;
89
90 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
91 if (PrevSlash == std::string::npos)
92 // Something's wrong, abort.
93 break;
94
95 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
96 // The next ".." might be following the one we've just erased.
97 Cursor = PrevSlash;
98 }
99
100 // Remove all duplicate backslashes.
101 Cursor = 0;
102 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
103 Filepath.erase(Cursor, 1);
104
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000105 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000106}
107
Reid Kleckner2214ed82016-01-29 00:49:42 +0000108unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
109 unsigned NextId = FileIdMap.size() + 1;
110 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
111 if (Insertion.second) {
112 // We have to compute the full filepath and emit a .cv_file directive.
113 StringRef FullPath = getFullFilepath(F);
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000114 bool Success = OS.EmitCVFileDirective(NextId, FullPath);
115 (void)Success;
116 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000117 }
118 return Insertion.first->second;
119}
120
Reid Kleckner876330d2016-02-12 21:48:30 +0000121CodeViewDebug::InlineSite &
122CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
123 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000124 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
125 InlineSite *Site = &SiteInsertion.first->second;
126 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000127 unsigned ParentFuncId = CurFn->FuncId;
128 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
129 ParentFuncId =
130 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
131 .SiteFuncId;
132
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000133 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000134 OS.EmitCVInlineSiteIdDirective(
135 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
136 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000137 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000138 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000139 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000140 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000141 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000142}
143
David Majnemer6bdc24e2016-07-01 23:12:45 +0000144static StringRef getPrettyScopeName(const DIScope *Scope) {
145 StringRef ScopeName = Scope->getName();
146 if (!ScopeName.empty())
147 return ScopeName;
148
149 switch (Scope->getTag()) {
150 case dwarf::DW_TAG_enumeration_type:
151 case dwarf::DW_TAG_class_type:
152 case dwarf::DW_TAG_structure_type:
153 case dwarf::DW_TAG_union_type:
154 return "<unnamed-tag>";
155 case dwarf::DW_TAG_namespace:
156 return "`anonymous namespace'";
157 }
158
159 return StringRef();
160}
161
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000162static const DISubprogram *getQualifiedNameComponents(
163 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
164 const DISubprogram *ClosestSubprogram = nullptr;
165 while (Scope != nullptr) {
166 if (ClosestSubprogram == nullptr)
167 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000168 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000169 if (!ScopeName.empty())
170 QualifiedNameComponents.push_back(ScopeName);
171 Scope = Scope->getScope().resolve();
172 }
173 return ClosestSubprogram;
174}
175
176static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
177 StringRef TypeName) {
178 std::string FullyQualifiedName;
179 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
180 FullyQualifiedName.append(QualifiedNameComponent);
181 FullyQualifiedName.append("::");
182 }
183 FullyQualifiedName.append(TypeName);
184 return FullyQualifiedName;
185}
186
187static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
188 SmallVector<StringRef, 5> QualifiedNameComponents;
189 getQualifiedNameComponents(Scope, QualifiedNameComponents);
190 return getQualifiedName(QualifiedNameComponents, Name);
191}
192
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000193struct CodeViewDebug::TypeLoweringScope {
194 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
195 ~TypeLoweringScope() {
196 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
197 // inner TypeLoweringScopes don't attempt to emit deferred types.
198 if (CVD.TypeEmissionLevel == 1)
199 CVD.emitDeferredCompleteTypes();
200 --CVD.TypeEmissionLevel;
201 }
202 CodeViewDebug &CVD;
203};
204
David Majnemer6bdc24e2016-07-01 23:12:45 +0000205static std::string getFullyQualifiedName(const DIScope *Ty) {
206 const DIScope *Scope = Ty->getScope().resolve();
207 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
208}
209
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000210TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
211 // No scope means global scope and that uses the zero index.
212 if (!Scope || isa<DIFile>(Scope))
213 return TypeIndex();
214
215 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
216
217 // Check if we've already translated this scope.
218 auto I = TypeIndices.find({Scope, nullptr});
219 if (I != TypeIndices.end())
220 return I->second;
221
222 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000223 std::string ScopeName = getFullyQualifiedName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000224 TypeIndex TI =
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000225 TypeTable.writeKnownType(StringIdRecord(TypeIndex(), ScopeName));
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000226 return recordTypeIndexForDINode(Scope, TI);
227}
228
David Majnemer75c3ebf2016-06-02 17:13:53 +0000229TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000230 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000231
David Majnemer75c3ebf2016-06-02 17:13:53 +0000232 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000233 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000234 if (I != TypeIndices.end())
235 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000236
Reid Klecknerac945e22016-06-17 16:11:20 +0000237 // The display name includes function template arguments. Drop them to match
238 // MSVC.
239 StringRef DisplayName = SP->getDisplayName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000240
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000241 const DIScope *Scope = SP->getScope().resolve();
242 TypeIndex TI;
243 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
244 // If the scope is a DICompositeType, then this must be a method. Member
245 // function types take some special handling, and require access to the
246 // subprogram.
247 TypeIndex ClassType = getTypeIndex(Class);
248 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
249 DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000250 TI = TypeTable.writeKnownType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000251 } else {
252 // Otherwise, this must be a free function.
253 TypeIndex ParentScope = getScopeIndex(Scope);
254 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000255 TI = TypeTable.writeKnownType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000256 }
257
258 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000259}
260
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000261TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
262 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000263 // Always use the method declaration as the key for the function type. The
264 // method declaration contains the this adjustment.
265 if (SP->getDeclaration())
266 SP = SP->getDeclaration();
267 assert(!SP->getDeclaration() && "should use declaration as key");
268
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000269 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
270 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000271 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000272 if (I != TypeIndices.end())
273 return I->second;
274
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000275 // Make sure complete type info for the class is emitted *after* the member
276 // function type, as the complete class type is likely to reference this
277 // member function type.
278 TypeLoweringScope S(*this);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000279 TypeIndex TI =
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000280 lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000281 return recordTypeIndexForDINode(SP, TI, Class);
282}
283
Amjad Aboudacee5682016-07-12 12:06:34 +0000284TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
285 TypeIndex TI,
286 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000287 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000288 (void)InsertResult;
289 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000290 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000291}
292
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000293unsigned CodeViewDebug::getPointerSizeInBytes() {
294 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
295}
296
Reid Kleckner876330d2016-02-12 21:48:30 +0000297void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
298 const DILocation *InlinedAt) {
299 if (InlinedAt) {
300 // This variable was inlined. Associate it with the InlineSite.
301 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
302 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
303 Site.InlinedLocals.emplace_back(Var);
304 } else {
305 // This variable goes in the main ProcSym.
306 CurFn->Locals.emplace_back(Var);
307 }
308}
309
Reid Kleckner829365a2016-02-11 19:41:47 +0000310static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
311 const DILocation *Loc) {
312 auto B = Locs.begin(), E = Locs.end();
313 if (std::find(B, E, Loc) == E)
314 Locs.push_back(Loc);
315}
316
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000317void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000318 const MachineFunction *MF) {
319 // Skip this instruction if it has the same location as the previous one.
320 if (DL == CurFn->LastLoc)
321 return;
322
323 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000324 if (!Scope)
325 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000326
David Majnemerc3340db2016-01-13 01:05:23 +0000327 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000328 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
329 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
330 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000331 return;
332
Reid Kleckner2214ed82016-01-29 00:49:42 +0000333 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
334 if (CI.getStartColumn() != DL.getCol())
335 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000336
Reid Kleckner2214ed82016-01-29 00:49:42 +0000337 if (!CurFn->HaveLineInfo)
338 CurFn->HaveLineInfo = true;
339 unsigned FileId = 0;
340 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
341 FileId = CurFn->LastFileId;
342 else
343 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
344 CurFn->LastLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000345
346 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000347 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000348 const DILocation *Loc = DL.get();
349
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000350 // If this location was actually inlined from somewhere else, give it the ID
351 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000352 FuncId =
353 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000354
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000355 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000356 bool FirstLoc = true;
357 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000358 InlineSite &Site =
359 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000360 if (!FirstLoc)
361 addLocIfNotPresent(Site.ChildSites, Loc);
362 FirstLoc = false;
363 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000364 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000365 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000366 }
367
Reid Klecknerdac21b42016-02-03 21:15:48 +0000368 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000369 /*PrologueEnd=*/false, /*IsStmt=*/false,
370 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000371}
372
Reid Kleckner5d122f82016-05-25 23:16:12 +0000373void CodeViewDebug::emitCodeViewMagicVersion() {
374 OS.EmitValueToAlignment(4);
375 OS.AddComment("Debug section magic");
376 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
377}
378
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000379void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000380 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000381 return;
382
383 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000384
385 // The COFF .debug$S section consists of several subsections, each starting
386 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
387 // of the payload followed by the payload itself. The subsections are 4-byte
388 // aligned.
389
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000390 // Use the generic .debug$S section, and make a subsection for all the inlined
391 // subprograms.
392 switchToDebugSectionForSymbol(nullptr);
Reid Kleckner5d122f82016-05-25 23:16:12 +0000393 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000394
Reid Kleckner2214ed82016-01-29 00:49:42 +0000395 // Emit per-function debug information.
396 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000397 if (!P.first->isDeclarationForLinker())
398 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000399
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000400 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000401 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000402 emitDebugInfoForGlobals();
403
Hans Wennborgb510b452016-06-23 16:33:53 +0000404 // Emit retained types.
405 emitDebugInfoForRetainedTypes();
406
Reid Kleckner5d122f82016-05-25 23:16:12 +0000407 // Switch back to the generic .debug$S section after potentially processing
408 // comdat symbol sections.
409 switchToDebugSectionForSymbol(nullptr);
410
David Majnemer3128b102016-06-15 18:00:01 +0000411 // Emit UDT records for any types used by global variables.
412 if (!GlobalUDTs.empty()) {
413 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
414 emitDebugInfoForUDTs(GlobalUDTs);
415 endCVSubsection(SymbolsEnd);
416 }
417
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000418 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000419 OS.AddComment("File index to string table offset subsection");
420 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000421
422 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000423 OS.AddComment("String table");
424 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000425
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000426 // Emit type information last, so that any types we translate while emitting
427 // function info are included.
428 emitTypeInformation();
429
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000430 clear();
431}
432
David Majnemerb9456a52016-03-14 05:15:09 +0000433static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
434 // Microsoft's linker seems to have trouble with symbol names longer than
435 // 0xffd8 bytes.
436 S = S.substr(0, 0xffd8);
437 SmallString<32> NullTerminatedString(S);
438 NullTerminatedString.push_back('\0');
439 OS.EmitBytes(NullTerminatedString);
440}
441
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000442void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000443 // Do nothing if we have no debug info or if no non-trivial types were emitted
444 // to TypeTable during codegen.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000445 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
Reid Klecknerfbd77872016-03-18 18:54:32 +0000446 if (!CU_Nodes)
447 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000448 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000449 return;
450
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000451 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000452 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000453 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000454
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000455 SmallString<8> CommentPrefix;
456 if (OS.isVerboseAsm()) {
457 CommentPrefix += '\t';
458 CommentPrefix += Asm->MAI->getCommentString();
459 CommentPrefix += ' ';
460 }
461
462 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
Reid Kleckner2280f932016-05-23 20:23:46 +0000463 TypeTable.ForEachRecord(
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000464 [&](TypeIndex Index, StringRef Record) {
465 if (OS.isVerboseAsm()) {
466 // Emit a block comment describing the type record for readability.
467 SmallString<512> CommentBlock;
468 raw_svector_ostream CommentOS(CommentBlock);
469 ScopedPrinter SP(CommentOS);
470 SP.setPrefix(CommentPrefix);
471 CVTD.setPrinter(&SP);
Reid Klecknerc92e9462016-07-01 18:05:56 +0000472 Error E = CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
473 if (E) {
474 logAllUnhandledErrors(std::move(E), errs(), "error: ");
475 llvm_unreachable("produced malformed type record");
476 }
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000477 // emitRawComment will insert its own tab and comment string before
478 // the first line, so strip off our first one. It also prints its own
479 // newline.
480 OS.emitRawComment(
481 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Reid Klecknerc92e9462016-07-01 18:05:56 +0000482 } else {
483#ifndef NDEBUG
484 // Assert that the type data is valid even if we aren't dumping
485 // comments. The MSVC linker doesn't do much type record validation,
486 // so the first link of an invalid type record can succeed while
487 // subsequent links will fail with LNK1285.
Zachary Turnerd66889c2016-07-28 19:12:28 +0000488 ByteStream Stream({Record.bytes_begin(), Record.bytes_end()});
Reid Klecknerc92e9462016-07-01 18:05:56 +0000489 CVTypeArray Types;
490 StreamReader Reader(Stream);
491 Error E = Reader.readArray(Types, Reader.getLength());
492 if (!E) {
493 TypeVisitorCallbacks C;
494 E = CVTypeVisitor(C).visitTypeStream(Types);
495 }
496 if (E) {
497 logAllUnhandledErrors(std::move(E), errs(), "error: ");
498 llvm_unreachable("produced malformed type record");
499 }
500#endif
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000501 }
502 OS.EmitBinaryData(Record);
Reid Kleckner2280f932016-05-23 20:23:46 +0000503 });
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000504}
505
Reid Kleckner5d122f82016-05-25 23:16:12 +0000506void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000507 if (InlinedSubprograms.empty())
508 return;
509
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000510 OS.AddComment("Inlinee lines subsection");
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000511 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000512
513 // We don't provide any extra file info.
514 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000515 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000516 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
517
518 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000519 assert(TypeIndices.count({SP, nullptr}));
520 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000521
David Majnemer30579ec2016-02-02 23:18:23 +0000522 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000523 unsigned FileId = maybeRecordFile(SP->getFile());
524 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
525 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000526 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000527 // The filechecksum table uses 8 byte entries for now, and file ids start at
528 // 1.
529 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000530 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000531 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000532 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000533 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000534 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000535 OS.EmitIntValue(SP->getLine(), 4);
536 }
537
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000538 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000539}
540
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000541void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
542 const DILocation *InlinedAt,
543 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000544 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
545 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000546
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000547 assert(TypeIndices.count({Site.Inlinee, nullptr}));
548 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000549
550 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000551 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000552 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000553 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000554 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000555 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000556
Reid Klecknerdac21b42016-02-03 21:15:48 +0000557 OS.AddComment("PtrParent");
558 OS.EmitIntValue(0, 4);
559 OS.AddComment("PtrEnd");
560 OS.EmitIntValue(0, 4);
561 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000562 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000563
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000564 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
565 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000566
567 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000568 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000569
570 OS.EmitLabel(InlineEnd);
571
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000572 emitLocalVariableList(Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000573
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000574 // Recurse on child inlined call sites before closing the scope.
575 for (const DILocation *ChildSite : Site.ChildSites) {
576 auto I = FI.InlineSites.find(ChildSite);
577 assert(I != FI.InlineSites.end() &&
578 "child site not in function inline site map");
579 emitInlinedCallSite(FI, ChildSite, I->second);
580 }
581
582 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000583 OS.AddComment("Record length");
584 OS.EmitIntValue(2, 2); // RecordLength
585 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000586 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000587}
588
Reid Kleckner5d122f82016-05-25 23:16:12 +0000589void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
590 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
591 // comdat key. A section may be comdat because of -ffunction-sections or
592 // because it is comdat in the IR.
593 MCSectionCOFF *GVSec =
594 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
595 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
596
597 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
598 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
599 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
600
601 OS.SwitchSection(DebugSec);
602
603 // Emit the magic version number if this is the first time we've switched to
604 // this section.
605 if (ComdatDebugSections.insert(DebugSec).second)
606 emitCodeViewMagicVersion();
607}
608
Reid Kleckner2214ed82016-01-29 00:49:42 +0000609void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
610 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000611 // For each function there is a separate subsection
612 // which holds the PC to file:line table.
613 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000614 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000615
Reid Kleckner5d122f82016-05-25 23:16:12 +0000616 // Switch to the to a comdat section, if appropriate.
617 switchToDebugSectionForSymbol(Fn);
618
Reid Klecknerac945e22016-06-17 16:11:20 +0000619 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000620 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000621 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000622 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000623
624 // If we have a display name, build the fully qualified name by walking the
625 // chain of scopes.
David Majnemer67f684e2016-07-28 05:03:22 +0000626 if (!SP->getDisplayName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000627 FuncName =
628 getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000629
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000630 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000631 if (FuncName.empty())
632 FuncName = GlobalValue::getRealLinkageName(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000633
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000634 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000635 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000636 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000637 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000638 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
639 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000640 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000641 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000642 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000643
David Majnemer7abd2692016-07-06 21:07:47 +0000644 if (GV->hasLocalLinkage()) {
645 OS.AddComment("Record kind: S_LPROC32_ID");
646 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
647 } else {
Reid Klecknerdac21b42016-02-03 21:15:48 +0000648 OS.AddComment("Record kind: S_GPROC32_ID");
Zachary Turner63a28462016-05-17 23:50:21 +0000649 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
David Majnemer7abd2692016-07-06 21:07:47 +0000650 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000651
David Majnemer30579ec2016-02-02 23:18:23 +0000652 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000653 OS.AddComment("PtrParent");
654 OS.EmitIntValue(0, 4);
655 OS.AddComment("PtrEnd");
656 OS.EmitIntValue(0, 4);
657 OS.AddComment("PtrNext");
658 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000659 // This is the important bit that tells the debugger where the function
660 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000661 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000662 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000663 OS.AddComment("Offset after prologue");
664 OS.EmitIntValue(0, 4);
665 OS.AddComment("Offset before epilogue");
666 OS.EmitIntValue(0, 4);
667 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000668 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000669 OS.AddComment("Function section relative address");
670 OS.EmitCOFFSecRel32(Fn);
671 OS.AddComment("Function section index");
672 OS.EmitCOFFSectionIndex(Fn);
673 OS.AddComment("Flags");
674 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000675 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000676 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000677 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000678 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000679 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000680
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000681 emitLocalVariableList(FI.Locals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000682
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000683 // Emit inlined call site information. Only emit functions inlined directly
684 // into the parent function. We'll emit the other sites recursively as part
685 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000686 for (const DILocation *InlinedAt : FI.ChildSites) {
687 auto I = FI.InlineSites.find(InlinedAt);
688 assert(I != FI.InlineSites.end() &&
689 "child site not in function inline site map");
690 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000691 }
692
David Majnemer3128b102016-06-15 18:00:01 +0000693 if (SP != nullptr)
694 emitDebugInfoForUDTs(LocalUDTs);
695
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000696 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000697 OS.AddComment("Record length");
698 OS.EmitIntValue(0x0002, 2);
699 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000700 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000701 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000702 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000703
Reid Kleckner2214ed82016-01-29 00:49:42 +0000704 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000705 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000706}
707
Reid Kleckner876330d2016-02-12 21:48:30 +0000708CodeViewDebug::LocalVarDefRange
709CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
710 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000711 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000712 DR.DataOffset = Offset;
713 assert(DR.DataOffset == Offset && "truncation");
714 DR.StructOffset = 0;
715 DR.CVRegister = CVRegister;
716 return DR;
717}
718
719CodeViewDebug::LocalVarDefRange
720CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
721 LocalVarDefRange DR;
722 DR.InMemory = 0;
723 DR.DataOffset = 0;
724 DR.StructOffset = 0;
725 DR.CVRegister = CVRegister;
726 return DR;
727}
728
729void CodeViewDebug::collectVariableInfoFromMMITable(
730 DenseSet<InlinedVariable> &Processed) {
731 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
732 const TargetFrameLowering *TFI = TSI.getFrameLowering();
733 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
734
735 for (const MachineModuleInfo::VariableDbgInfo &VI :
736 MMI->getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000737 if (!VI.Var)
738 continue;
739 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
740 "Expected inlined-at fields to agree");
741
Reid Kleckner876330d2016-02-12 21:48:30 +0000742 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000743 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
744
745 // If variable scope is not found then skip this variable.
746 if (!Scope)
747 continue;
748
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000749 // Get the frame register used and the offset.
750 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000751 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
752 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000753
754 // Calculate the label ranges.
Reid Kleckner876330d2016-02-12 21:48:30 +0000755 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000756 for (const InsnRange &Range : Scope->getRanges()) {
757 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
758 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000759 End = End ? End : Asm->getFunctionEnd();
760 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000761 }
762
Reid Kleckner876330d2016-02-12 21:48:30 +0000763 LocalVariable Var;
764 Var.DIVar = VI.Var;
765 Var.DefRanges.emplace_back(std::move(DefRange));
766 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
767 }
768}
769
770void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
771 DenseSet<InlinedVariable> Processed;
772 // Grab the variable info that was squirreled away in the MMI side-table.
773 collectVariableInfoFromMMITable(Processed);
774
775 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
776
777 for (const auto &I : DbgValues) {
778 InlinedVariable IV = I.first;
779 if (Processed.count(IV))
780 continue;
781 const DILocalVariable *DIVar = IV.first;
782 const DILocation *InlinedAt = IV.second;
783
784 // Instruction ranges, specifying where IV is accessible.
785 const auto &Ranges = I.second;
786
787 LexicalScope *Scope = nullptr;
788 if (InlinedAt)
789 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
790 else
791 Scope = LScopes.findLexicalScope(DIVar->getScope());
792 // If variable scope is not found then skip this variable.
793 if (!Scope)
794 continue;
795
796 LocalVariable Var;
797 Var.DIVar = DIVar;
798
799 // Calculate the definition ranges.
800 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
801 const InsnRange &Range = *I;
802 const MachineInstr *DVInst = Range.first;
803 assert(DVInst->isDebugValue() && "Invalid History entry");
804 const DIExpression *DIExpr = DVInst->getDebugExpression();
805
806 // Bail if there is a complex DWARF expression for now.
807 if (DIExpr && DIExpr->getNumElements() > 0)
808 continue;
809
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000810 // Bail if operand 0 is not a valid register. This means the variable is a
811 // simple constant, or is described by a complex expression.
812 // FIXME: Find a way to represent constant variables, since they are
813 // relatively common.
814 unsigned Reg =
815 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
816 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +0000817 continue;
818
Reid Kleckner876330d2016-02-12 21:48:30 +0000819 // Handle the two cases we can handle: indirect in memory and in register.
820 bool IsIndirect = DVInst->getOperand(1).isImm();
821 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
822 {
823 LocalVarDefRange DefRange;
824 if (IsIndirect) {
825 int64_t Offset = DVInst->getOperand(1).getImm();
826 DefRange = createDefRangeMem(CVReg, Offset);
827 } else {
828 DefRange = createDefRangeReg(CVReg);
829 }
830 if (Var.DefRanges.empty() ||
831 Var.DefRanges.back().isDifferentLocation(DefRange)) {
832 Var.DefRanges.emplace_back(std::move(DefRange));
833 }
834 }
835
836 // Compute the label range.
837 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
838 const MCSymbol *End = getLabelAfterInsn(Range.second);
839 if (!End) {
840 if (std::next(I) != E)
841 End = getLabelBeforeInsn(std::next(I)->first);
842 else
843 End = Asm->getFunctionEnd();
844 }
845
846 // If the last range end is our begin, just extend the last range.
847 // Otherwise make a new range.
848 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
849 Var.DefRanges.back().Ranges;
850 if (!Ranges.empty() && Ranges.back().second == Begin)
851 Ranges.back().second = End;
852 else
853 Ranges.emplace_back(Begin, End);
854
855 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000856 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000857
858 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000859 }
860}
861
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000862void CodeViewDebug::beginFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000863 assert(!CurFn && "Can't process two functions at once!");
864
David Majnemer67f684e2016-07-28 05:03:22 +0000865 if (!Asm || !MMI->hasDebugInfo() || !MF->getFunction()->getSubprogram())
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000866 return;
867
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000868 DebugHandlerBase::beginFunction(MF);
869
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000870 const Function *GV = MF->getFunction();
871 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000872 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +0000873 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000874 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000875
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000876 OS.EmitCVFuncIdDirective(CurFn->FuncId);
877
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000878 // Find the end of the function prolog. First known non-DBG_VALUE and
879 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000880 // FIXME: is there a simpler a way to do this? Can we just search
881 // for the first instruction of the function, not the last of the prolog?
882 DebugLoc PrologEndLoc;
883 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000884 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000885 for (const auto &MI : MBB) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000886 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
887 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000888 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000889 break;
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000890 } else if (!MI.isDebugValue()) {
891 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000892 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000893 }
894 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000895
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000896 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000897 if (PrologEndLoc && !EmptyPrologue) {
898 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000899 maybeRecordLocation(FnStartDL, MF);
900 }
901}
902
Hans Wennborg4b63a982016-06-23 22:57:25 +0000903void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
Reid Klecknerad56ea32016-07-01 22:24:51 +0000904 // Don't record empty UDTs.
905 if (Ty->getName().empty())
906 return;
907
Hans Wennborg4b63a982016-06-23 22:57:25 +0000908 SmallVector<StringRef, 5> QualifiedNameComponents;
909 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
910 Ty->getScope().resolve(), QualifiedNameComponents);
911
912 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +0000913 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +0000914
915 if (ClosestSubprogram == nullptr)
916 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
917 else if (ClosestSubprogram == CurrentSubprogram)
918 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
919
920 // TODO: What if the ClosestSubprogram is neither null or the current
921 // subprogram? Currently, the UDT just gets dropped on the floor.
922 //
923 // The current behavior is not desirable. To get maximal fidelity, we would
924 // need to perform all type translation before beginning emission of .debug$S
925 // and then make LocalUDTs a member of FunctionInfo
926}
927
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000928TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000929 // Generic dispatch for lowering an unknown type.
930 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +0000931 case dwarf::DW_TAG_array_type:
932 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +0000933 case dwarf::DW_TAG_typedef:
934 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000935 case dwarf::DW_TAG_base_type:
936 return lowerTypeBasic(cast<DIBasicType>(Ty));
937 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +0000938 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
939 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
940 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000941 case dwarf::DW_TAG_reference_type:
942 case dwarf::DW_TAG_rvalue_reference_type:
943 return lowerTypePointer(cast<DIDerivedType>(Ty));
944 case dwarf::DW_TAG_ptr_to_member_type:
945 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
946 case dwarf::DW_TAG_const_type:
947 case dwarf::DW_TAG_volatile_type:
948 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +0000949 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000950 if (ClassTy) {
951 // The member function type of a member function pointer has no
952 // ThisAdjustment.
953 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
954 /*ThisAdjustment=*/0);
955 }
David Majnemer75c3ebf2016-06-02 17:13:53 +0000956 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +0000957 case dwarf::DW_TAG_enumeration_type:
958 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +0000959 case dwarf::DW_TAG_class_type:
960 case dwarf::DW_TAG_structure_type:
961 return lowerTypeClass(cast<DICompositeType>(Ty));
962 case dwarf::DW_TAG_union_type:
963 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000964 default:
965 // Use the null type index.
966 return TypeIndex();
967 }
968}
969
David Majnemerd065e232016-06-02 06:21:37 +0000970TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +0000971 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
972 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +0000973 StringRef TypeName = Ty->getName();
974
Hans Wennborg4b63a982016-06-23 22:57:25 +0000975 addToUDTs(Ty, UnderlyingTypeIndex);
David Majnemer3128b102016-06-15 18:00:01 +0000976
David Majnemerd065e232016-06-02 06:21:37 +0000977 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +0000978 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +0000979 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +0000980 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +0000981 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +0000982 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +0000983
David Majnemerd065e232016-06-02 06:21:37 +0000984 return UnderlyingTypeIndex;
985}
986
Adrian McCarthyf3c3c132016-06-08 18:22:59 +0000987TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
988 DITypeRef ElementTypeRef = Ty->getBaseType();
989 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
990 // IndexType is size_t, which depends on the bitness of the target.
991 TypeIndex IndexType = Asm->MAI->getPointerSize() == 8
992 ? TypeIndex(SimpleTypeKind::UInt64Quad)
993 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +0000994
995 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
996
997 bool UndefinedSubrange = false;
998
999 // FIXME:
1000 // There is a bug in the front-end where an array of a structure, which was
1001 // declared as incomplete structure first, ends up not getting a size assigned
1002 // to it. (PR28303)
1003 // Example:
1004 // struct A(*p)[3];
1005 // struct A { int f; } a[3];
1006 //
1007 // This needs to be fixed in the front-end, but in the meantime we don't want
1008 // to trigger an assertion because of this.
1009 if (Ty->getSizeInBits() == 0) {
1010 UndefinedSubrange = true;
1011 }
1012
1013 // Add subranges to array type.
1014 DINodeArray Elements = Ty->getElements();
1015 for (int i = Elements.size() - 1; i >= 0; --i) {
1016 const DINode *Element = Elements[i];
1017 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1018
1019 const DISubrange *Subrange = cast<DISubrange>(Element);
1020 assert(Subrange->getLowerBound() == 0 &&
1021 "codeview doesn't support subranges with lower bounds");
1022 int64_t Count = Subrange->getCount();
1023
1024 // Variable Length Array (VLA) has Count equal to '-1'.
1025 // Replace with Count '1', assume it is the minimum VLA length.
1026 // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
1027 if (Count == -1) {
1028 Count = 1;
1029 UndefinedSubrange = true;
1030 }
1031
1032 StringRef Name = (i == 0) ? Ty->getName() : "";
1033 // Update the element size and element type index for subsequent subranges.
1034 ElementSize *= Count;
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001035 ElementTypeIndex = TypeTable.writeKnownType(
Amjad Aboudacee5682016-07-12 12:06:34 +00001036 ArrayRecord(ElementTypeIndex, IndexType, ElementSize, Name));
1037 }
1038
1039 (void)UndefinedSubrange;
1040 assert(UndefinedSubrange || ElementSize == (Ty->getSizeInBits() / 8));
1041
1042 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001043}
1044
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001045TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1046 TypeIndex Index;
1047 dwarf::TypeKind Kind;
1048 uint32_t ByteSize;
1049
1050 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001051 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001052
1053 SimpleTypeKind STK = SimpleTypeKind::None;
1054 switch (Kind) {
1055 case dwarf::DW_ATE_address:
1056 // FIXME: Translate
1057 break;
1058 case dwarf::DW_ATE_boolean:
1059 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001060 case 1: STK = SimpleTypeKind::Boolean8; break;
1061 case 2: STK = SimpleTypeKind::Boolean16; break;
1062 case 4: STK = SimpleTypeKind::Boolean32; break;
1063 case 8: STK = SimpleTypeKind::Boolean64; break;
1064 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001065 }
1066 break;
1067 case dwarf::DW_ATE_complex_float:
1068 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001069 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001070 case 4: STK = SimpleTypeKind::Complex32; break;
1071 case 8: STK = SimpleTypeKind::Complex64; break;
1072 case 10: STK = SimpleTypeKind::Complex80; break;
1073 case 16: STK = SimpleTypeKind::Complex128; break;
1074 }
1075 break;
1076 case dwarf::DW_ATE_float:
1077 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001078 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001079 case 4: STK = SimpleTypeKind::Float32; break;
1080 case 6: STK = SimpleTypeKind::Float48; break;
1081 case 8: STK = SimpleTypeKind::Float64; break;
1082 case 10: STK = SimpleTypeKind::Float80; break;
1083 case 16: STK = SimpleTypeKind::Float128; break;
1084 }
1085 break;
1086 case dwarf::DW_ATE_signed:
1087 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001088 case 1: STK = SimpleTypeKind::SByte; break;
1089 case 2: STK = SimpleTypeKind::Int16Short; break;
1090 case 4: STK = SimpleTypeKind::Int32; break;
1091 case 8: STK = SimpleTypeKind::Int64Quad; break;
1092 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001093 }
1094 break;
1095 case dwarf::DW_ATE_unsigned:
1096 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001097 case 1: STK = SimpleTypeKind::Byte; break;
1098 case 2: STK = SimpleTypeKind::UInt16Short; break;
1099 case 4: STK = SimpleTypeKind::UInt32; break;
1100 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1101 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001102 }
1103 break;
1104 case dwarf::DW_ATE_UTF:
1105 switch (ByteSize) {
1106 case 2: STK = SimpleTypeKind::Character16; break;
1107 case 4: STK = SimpleTypeKind::Character32; break;
1108 }
1109 break;
1110 case dwarf::DW_ATE_signed_char:
1111 if (ByteSize == 1)
1112 STK = SimpleTypeKind::SignedCharacter;
1113 break;
1114 case dwarf::DW_ATE_unsigned_char:
1115 if (ByteSize == 1)
1116 STK = SimpleTypeKind::UnsignedCharacter;
1117 break;
1118 default:
1119 break;
1120 }
1121
1122 // Apply some fixups based on the source-level type name.
1123 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1124 STK = SimpleTypeKind::Int32Long;
1125 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1126 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001127 if (STK == SimpleTypeKind::UInt16Short &&
1128 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001129 STK = SimpleTypeKind::WideCharacter;
1130 if ((STK == SimpleTypeKind::SignedCharacter ||
1131 STK == SimpleTypeKind::UnsignedCharacter) &&
1132 Ty->getName() == "char")
1133 STK = SimpleTypeKind::NarrowCharacter;
1134
1135 return TypeIndex(STK);
1136}
1137
1138TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1139 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1140
1141 // Pointers to simple types can use SimpleTypeMode, rather than having a
1142 // dedicated pointer type record.
1143 if (PointeeTI.isSimple() &&
1144 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1145 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1146 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1147 ? SimpleTypeMode::NearPointer64
1148 : SimpleTypeMode::NearPointer32;
1149 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1150 }
1151
1152 PointerKind PK =
1153 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1154 PointerMode PM = PointerMode::Pointer;
1155 switch (Ty->getTag()) {
1156 default: llvm_unreachable("not a pointer tag type");
1157 case dwarf::DW_TAG_pointer_type:
1158 PM = PointerMode::Pointer;
1159 break;
1160 case dwarf::DW_TAG_reference_type:
1161 PM = PointerMode::LValueReference;
1162 break;
1163 case dwarf::DW_TAG_rvalue_reference_type:
1164 PM = PointerMode::RValueReference;
1165 break;
1166 }
1167 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1168 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1169 // do.
1170 PointerOptions PO = PointerOptions::None;
1171 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001172 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001173}
1174
Reid Kleckner6fa15462016-06-17 22:14:39 +00001175static PointerToMemberRepresentation
1176translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1177 // SizeInBytes being zero generally implies that the member pointer type was
1178 // incomplete, which can happen if it is part of a function prototype. In this
1179 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001180 if (IsPMF) {
1181 switch (Flags & DINode::FlagPtrToMemberRep) {
1182 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001183 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1184 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001185 case DINode::FlagSingleInheritance:
1186 return PointerToMemberRepresentation::SingleInheritanceFunction;
1187 case DINode::FlagMultipleInheritance:
1188 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1189 case DINode::FlagVirtualInheritance:
1190 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1191 }
1192 } else {
1193 switch (Flags & DINode::FlagPtrToMemberRep) {
1194 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001195 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1196 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001197 case DINode::FlagSingleInheritance:
1198 return PointerToMemberRepresentation::SingleInheritanceData;
1199 case DINode::FlagMultipleInheritance:
1200 return PointerToMemberRepresentation::MultipleInheritanceData;
1201 case DINode::FlagVirtualInheritance:
1202 return PointerToMemberRepresentation::VirtualInheritanceData;
1203 }
1204 }
1205 llvm_unreachable("invalid ptr to member representation");
1206}
1207
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001208TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1209 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1210 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001211 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001212 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
1213 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001214 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1215 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1216 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001217 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner6fa15462016-06-17 22:14:39 +00001218 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1219 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1220 MemberPointerInfo MPI(
1221 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001222 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001223 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001224}
1225
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001226/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1227/// have a translation, use the NearC convention.
1228static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1229 switch (DwarfCC) {
1230 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1231 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1232 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1233 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1234 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1235 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1236 }
1237 return CallingConvention::NearC;
1238}
1239
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001240TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1241 ModifierOptions Mods = ModifierOptions::None;
1242 bool IsModifier = true;
1243 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001244 while (IsModifier && BaseTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001245 // FIXME: Need to add DWARF tag for __unaligned.
1246 switch (BaseTy->getTag()) {
1247 case dwarf::DW_TAG_const_type:
1248 Mods |= ModifierOptions::Const;
1249 break;
1250 case dwarf::DW_TAG_volatile_type:
1251 Mods |= ModifierOptions::Volatile;
1252 break;
1253 default:
1254 IsModifier = false;
1255 break;
1256 }
1257 if (IsModifier)
1258 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1259 }
1260 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Reid Klecknerdbaa61c2016-08-30 21:48:14 +00001261 return TypeTable.writeKnownType(ModifierRecord(ModifiedTI, Mods));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001262}
1263
David Majnemer75c3ebf2016-06-02 17:13:53 +00001264TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1265 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1266 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1267 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1268
1269 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1270 ArrayRef<TypeIndex> ArgTypeIndices = None;
1271 if (!ReturnAndArgTypeIndices.empty()) {
1272 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1273 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1274 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1275 }
1276
1277 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001278 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001279
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001280 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1281
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001282 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1283 ArgTypeIndices.size(), ArgListIndex);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001284 return TypeTable.writeKnownType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001285}
1286
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001287TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001288 const DIType *ClassTy,
1289 int ThisAdjustment) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001290 // Lower the containing class type.
1291 TypeIndex ClassType = getTypeIndex(ClassTy);
1292
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001293 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1294 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1295 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1296
1297 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1298 ArrayRef<TypeIndex> ArgTypeIndices = None;
1299 if (!ReturnAndArgTypeIndices.empty()) {
1300 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1301 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1302 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1303 }
1304 TypeIndex ThisTypeIndex = TypeIndex::Void();
1305 if (!ArgTypeIndices.empty()) {
1306 ThisTypeIndex = ArgTypeIndices.front();
1307 ArgTypeIndices = ArgTypeIndices.drop_front();
1308 }
1309
1310 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001311 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001312
1313 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1314
1315 // TODO: Need to use the correct values for:
1316 // FunctionOptions
1317 // ThisPointerAdjustment.
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001318 TypeIndex TI = TypeTable.writeKnownType(MemberFunctionRecord(
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001319 ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FunctionOptions::None,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001320 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001321
1322 return TI;
1323}
1324
Reid Kleckner9dac4732016-08-31 15:59:30 +00001325TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
1326 unsigned VSlotCount = Ty->getSizeInBits() / (8 * Asm->MAI->getPointerSize());
1327 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
1328 return TypeTable.writeKnownType(VFTableShapeRecord(Slots));
1329}
1330
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001331static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1332 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001333 case DINode::FlagPrivate: return MemberAccess::Private;
1334 case DINode::FlagPublic: return MemberAccess::Public;
1335 case DINode::FlagProtected: return MemberAccess::Protected;
1336 case 0:
1337 // If there was no explicit access control, provide the default for the tag.
1338 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1339 : MemberAccess::Public;
1340 }
1341 llvm_unreachable("access flags are exclusive");
1342}
1343
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001344static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1345 if (SP->isArtificial())
1346 return MethodOptions::CompilerGenerated;
1347
1348 // FIXME: Handle other MethodOptions.
1349
1350 return MethodOptions::None;
1351}
1352
1353static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1354 bool Introduced) {
1355 switch (SP->getVirtuality()) {
1356 case dwarf::DW_VIRTUALITY_none:
1357 break;
1358 case dwarf::DW_VIRTUALITY_virtual:
1359 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1360 case dwarf::DW_VIRTUALITY_pure_virtual:
1361 return Introduced ? MethodKind::PureIntroducingVirtual
1362 : MethodKind::PureVirtual;
1363 default:
1364 llvm_unreachable("unhandled virtuality case");
1365 }
1366
1367 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1368
1369 return MethodKind::Vanilla;
1370}
1371
Reid Klecknera8d57402016-06-03 15:58:20 +00001372static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1373 switch (Ty->getTag()) {
1374 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1375 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1376 }
1377 llvm_unreachable("unexpected tag");
1378}
1379
Reid Klecknere092dad2016-07-02 00:11:07 +00001380/// Return ClassOptions that should be present on both the forward declaration
1381/// and the defintion of a tag type.
1382static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1383 ClassOptions CO = ClassOptions::None;
1384
1385 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001386 // appear to give every type a linkage name, which may be problematic for us.
1387 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001388 if (!Ty->getIdentifier().empty())
1389 CO |= ClassOptions::HasUniqueName;
1390
1391 // Put the Nested flag on a type if it appears immediately inside a tag type.
1392 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1393 // here. That flag is only set on definitions, and not forward declarations.
1394 const DIScope *ImmediateScope = Ty->getScope().resolve();
1395 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1396 CO |= ClassOptions::Nested;
1397
1398 // Put the Scoped flag on function-local types.
1399 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1400 Scope = Scope->getScope().resolve()) {
1401 if (isa<DISubprogram>(Scope)) {
1402 CO |= ClassOptions::Scoped;
1403 break;
1404 }
1405 }
1406
1407 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001408}
1409
David Majnemer979cb882016-06-16 21:32:16 +00001410TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001411 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001412 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001413 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001414
David Majnemerda9548f2016-06-17 16:13:21 +00001415 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001416 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001417 } else {
1418 FieldListRecordBuilder Fields;
1419 for (const DINode *Element : Ty->getElements()) {
1420 // We assume that the frontend provides all members in source declaration
1421 // order, which is what MSVC does.
1422 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001423 Fields.writeMemberType(EnumeratorRecord(
David Majnemerda9548f2016-06-17 16:13:21 +00001424 MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()),
1425 Enumerator->getName()));
1426 EnumeratorCount++;
1427 }
1428 }
1429 FTI = TypeTable.writeFieldList(Fields);
1430 }
David Majnemer979cb882016-06-16 21:32:16 +00001431
David Majnemer6bdc24e2016-07-01 23:12:45 +00001432 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001433
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001434 return TypeTable.writeKnownType(EnumRecord(EnumeratorCount, CO, FTI, FullName,
1435 Ty->getIdentifier(),
1436 getTypeIndex(Ty->getBaseType())));
David Majnemer979cb882016-06-16 21:32:16 +00001437}
1438
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001439//===----------------------------------------------------------------------===//
1440// ClassInfo
1441//===----------------------------------------------------------------------===//
1442
1443struct llvm::ClassInfo {
1444 struct MemberInfo {
1445 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00001446 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001447 };
1448 // [MemberInfo]
1449 typedef std::vector<MemberInfo> MemberList;
1450
Reid Kleckner156a7232016-06-22 18:31:14 +00001451 typedef TinyPtrVector<const DISubprogram *> MethodsList;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001452 // MethodName -> MethodsList
1453 typedef MapVector<MDString *, MethodsList> MethodsMap;
1454
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001455 /// Base classes.
1456 std::vector<const DIDerivedType *> Inheritance;
1457
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001458 /// Direct members.
1459 MemberList Members;
1460 // Direct overloaded methods gathered by name.
1461 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001462
Reid Kleckner9dac4732016-08-31 15:59:30 +00001463 TypeIndex VShapeTI;
1464
Adrian McCarthy820ca542016-07-06 19:49:51 +00001465 std::vector<const DICompositeType *> NestedClasses;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001466};
1467
1468void CodeViewDebug::clear() {
1469 assert(CurFn == nullptr);
1470 FileIdMap.clear();
1471 FnDebugInfo.clear();
1472 FileToFilepathMap.clear();
1473 LocalUDTs.clear();
1474 GlobalUDTs.clear();
1475 TypeIndices.clear();
1476 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001477}
1478
1479void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1480 const DIDerivedType *DDTy) {
1481 if (!DDTy->getName().empty()) {
1482 Info.Members.push_back({DDTy, 0});
1483 return;
1484 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001485 // An unnamed member must represent a nested struct or union. Add all the
1486 // indirect fields to the current record.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001487 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00001488 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001489 const DIType *Ty = DDTy->getBaseType().resolve();
Reid Kleckner9ff936c2016-06-21 14:56:24 +00001490 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001491 ClassInfo NestedInfo = collectClassInfo(DCTy);
1492 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001493 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001494 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001495}
1496
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001497ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1498 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001499 // Add elements to structure type.
1500 DINodeArray Elements = Ty->getElements();
1501 for (auto *Element : Elements) {
1502 // We assume that the frontend provides all members in source declaration
1503 // order, which is what MSVC does.
1504 if (!Element)
1505 continue;
1506 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001507 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001508 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001509 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001510 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001511 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1512 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001513 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1514 DDTy->getName() == "__vtbl_ptr_type") {
1515 Info.VShapeTI = getTypeIndex(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001516 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1517 // Ignore friend members. It appears that MSVC emitted info about
1518 // friends in the past, but modern versions do not.
1519 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001520 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1521 Info.NestedClasses.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001522 }
1523 // Skip other unrecognized kinds of elements.
1524 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001525 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001526}
1527
Reid Klecknera8d57402016-06-03 15:58:20 +00001528TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1529 // First, construct the forward decl. Don't look into Ty to compute the
1530 // forward decl options, since it might not be available in all TUs.
1531 TypeRecordKind Kind = getRecordKind(Ty);
1532 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001533 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001534 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001535 TypeIndex FwdDeclTI = TypeTable.writeKnownType(ClassRecord(
Reid Klecknera8d57402016-06-03 15:58:20 +00001536 Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(),
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001537 TypeIndex(), TypeIndex(), 0, FullName, Ty->getIdentifier()));
Reid Kleckner643dd832016-06-22 17:15:28 +00001538 if (!Ty->isForwardDecl())
1539 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001540 return FwdDeclTI;
1541}
1542
1543TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1544 // Construct the field list and complete type record.
1545 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00001546 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001547 TypeIndex FieldTI;
1548 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001549 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001550 bool ContainsNestedClass;
1551 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1552 lowerRecordFieldList(Ty);
1553
1554 if (ContainsNestedClass)
1555 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00001556
David Majnemer6bdc24e2016-07-01 23:12:45 +00001557 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001558
Reid Klecknera8d57402016-06-03 15:58:20 +00001559 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00001560
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001561 TypeIndex ClassTI = TypeTable.writeKnownType(ClassRecord(
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001562 Kind, FieldCount, CO, HfaKind::None, WindowsRTClassKind::None, FieldTI,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001563 TypeIndex(), VShapeTI, SizeInBytes, FullName, Ty->getIdentifier()));
Hans Wennborg9a519a02016-06-22 21:22:13 +00001564
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001565 TypeTable.writeKnownType(UdtSourceLineRecord(
1566 ClassTI, TypeTable.writeKnownType(StringIdRecord(
Hans Wennborg9a519a02016-06-22 21:22:13 +00001567 TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1568 Ty->getLine()));
1569
Hans Wennborg4b63a982016-06-23 22:57:25 +00001570 addToUDTs(Ty, ClassTI);
1571
Hans Wennborg9a519a02016-06-22 21:22:13 +00001572 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001573}
1574
1575TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1576 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001577 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001578 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001579 TypeIndex FwdDeclTI = TypeTable.writeKnownType(UnionRecord(
1580 0, CO, HfaKind::None, TypeIndex(), 0, FullName, Ty->getIdentifier()));
Reid Kleckner643dd832016-06-22 17:15:28 +00001581 if (!Ty->isForwardDecl())
1582 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001583 return FwdDeclTI;
1584}
1585
1586TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00001587 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001588 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001589 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001590 bool ContainsNestedClass;
1591 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1592 lowerRecordFieldList(Ty);
1593
1594 if (ContainsNestedClass)
1595 CO |= ClassOptions::ContainsNestedClass;
1596
Reid Klecknera8d57402016-06-03 15:58:20 +00001597 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00001598 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001599
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001600 TypeIndex UnionTI = TypeTable.writeKnownType(
Hans Wennborg9a519a02016-06-22 21:22:13 +00001601 UnionRecord(FieldCount, CO, HfaKind::None, FieldTI, SizeInBytes, FullName,
1602 Ty->getIdentifier()));
1603
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001604 TypeTable.writeKnownType(UdtSourceLineRecord(
1605 UnionTI, TypeTable.writeKnownType(StringIdRecord(
Hans Wennborg9a519a02016-06-22 21:22:13 +00001606 TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1607 Ty->getLine()));
1608
Hans Wennborg4b63a982016-06-23 22:57:25 +00001609 addToUDTs(Ty, UnionTI);
1610
Hans Wennborg9a519a02016-06-22 21:22:13 +00001611 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001612}
1613
Adrian McCarthy820ca542016-07-06 19:49:51 +00001614std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00001615CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1616 // Manually count members. MSVC appears to count everything that generates a
1617 // field list record. Each individual overload in a method overload group
1618 // contributes to this count, even though the overload group is a single field
1619 // list record.
1620 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001621 ClassInfo Info = collectClassInfo(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001622 FieldListRecordBuilder Fields;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001623
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001624 // Create base classes.
1625 for (const DIDerivedType *I : Info.Inheritance) {
1626 if (I->getFlags() & DINode::FlagVirtual) {
1627 // Virtual base.
1628 // FIXME: Emit VBPtrOffset when the frontend provides it.
1629 unsigned VBPtrOffset = 0;
1630 // FIXME: Despite the accessor name, the offset is really in bytes.
1631 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001632 Fields.writeMemberType(VirtualBaseClassRecord(
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001633 translateAccessFlags(Ty->getTag(), I->getFlags()),
1634 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
1635 VBTableIndex));
1636 } else {
1637 assert(I->getOffsetInBits() % 8 == 0 &&
1638 "bases must be on byte boundaries");
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001639 Fields.writeMemberType(BaseClassRecord(
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001640 translateAccessFlags(Ty->getTag(), I->getFlags()),
1641 getTypeIndex(I->getBaseType()), I->getOffsetInBits() / 8));
1642 }
1643 }
1644
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001645 // Create members.
1646 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1647 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1648 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00001649 StringRef MemberName = Member->getName();
1650 MemberAccess Access =
1651 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001652
1653 if (Member->isStaticMember()) {
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001654 Fields.writeMemberType(
David Majnemer9319cbc2016-06-30 03:00:20 +00001655 StaticDataMemberRecord(Access, MemberBaseType, MemberName));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001656 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001657 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00001658 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001659
Reid Kleckner9dac4732016-08-31 15:59:30 +00001660 // Virtual function pointer member.
1661 if ((Member->getFlags() & DINode::FlagArtificial) &&
1662 Member->getName().startswith("_vptr$")) {
1663 Fields.writeMemberType(VFPtrRecord(getTypeIndex(Member->getBaseType())));
1664 MemberCount++;
1665 continue;
1666 }
1667
David Majnemer9319cbc2016-06-30 03:00:20 +00001668 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00001669 uint64_t MemberOffsetInBits =
1670 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001671 if (Member->isBitField()) {
1672 uint64_t StartBitOffset = MemberOffsetInBits;
1673 if (const auto *CI =
1674 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00001675 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001676 }
1677 StartBitOffset -= MemberOffsetInBits;
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001678 MemberBaseType = TypeTable.writeKnownType(BitFieldRecord(
David Majnemer9319cbc2016-06-30 03:00:20 +00001679 MemberBaseType, Member->getSizeInBits(), StartBitOffset));
1680 }
1681 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001682 Fields.writeMemberType(DataMemberRecord(Access, MemberBaseType,
David Majnemer9319cbc2016-06-30 03:00:20 +00001683 MemberOffsetInBytes, MemberName));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001684 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001685 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001686
1687 // Create methods
1688 for (auto &MethodItr : Info.Methods) {
1689 StringRef Name = MethodItr.first->getString();
1690
1691 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00001692 for (const DISubprogram *SP : MethodItr.second) {
1693 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1694 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001695
1696 unsigned VFTableOffset = -1;
1697 if (Introduced)
1698 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1699
1700 Methods.push_back(
1701 OneMethodRecord(MethodType, translateMethodKindFlags(SP, Introduced),
1702 translateMethodOptionFlags(SP),
1703 translateAccessFlags(Ty->getTag(), SP->getFlags()),
1704 VFTableOffset, Name));
1705 MemberCount++;
1706 }
1707 assert(Methods.size() > 0 && "Empty methods map entry");
1708 if (Methods.size() == 1)
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001709 Fields.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001710 else {
1711 TypeIndex MethodList =
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001712 TypeTable.writeKnownType(MethodOverloadListRecord(Methods));
1713 Fields.writeMemberType(
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001714 OverloadedMethodRecord(Methods.size(), MethodList, Name));
1715 }
1716 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001717
1718 // Create nested classes.
1719 for (const DICompositeType *Nested : Info.NestedClasses) {
1720 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001721 Fields.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00001722 MemberCount++;
1723 }
1724
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001725 TypeIndex FieldTI = TypeTable.writeFieldList(Fields);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001726 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Adrian McCarthy820ca542016-07-06 19:49:51 +00001727 !Info.NestedClasses.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00001728}
1729
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001730TypeIndex CodeViewDebug::getVBPTypeIndex() {
1731 if (!VBPType.getIndex()) {
1732 // Make a 'const int *' type.
1733 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001734 TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001735
1736 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1737 : PointerKind::Near32;
1738 PointerMode PM = PointerMode::Pointer;
1739 PointerOptions PO = PointerOptions::None;
1740 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1741
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001742 VBPType = TypeTable.writeKnownType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001743 }
1744
1745 return VBPType;
1746}
1747
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001748TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001749 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001750 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001751
1752 // The null DIType is the void type. Don't try to hash it.
1753 if (!Ty)
1754 return TypeIndex::Void();
1755
Reid Klecknera8d57402016-06-03 15:58:20 +00001756 // Check if we've already translated this type. Don't try to do a
1757 // get-or-create style insertion that caches the hash lookup across the
1758 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001759 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001760 if (I != TypeIndices.end())
1761 return I->second;
1762
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001763 TypeLoweringScope S(*this);
1764 TypeIndex TI = lowerType(Ty, ClassTy);
1765 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00001766}
1767
1768TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1769 const DIType *Ty = TypeRef.resolve();
1770
1771 // The null DIType is the void type. Don't try to hash it.
1772 if (!Ty)
1773 return TypeIndex::Void();
1774
1775 // If this is a non-record type, the complete type index is the same as the
1776 // normal type index. Just call getTypeIndex.
1777 switch (Ty->getTag()) {
1778 case dwarf::DW_TAG_class_type:
1779 case dwarf::DW_TAG_structure_type:
1780 case dwarf::DW_TAG_union_type:
1781 break;
1782 default:
1783 return getTypeIndex(Ty);
1784 }
1785
1786 // Check if we've already translated the complete record type. Lowering a
1787 // complete type should never trigger lowering another complete type, so we
1788 // can reuse the hash table lookup result.
1789 const auto *CTy = cast<DICompositeType>(Ty);
1790 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1791 if (!InsertResult.second)
1792 return InsertResult.first->second;
1793
Reid Kleckner643dd832016-06-22 17:15:28 +00001794 TypeLoweringScope S(*this);
1795
Reid Klecknera8d57402016-06-03 15:58:20 +00001796 // Make sure the forward declaration is emitted first. It's unclear if this
1797 // is necessary, but MSVC does it, and we should follow suit until we can show
1798 // otherwise.
1799 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1800
1801 // Just use the forward decl if we don't have complete type info. This might
1802 // happen if the frontend is using modules and expects the complete definition
1803 // to be emitted elsewhere.
1804 if (CTy->isForwardDecl())
1805 return FwdDeclTI;
1806
1807 TypeIndex TI;
1808 switch (CTy->getTag()) {
1809 case dwarf::DW_TAG_class_type:
1810 case dwarf::DW_TAG_structure_type:
1811 TI = lowerCompleteTypeClass(CTy);
1812 break;
1813 case dwarf::DW_TAG_union_type:
1814 TI = lowerCompleteTypeUnion(CTy);
1815 break;
1816 default:
1817 llvm_unreachable("not a record");
1818 }
1819
1820 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001821 return TI;
1822}
1823
Reid Kleckner643dd832016-06-22 17:15:28 +00001824/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00001825/// and do this until fixpoint, as each complete record type typically
1826/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00001827/// many other record types.
1828void CodeViewDebug::emitDeferredCompleteTypes() {
1829 SmallVector<const DICompositeType *, 4> TypesToEmit;
1830 while (!DeferredCompleteTypes.empty()) {
1831 std::swap(DeferredCompleteTypes, TypesToEmit);
1832 for (const DICompositeType *RecordTy : TypesToEmit)
1833 getCompleteTypeIndex(RecordTy);
1834 TypesToEmit.clear();
1835 }
1836}
1837
Reid Kleckner10dd55c2016-06-24 17:55:40 +00001838void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
1839 // Get the sorted list of parameters and emit them first.
1840 SmallVector<const LocalVariable *, 6> Params;
1841 for (const LocalVariable &L : Locals)
1842 if (L.DIVar->isParameter())
1843 Params.push_back(&L);
1844 std::sort(Params.begin(), Params.end(),
1845 [](const LocalVariable *L, const LocalVariable *R) {
1846 return L->DIVar->getArg() < R->DIVar->getArg();
1847 });
1848 for (const LocalVariable *L : Params)
1849 emitLocalVariable(*L);
1850
1851 // Next emit all non-parameters in the order that we found them.
1852 for (const LocalVariable &L : Locals)
1853 if (!L.DIVar->isParameter())
1854 emitLocalVariable(L);
1855}
1856
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001857void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
1858 // LocalSym record, see SymbolRecord.h for more info.
1859 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
1860 *LocalEnd = MMI->getContext().createTempSymbol();
1861 OS.AddComment("Record length");
1862 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
1863 OS.EmitLabel(LocalBegin);
1864
1865 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00001866 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001867
Zachary Turner63a28462016-05-17 23:50:21 +00001868 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001869 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00001870 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00001871 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00001872 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001873
1874 OS.AddComment("TypeIndex");
Reid Klecknera8d57402016-06-03 15:58:20 +00001875 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001876 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001877 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00001878 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00001879 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00001880 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001881 OS.EmitLabel(LocalEnd);
1882
Reid Kleckner876330d2016-02-12 21:48:30 +00001883 // Calculate the on disk prefix of the appropriate def range record. The
1884 // records and on disk formats are described in SymbolRecords.h. BytePrefix
1885 // should be big enough to hold all forms without memory allocation.
1886 SmallString<20> BytePrefix;
1887 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
1888 BytePrefix.clear();
1889 // FIXME: Handle bitpieces.
1890 if (DefRange.StructOffset != 0)
1891 continue;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001892
Reid Kleckner876330d2016-02-12 21:48:30 +00001893 if (DefRange.InMemory) {
Zachary Turnera78ecd12016-05-23 18:49:06 +00001894 DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
1895 0, 0, ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001896 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00001897 BytePrefix +=
1898 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001899 BytePrefix +=
1900 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1901 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001902 } else {
1903 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Zachary Turnera78ecd12016-05-23 18:49:06 +00001904 // Unclear what matters here.
1905 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
1906 ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001907 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
Reid Kleckner876330d2016-02-12 21:48:30 +00001908 BytePrefix +=
1909 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001910 BytePrefix +=
1911 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1912 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001913 }
1914 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
1915 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001916}
1917
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001918void CodeViewDebug::endFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001919 if (!Asm || !CurFn) // We haven't created any debug info for this function.
1920 return;
1921
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001922 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00001923 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001924 assert(CurFn == &FnDebugInfo[GV]);
1925
Pete Cooperadebb932016-03-11 02:14:16 +00001926 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00001927
1928 DebugHandlerBase::endFunction(MF);
1929
Reid Kleckner2214ed82016-01-29 00:49:42 +00001930 // Don't emit anything if we don't have any line tables.
1931 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001932 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001933 CurFn = nullptr;
1934 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00001935 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001936
1937 CurFn->End = Asm->getFunctionEnd();
1938
Craig Topper353eda42014-04-24 06:44:33 +00001939 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001940}
1941
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001942void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001943 DebugHandlerBase::beginInstruction(MI);
1944
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001945 // Ignore DBG_VALUE locations and function prologue.
David Majnemer67f684e2016-07-28 05:03:22 +00001946 if (!Asm || !CurFn || MI->isDebugValue() ||
1947 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001948 return;
1949 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001950 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001951 return;
1952 maybeRecordLocation(DL, Asm->MF);
1953}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001954
1955MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
1956 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
1957 *EndLabel = MMI->getContext().createTempSymbol();
1958 OS.EmitIntValue(unsigned(Kind), 4);
1959 OS.AddComment("Subsection size");
1960 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
1961 OS.EmitLabel(BeginLabel);
1962 return EndLabel;
1963}
1964
1965void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
1966 OS.EmitLabel(EndLabel);
1967 // Every subsection must be aligned to a 4-byte boundary.
1968 OS.EmitValueToAlignment(4);
1969}
1970
David Majnemer3128b102016-06-15 18:00:01 +00001971void CodeViewDebug::emitDebugInfoForUDTs(
1972 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
1973 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
1974 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
1975 *UDTRecordEnd = MMI->getContext().createTempSymbol();
1976 OS.AddComment("Record length");
1977 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
1978 OS.EmitLabel(UDTRecordBegin);
1979
1980 OS.AddComment("Record kind: S_UDT");
1981 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
1982
1983 OS.AddComment("Type");
1984 OS.EmitIntValue(UDT.second.getIndex(), 4);
1985
1986 emitNullTerminatedSymbolName(OS, UDT.first);
1987 OS.EmitLabel(UDTRecordEnd);
1988 }
1989}
1990
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001991void CodeViewDebug::emitDebugInfoForGlobals() {
1992 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
1993 for (const MDNode *Node : CUs->operands()) {
1994 const auto *CU = cast<DICompileUnit>(Node);
1995
1996 // First, emit all globals that are not in a comdat in a single symbol
1997 // substream. MSVC doesn't like it if the substream is empty, so only open
1998 // it if we have at least one global to emit.
1999 switchToDebugSectionForSymbol(nullptr);
2000 MCSymbol *EndLabel = nullptr;
2001 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Reid Kleckner6d1d2752016-06-09 00:29:00 +00002002 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
David Majnemer577be0f2016-06-15 00:19:52 +00002003 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002004 if (!EndLabel) {
2005 OS.AddComment("Symbol subsection for globals");
2006 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
2007 }
2008 emitDebugInfoForGlobal(G, Asm->getSymbol(GV));
2009 }
Reid Kleckner6d1d2752016-06-09 00:29:00 +00002010 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002011 }
2012 if (EndLabel)
2013 endCVSubsection(EndLabel);
2014
2015 // Second, emit each global that is in a comdat into its own .debug$S
2016 // section along with its own symbol substream.
2017 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Reid Kleckner6d1d2752016-06-09 00:29:00 +00002018 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002019 if (GV->hasComdat()) {
2020 MCSymbol *GVSym = Asm->getSymbol(GV);
2021 OS.AddComment("Symbol subsection for " +
2022 Twine(GlobalValue::getRealLinkageName(GV->getName())));
2023 switchToDebugSectionForSymbol(GVSym);
2024 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
2025 emitDebugInfoForGlobal(G, GVSym);
2026 endCVSubsection(EndLabel);
2027 }
2028 }
2029 }
2030 }
2031}
2032
Hans Wennborgb510b452016-06-23 16:33:53 +00002033void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2034 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2035 for (const MDNode *Node : CUs->operands()) {
2036 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2037 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2038 getTypeIndex(RT);
2039 // FIXME: Add to global/local DTU list.
2040 }
2041 }
2042 }
2043}
2044
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002045void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
2046 MCSymbol *GVSym) {
2047 // DataSym record, see SymbolRecord.h for more info.
2048 // FIXME: Thread local data, etc
2049 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2050 *DataEnd = MMI->getContext().createTempSymbol();
2051 OS.AddComment("Record length");
2052 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2053 OS.EmitLabel(DataBegin);
David Majnemera54fe1a2016-07-07 05:14:21 +00002054 const auto *GV = cast<GlobalVariable>(DIGV->getVariable());
David Majnemer7abd2692016-07-06 21:07:47 +00002055 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002056 if (GV->isThreadLocal()) {
2057 OS.AddComment("Record kind: S_LTHREAD32");
2058 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2059 } else {
2060 OS.AddComment("Record kind: S_LDATA32");
2061 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2062 }
David Majnemer7abd2692016-07-06 21:07:47 +00002063 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002064 if (GV->isThreadLocal()) {
2065 OS.AddComment("Record kind: S_GTHREAD32");
2066 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2067 } else {
2068 OS.AddComment("Record kind: S_GDATA32");
2069 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2070 }
David Majnemer7abd2692016-07-06 21:07:47 +00002071 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002072 OS.AddComment("Type");
2073 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2074 OS.AddComment("DataOffset");
2075 OS.EmitCOFFSecRel32(GVSym);
2076 OS.AddComment("Segment");
2077 OS.EmitCOFFSectionIndex(GVSym);
2078 OS.AddComment("Name");
2079 emitNullTerminatedSymbolName(OS, DIGV->getName());
2080 OS.EmitLabel(DataEnd);
2081}