blob: 385c78bbcceff590a962ffda1571613a710f8116 [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"
Zachary Turner8c099fe2017-05-30 16:36:15 +000018#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.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"
Zachary Turnerc640b762017-01-11 00:35:08 +000021#include "llvm/DebugInfo/CodeView/TypeDatabase.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000022#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000023#include "llvm/DebugInfo/CodeView/TypeIndex.h"
24#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000025#include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000026#include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.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"
Zachary Turnerd9dc2822017-03-02 20:52:51 +000032#include "llvm/Support/BinaryByteStream.h"
33#include "llvm/Support/BinaryStreamReader.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000034#include "llvm/Support/COFF.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000035#include "llvm/Support/ScopedPrinter.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000036#include "llvm/Target/TargetFrameLowering.h"
Amjad Aboud76c9eb92016-06-18 10:25:07 +000037#include "llvm/Target/TargetRegisterInfo.h"
38#include "llvm/Target/TargetSubtargetInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000039
Reid Klecknerf9c275f2016-02-10 20:55:49 +000040using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000041using namespace llvm::codeview;
42
Reid Klecknerf9c275f2016-02-10 20:55:49 +000043CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
Zachary Turnerc6d54da2016-09-09 17:46:17 +000044 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), Allocator(),
45 TypeTable(Allocator), CurFn(nullptr) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +000046 // If module doesn't have named metadata anchors or COFF debug section
47 // is not available, skip any debug info related stuff.
48 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
49 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
50 Asm = nullptr;
51 return;
52 }
53
54 // Tell MMI that we have debug info.
55 MMI->setDebugInfoAvailability(true);
56}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000057
Reid Kleckner9533af42016-01-16 00:09:09 +000058StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
59 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000060 if (!Filepath.empty())
61 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000062
Reid Kleckner9533af42016-01-16 00:09:09 +000063 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
64
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000065 // Clang emits directory and relative filename info into the IR, but CodeView
66 // operates on full paths. We could change Clang to emit full paths too, but
67 // that would increase the IR size and probably not needed for other users.
68 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000069 if (Filename.find(':') == 1)
70 Filepath = Filename;
71 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +000072 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000073
74 // Canonicalize the path. We have to do it textually because we may no longer
75 // have access the file in the filesystem.
76 // First, replace all slashes with backslashes.
77 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
78
79 // Remove all "\.\" with "\".
80 size_t Cursor = 0;
81 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
82 Filepath.erase(Cursor, 2);
83
84 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
85 // path should be well-formatted, e.g. start with a drive letter, etc.
86 Cursor = 0;
87 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
88 // Something's wrong if the path starts with "\..\", abort.
89 if (Cursor == 0)
90 break;
91
92 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
93 if (PrevSlash == std::string::npos)
94 // Something's wrong, abort.
95 break;
96
97 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
98 // The next ".." might be following the one we've just erased.
99 Cursor = PrevSlash;
100 }
101
102 // Remove all duplicate backslashes.
103 Cursor = 0;
104 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
105 Filepath.erase(Cursor, 1);
106
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000107 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000108}
109
Reid Kleckner2214ed82016-01-29 00:49:42 +0000110unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
111 unsigned NextId = FileIdMap.size() + 1;
112 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
113 if (Insertion.second) {
114 // We have to compute the full filepath and emit a .cv_file directive.
115 StringRef FullPath = getFullFilepath(F);
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000116 bool Success = OS.EmitCVFileDirective(NextId, FullPath);
117 (void)Success;
118 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000119 }
120 return Insertion.first->second;
121}
122
Reid Kleckner876330d2016-02-12 21:48:30 +0000123CodeViewDebug::InlineSite &
124CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
125 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000126 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
127 InlineSite *Site = &SiteInsertion.first->second;
128 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000129 unsigned ParentFuncId = CurFn->FuncId;
130 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
131 ParentFuncId =
132 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
133 .SiteFuncId;
134
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000135 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000136 OS.EmitCVInlineSiteIdDirective(
137 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
138 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000139 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000140 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000141 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000142 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000143 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000144}
145
David Majnemer6bdc24e2016-07-01 23:12:45 +0000146static StringRef getPrettyScopeName(const DIScope *Scope) {
147 StringRef ScopeName = Scope->getName();
148 if (!ScopeName.empty())
149 return ScopeName;
150
151 switch (Scope->getTag()) {
152 case dwarf::DW_TAG_enumeration_type:
153 case dwarf::DW_TAG_class_type:
154 case dwarf::DW_TAG_structure_type:
155 case dwarf::DW_TAG_union_type:
156 return "<unnamed-tag>";
157 case dwarf::DW_TAG_namespace:
158 return "`anonymous namespace'";
159 }
160
161 return StringRef();
162}
163
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000164static const DISubprogram *getQualifiedNameComponents(
165 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
166 const DISubprogram *ClosestSubprogram = nullptr;
167 while (Scope != nullptr) {
168 if (ClosestSubprogram == nullptr)
169 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000170 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000171 if (!ScopeName.empty())
172 QualifiedNameComponents.push_back(ScopeName);
173 Scope = Scope->getScope().resolve();
174 }
175 return ClosestSubprogram;
176}
177
178static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
179 StringRef TypeName) {
180 std::string FullyQualifiedName;
181 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
182 FullyQualifiedName.append(QualifiedNameComponent);
183 FullyQualifiedName.append("::");
184 }
185 FullyQualifiedName.append(TypeName);
186 return FullyQualifiedName;
187}
188
189static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
190 SmallVector<StringRef, 5> QualifiedNameComponents;
191 getQualifiedNameComponents(Scope, QualifiedNameComponents);
192 return getQualifiedName(QualifiedNameComponents, Name);
193}
194
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000195struct CodeViewDebug::TypeLoweringScope {
196 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
197 ~TypeLoweringScope() {
198 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
199 // inner TypeLoweringScopes don't attempt to emit deferred types.
200 if (CVD.TypeEmissionLevel == 1)
201 CVD.emitDeferredCompleteTypes();
202 --CVD.TypeEmissionLevel;
203 }
204 CodeViewDebug &CVD;
205};
206
David Majnemer6bdc24e2016-07-01 23:12:45 +0000207static std::string getFullyQualifiedName(const DIScope *Ty) {
208 const DIScope *Scope = Ty->getScope().resolve();
209 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
210}
211
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000212TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
213 // No scope means global scope and that uses the zero index.
214 if (!Scope || isa<DIFile>(Scope))
215 return TypeIndex();
216
217 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
218
219 // Check if we've already translated this scope.
220 auto I = TypeIndices.find({Scope, nullptr});
221 if (I != TypeIndices.end())
222 return I->second;
223
224 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000225 std::string ScopeName = getFullyQualifiedName(Scope);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000226 StringIdRecord SID(TypeIndex(), ScopeName);
227 auto TI = TypeTable.writeKnownType(SID);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000228 return recordTypeIndexForDINode(Scope, TI);
229}
230
David Majnemer75c3ebf2016-06-02 17:13:53 +0000231TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000232 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000233
David Majnemer75c3ebf2016-06-02 17:13:53 +0000234 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000235 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000236 if (I != TypeIndices.end())
237 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000238
Reid Klecknerac945e22016-06-17 16:11:20 +0000239 // The display name includes function template arguments. Drop them to match
240 // MSVC.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000241 StringRef DisplayName = SP->getName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000242
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000243 const DIScope *Scope = SP->getScope().resolve();
244 TypeIndex TI;
245 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
246 // If the scope is a DICompositeType, then this must be a method. Member
247 // function types take some special handling, and require access to the
248 // subprogram.
249 TypeIndex ClassType = getTypeIndex(Class);
250 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
251 DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000252 TI = TypeTable.writeKnownType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000253 } else {
254 // Otherwise, this must be a free function.
255 TypeIndex ParentScope = getScopeIndex(Scope);
256 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000257 TI = TypeTable.writeKnownType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000258 }
259
260 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000261}
262
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000263TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
264 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000265 // Always use the method declaration as the key for the function type. The
266 // method declaration contains the this adjustment.
267 if (SP->getDeclaration())
268 SP = SP->getDeclaration();
269 assert(!SP->getDeclaration() && "should use declaration as key");
270
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000271 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
272 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000273 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000274 if (I != TypeIndices.end())
275 return I->second;
276
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000277 // Make sure complete type info for the class is emitted *after* the member
278 // function type, as the complete class type is likely to reference this
279 // member function type.
280 TypeLoweringScope S(*this);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000281 TypeIndex TI =
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000282 lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000283 return recordTypeIndexForDINode(SP, TI, Class);
284}
285
Amjad Aboudacee5682016-07-12 12:06:34 +0000286TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
287 TypeIndex TI,
288 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000289 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000290 (void)InsertResult;
291 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000292 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000293}
294
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000295unsigned CodeViewDebug::getPointerSizeInBytes() {
296 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
297}
298
Reid Kleckner876330d2016-02-12 21:48:30 +0000299void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
300 const DILocation *InlinedAt) {
301 if (InlinedAt) {
302 // This variable was inlined. Associate it with the InlineSite.
303 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
304 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
305 Site.InlinedLocals.emplace_back(Var);
306 } else {
307 // This variable goes in the main ProcSym.
308 CurFn->Locals.emplace_back(Var);
309 }
310}
311
Reid Kleckner829365a2016-02-11 19:41:47 +0000312static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
313 const DILocation *Loc) {
314 auto B = Locs.begin(), E = Locs.end();
315 if (std::find(B, E, Loc) == E)
316 Locs.push_back(Loc);
317}
318
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000319void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000320 const MachineFunction *MF) {
321 // Skip this instruction if it has the same location as the previous one.
322 if (DL == CurFn->LastLoc)
323 return;
324
325 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000326 if (!Scope)
327 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000328
David Majnemerc3340db2016-01-13 01:05:23 +0000329 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000330 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
331 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
332 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000333 return;
334
Reid Kleckner2214ed82016-01-29 00:49:42 +0000335 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
336 if (CI.getStartColumn() != DL.getCol())
337 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000338
Reid Kleckner2214ed82016-01-29 00:49:42 +0000339 if (!CurFn->HaveLineInfo)
340 CurFn->HaveLineInfo = true;
341 unsigned FileId = 0;
342 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
343 FileId = CurFn->LastFileId;
344 else
345 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
346 CurFn->LastLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000347
348 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000349 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000350 const DILocation *Loc = DL.get();
351
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000352 // If this location was actually inlined from somewhere else, give it the ID
353 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000354 FuncId =
355 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000356
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000357 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000358 bool FirstLoc = true;
359 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000360 InlineSite &Site =
361 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000362 if (!FirstLoc)
363 addLocIfNotPresent(Site.ChildSites, Loc);
364 FirstLoc = false;
365 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000366 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000367 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000368 }
369
Reid Klecknerdac21b42016-02-03 21:15:48 +0000370 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000371 /*PrologueEnd=*/false, /*IsStmt=*/false,
372 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000373}
374
Reid Kleckner5d122f82016-05-25 23:16:12 +0000375void CodeViewDebug::emitCodeViewMagicVersion() {
376 OS.EmitValueToAlignment(4);
377 OS.AddComment("Debug section magic");
378 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
379}
380
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000381void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000382 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000383 return;
384
385 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000386
387 // The COFF .debug$S section consists of several subsections, each starting
388 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
389 // of the payload followed by the payload itself. The subsections are 4-byte
390 // aligned.
391
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000392 // Use the generic .debug$S section, and make a subsection for all the inlined
393 // subprograms.
394 switchToDebugSectionForSymbol(nullptr);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000395
Zachary Turner8c099fe2017-05-30 16:36:15 +0000396 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000397 emitCompilerInformation();
398 endCVSubsection(CompilerInfo);
399
Reid Kleckner5d122f82016-05-25 23:16:12 +0000400 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000401
Reid Kleckner2214ed82016-01-29 00:49:42 +0000402 // Emit per-function debug information.
403 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000404 if (!P.first->isDeclarationForLinker())
405 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000406
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000407 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000408 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000409 emitDebugInfoForGlobals();
410
Hans Wennborgb510b452016-06-23 16:33:53 +0000411 // Emit retained types.
412 emitDebugInfoForRetainedTypes();
413
Reid Kleckner5d122f82016-05-25 23:16:12 +0000414 // Switch back to the generic .debug$S section after potentially processing
415 // comdat symbol sections.
416 switchToDebugSectionForSymbol(nullptr);
417
David Majnemer3128b102016-06-15 18:00:01 +0000418 // Emit UDT records for any types used by global variables.
419 if (!GlobalUDTs.empty()) {
Zachary Turner8c099fe2017-05-30 16:36:15 +0000420 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
David Majnemer3128b102016-06-15 18:00:01 +0000421 emitDebugInfoForUDTs(GlobalUDTs);
422 endCVSubsection(SymbolsEnd);
423 }
424
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000425 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000426 OS.AddComment("File index to string table offset subsection");
427 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000428
429 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000430 OS.AddComment("String table");
431 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000432
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000433 // Emit type information last, so that any types we translate while emitting
434 // function info are included.
435 emitTypeInformation();
436
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000437 clear();
438}
439
David Majnemerb9456a52016-03-14 05:15:09 +0000440static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000441 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
442 // after a fixed length portion of the record. The fixed length portion should
443 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
444 // overall record size is less than the maximum allowed.
445 unsigned MaxFixedRecordLength = 0xF00;
446 SmallString<32> NullTerminatedString(
447 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
David Majnemerb9456a52016-03-14 05:15:09 +0000448 NullTerminatedString.push_back('\0');
449 OS.EmitBytes(NullTerminatedString);
450}
451
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000452void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000453 // Do nothing if we have no debug info or if no non-trivial types were emitted
454 // to TypeTable during codegen.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000455 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
Reid Klecknerfbd77872016-03-18 18:54:32 +0000456 if (!CU_Nodes)
457 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000458 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000459 return;
460
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000461 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000462 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000463 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000464
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000465 SmallString<8> CommentPrefix;
466 if (OS.isVerboseAsm()) {
467 CommentPrefix += '\t';
468 CommentPrefix += Asm->MAI->getCommentString();
469 CommentPrefix += ' ';
470 }
471
Zachary Turner526f4f22017-05-19 19:26:58 +0000472 TypeTableCollection Table(TypeTable.records());
473 Optional<TypeIndex> B = Table.getFirst();
474 while (B) {
475 // This will fail if the record data is invalid.
476 CVType Record = Table.getType(*B);
477
Zachary Turner4efa0a42016-11-08 22:24:53 +0000478 if (OS.isVerboseAsm()) {
479 // Emit a block comment describing the type record for readability.
480 SmallString<512> CommentBlock;
481 raw_svector_ostream CommentOS(CommentBlock);
482 ScopedPrinter SP(CommentOS);
483 SP.setPrefix(CommentPrefix);
Zachary Turner526f4f22017-05-19 19:26:58 +0000484 TypeDumpVisitor TDV(Table, &SP, false);
485
486 Error E = codeview::visitTypeRecord(Record, *B, TDV);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000487 if (E) {
488 logAllUnhandledErrors(std::move(E), errs(), "error: ");
489 llvm_unreachable("produced malformed type record");
490 }
491 // emitRawComment will insert its own tab and comment string before
492 // the first line, so strip off our first one. It also prints its own
493 // newline.
494 OS.emitRawComment(
495 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Zachary Turner4efa0a42016-11-08 22:24:53 +0000496 }
Zachary Turner526f4f22017-05-19 19:26:58 +0000497 OS.EmitBinaryData(Record.str_data());
498 B = Table.getNext(*B);
499 }
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000500}
501
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000502namespace {
503
504static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
505 switch (DWLang) {
506 case dwarf::DW_LANG_C:
507 case dwarf::DW_LANG_C89:
508 case dwarf::DW_LANG_C99:
509 case dwarf::DW_LANG_C11:
510 case dwarf::DW_LANG_ObjC:
511 return SourceLanguage::C;
512 case dwarf::DW_LANG_C_plus_plus:
513 case dwarf::DW_LANG_C_plus_plus_03:
514 case dwarf::DW_LANG_C_plus_plus_11:
515 case dwarf::DW_LANG_C_plus_plus_14:
516 return SourceLanguage::Cpp;
517 case dwarf::DW_LANG_Fortran77:
518 case dwarf::DW_LANG_Fortran90:
519 case dwarf::DW_LANG_Fortran03:
520 case dwarf::DW_LANG_Fortran08:
521 return SourceLanguage::Fortran;
522 case dwarf::DW_LANG_Pascal83:
523 return SourceLanguage::Pascal;
524 case dwarf::DW_LANG_Cobol74:
525 case dwarf::DW_LANG_Cobol85:
526 return SourceLanguage::Cobol;
527 case dwarf::DW_LANG_Java:
528 return SourceLanguage::Java;
529 default:
530 // There's no CodeView representation for this language, and CV doesn't
531 // have an "unknown" option for the language field, so we'll use MASM,
532 // as it's very low level.
533 return SourceLanguage::Masm;
534 }
535}
536
537struct Version {
538 int Part[4];
539};
540
541// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
542// the version number.
543static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000544 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000545 int N = 0;
546 for (const char C : Name) {
547 if (isdigit(C)) {
548 V.Part[N] *= 10;
549 V.Part[N] += C - '0';
550 } else if (C == '.') {
551 ++N;
552 if (N >= 4)
553 return V;
554 } else if (N > 0)
555 return V;
556 }
557 return V;
558}
559
560static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
561 switch (Type) {
562 case Triple::ArchType::x86:
563 return CPUType::Pentium3;
564 case Triple::ArchType::x86_64:
565 return CPUType::X64;
566 case Triple::ArchType::thumb:
567 return CPUType::Thumb;
568 default:
569 report_fatal_error("target architecture doesn't map to a CodeView "
570 "CPUType");
571 }
572}
573
574} // anonymous namespace
575
576void CodeViewDebug::emitCompilerInformation() {
577 MCContext &Context = MMI->getContext();
578 MCSymbol *CompilerBegin = Context.createTempSymbol(),
579 *CompilerEnd = Context.createTempSymbol();
580 OS.AddComment("Record length");
581 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
582 OS.EmitLabel(CompilerBegin);
583 OS.AddComment("Record kind: S_COMPILE3");
584 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
585 uint32_t Flags = 0;
586
587 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
588 const MDNode *Node = *CUs->operands().begin();
589 const auto *CU = cast<DICompileUnit>(Node);
590
591 // The low byte of the flags indicates the source language.
592 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
593 // TODO: Figure out which other flags need to be set.
594
595 OS.AddComment("Flags and language");
596 OS.EmitIntValue(Flags, 4);
597
598 OS.AddComment("CPUType");
599 CPUType CPU =
600 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
601 OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
602
603 StringRef CompilerVersion = CU->getProducer();
604 Version FrontVer = parseVersion(CompilerVersion);
605 OS.AddComment("Frontend version");
606 for (int N = 0; N < 4; ++N)
607 OS.EmitIntValue(FrontVer.Part[N], 2);
608
609 // Some Microsoft tools, like Binscope, expect a backend version number of at
610 // least 8.something, so we'll coerce the LLVM version into a form that
611 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000612 int Major = 1000 * LLVM_VERSION_MAJOR +
613 10 * LLVM_VERSION_MINOR +
614 LLVM_VERSION_PATCH;
615 // Clamp it for builds that use unusually large version numbers.
616 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
617 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000618 OS.AddComment("Backend version");
619 for (int N = 0; N < 4; ++N)
620 OS.EmitIntValue(BackVer.Part[N], 2);
621
622 OS.AddComment("Null-terminated compiler version string");
623 emitNullTerminatedSymbolName(OS, CompilerVersion);
624
625 OS.EmitLabel(CompilerEnd);
626}
627
Reid Kleckner5d122f82016-05-25 23:16:12 +0000628void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000629 if (InlinedSubprograms.empty())
630 return;
631
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000632 OS.AddComment("Inlinee lines subsection");
Zachary Turner8c099fe2017-05-30 16:36:15 +0000633 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000634
635 // We don't provide any extra file info.
636 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000637 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000638 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
639
640 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000641 assert(TypeIndices.count({SP, nullptr}));
642 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000643
David Majnemer30579ec2016-02-02 23:18:23 +0000644 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000645 unsigned FileId = maybeRecordFile(SP->getFile());
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000646 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000647 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000648 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000649 // The filechecksum table uses 8 byte entries for now, and file ids start at
650 // 1.
651 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000652 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000653 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000654 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000655 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000656 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000657 OS.EmitIntValue(SP->getLine(), 4);
658 }
659
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000660 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000661}
662
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000663void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
664 const DILocation *InlinedAt,
665 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000666 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
667 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000668
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000669 assert(TypeIndices.count({Site.Inlinee, nullptr}));
670 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000671
672 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000673 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000674 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000675 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000676 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000677 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000678
Reid Klecknerdac21b42016-02-03 21:15:48 +0000679 OS.AddComment("PtrParent");
680 OS.EmitIntValue(0, 4);
681 OS.AddComment("PtrEnd");
682 OS.EmitIntValue(0, 4);
683 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000684 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000685
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000686 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
687 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000688
689 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000690 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000691
692 OS.EmitLabel(InlineEnd);
693
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000694 emitLocalVariableList(Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000695
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000696 // Recurse on child inlined call sites before closing the scope.
697 for (const DILocation *ChildSite : Site.ChildSites) {
698 auto I = FI.InlineSites.find(ChildSite);
699 assert(I != FI.InlineSites.end() &&
700 "child site not in function inline site map");
701 emitInlinedCallSite(FI, ChildSite, I->second);
702 }
703
704 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000705 OS.AddComment("Record length");
706 OS.EmitIntValue(2, 2); // RecordLength
707 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000708 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000709}
710
Reid Kleckner5d122f82016-05-25 23:16:12 +0000711void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
712 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
713 // comdat key. A section may be comdat because of -ffunction-sections or
714 // because it is comdat in the IR.
715 MCSectionCOFF *GVSec =
716 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
717 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
718
719 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
720 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
721 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
722
723 OS.SwitchSection(DebugSec);
724
725 // Emit the magic version number if this is the first time we've switched to
726 // this section.
727 if (ComdatDebugSections.insert(DebugSec).second)
728 emitCodeViewMagicVersion();
729}
730
Reid Kleckner2214ed82016-01-29 00:49:42 +0000731void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
732 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000733 // For each function there is a separate subsection
734 // which holds the PC to file:line table.
735 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000736 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000737
Reid Kleckner5d122f82016-05-25 23:16:12 +0000738 // Switch to the to a comdat section, if appropriate.
739 switchToDebugSectionForSymbol(Fn);
740
Reid Klecknerac945e22016-06-17 16:11:20 +0000741 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000742 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000743 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000744 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000745
746 // If we have a display name, build the fully qualified name by walking the
747 // chain of scopes.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000748 if (!SP->getName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000749 FuncName =
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000750 getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000751
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000752 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000753 if (FuncName.empty())
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +0000754 FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000755
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000756 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000757 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Zachary Turner8c099fe2017-05-30 16:36:15 +0000758 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000759 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000760 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
761 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000762 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000763 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000764 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000765
Reid Kleckner4ad127f2016-09-14 21:49:21 +0000766 if (GV->hasLocalLinkage()) {
767 OS.AddComment("Record kind: S_LPROC32_ID");
768 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
769 } else {
770 OS.AddComment("Record kind: S_GPROC32_ID");
771 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
772 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000773
David Majnemer30579ec2016-02-02 23:18:23 +0000774 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000775 OS.AddComment("PtrParent");
776 OS.EmitIntValue(0, 4);
777 OS.AddComment("PtrEnd");
778 OS.EmitIntValue(0, 4);
779 OS.AddComment("PtrNext");
780 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000781 // This is the important bit that tells the debugger where the function
782 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000783 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000784 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000785 OS.AddComment("Offset after prologue");
786 OS.EmitIntValue(0, 4);
787 OS.AddComment("Offset before epilogue");
788 OS.EmitIntValue(0, 4);
789 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000790 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000791 OS.AddComment("Function section relative address");
Keno Fischerf7d84ee2017-01-02 03:00:19 +0000792 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000793 OS.AddComment("Function section index");
794 OS.EmitCOFFSectionIndex(Fn);
795 OS.AddComment("Flags");
796 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000797 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000798 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000799 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000800 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000801 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000802
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000803 emitLocalVariableList(FI.Locals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000804
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000805 // Emit inlined call site information. Only emit functions inlined directly
806 // into the parent function. We'll emit the other sites recursively as part
807 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000808 for (const DILocation *InlinedAt : FI.ChildSites) {
809 auto I = FI.InlineSites.find(InlinedAt);
810 assert(I != FI.InlineSites.end() &&
811 "child site not in function inline site map");
812 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000813 }
814
David Majnemer3128b102016-06-15 18:00:01 +0000815 if (SP != nullptr)
816 emitDebugInfoForUDTs(LocalUDTs);
817
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000818 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000819 OS.AddComment("Record length");
820 OS.EmitIntValue(0x0002, 2);
821 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000822 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000823 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000824 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000825
Reid Kleckner2214ed82016-01-29 00:49:42 +0000826 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000827 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000828}
829
Reid Kleckner876330d2016-02-12 21:48:30 +0000830CodeViewDebug::LocalVarDefRange
831CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
832 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000833 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000834 DR.DataOffset = Offset;
835 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000836 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000837 DR.StructOffset = 0;
838 DR.CVRegister = CVRegister;
839 return DR;
840}
841
842CodeViewDebug::LocalVarDefRange
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000843CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
844 int Offset, bool IsSubfield,
845 uint16_t StructOffset) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000846 LocalVarDefRange DR;
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000847 DR.InMemory = InMemory;
848 DR.DataOffset = Offset;
849 DR.IsSubfield = IsSubfield;
850 DR.StructOffset = StructOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +0000851 DR.CVRegister = CVRegister;
852 return DR;
853}
854
Matthias Braunef331ef2016-11-30 23:48:50 +0000855void CodeViewDebug::collectVariableInfoFromMFTable(
Reid Kleckner876330d2016-02-12 21:48:30 +0000856 DenseSet<InlinedVariable> &Processed) {
Matthias Braunef331ef2016-11-30 23:48:50 +0000857 const MachineFunction &MF = *Asm->MF;
858 const TargetSubtargetInfo &TSI = MF.getSubtarget();
Reid Kleckner876330d2016-02-12 21:48:30 +0000859 const TargetFrameLowering *TFI = TSI.getFrameLowering();
860 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
861
Matthias Braunef331ef2016-11-30 23:48:50 +0000862 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000863 if (!VI.Var)
864 continue;
865 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
866 "Expected inlined-at fields to agree");
867
Reid Kleckner876330d2016-02-12 21:48:30 +0000868 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000869 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
870
871 // If variable scope is not found then skip this variable.
872 if (!Scope)
873 continue;
874
Reid Klecknerb5fced72017-05-09 19:59:29 +0000875 // If the variable has an attached offset expression, extract it.
876 // FIXME: Try to handle DW_OP_deref as well.
877 int64_t ExprOffset = 0;
878 if (VI.Expr)
879 if (!VI.Expr->extractIfOffset(ExprOffset))
880 continue;
881
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000882 // Get the frame register used and the offset.
883 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000884 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
885 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000886
887 // Calculate the label ranges.
Reid Klecknerb5fced72017-05-09 19:59:29 +0000888 LocalVarDefRange DefRange =
889 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000890 for (const InsnRange &Range : Scope->getRanges()) {
891 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
892 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000893 End = End ? End : Asm->getFunctionEnd();
894 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000895 }
896
Reid Kleckner876330d2016-02-12 21:48:30 +0000897 LocalVariable Var;
898 Var.DIVar = VI.Var;
899 Var.DefRanges.emplace_back(std::move(DefRange));
900 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
901 }
902}
903
904void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
905 DenseSet<InlinedVariable> Processed;
906 // Grab the variable info that was squirreled away in the MMI side-table.
Matthias Braunef331ef2016-11-30 23:48:50 +0000907 collectVariableInfoFromMFTable(Processed);
Reid Kleckner876330d2016-02-12 21:48:30 +0000908
909 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
910
911 for (const auto &I : DbgValues) {
912 InlinedVariable IV = I.first;
913 if (Processed.count(IV))
914 continue;
915 const DILocalVariable *DIVar = IV.first;
916 const DILocation *InlinedAt = IV.second;
917
918 // Instruction ranges, specifying where IV is accessible.
919 const auto &Ranges = I.second;
920
921 LexicalScope *Scope = nullptr;
922 if (InlinedAt)
923 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
924 else
925 Scope = LScopes.findLexicalScope(DIVar->getScope());
926 // If variable scope is not found then skip this variable.
927 if (!Scope)
928 continue;
929
930 LocalVariable Var;
931 Var.DIVar = DIVar;
932
933 // Calculate the definition ranges.
934 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
935 const InsnRange &Range = *I;
936 const MachineInstr *DVInst = Range.first;
937 assert(DVInst->isDebugValue() && "Invalid History entry");
938 const DIExpression *DIExpr = DVInst->getDebugExpression();
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000939 bool IsSubfield = false;
940 unsigned StructOffset = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000941
Adrian Prantl941fa752016-12-05 18:04:47 +0000942 // Handle fragments.
Adrian Prantl49797ca2016-12-22 05:27:12 +0000943 auto Fragment = DIExpr->getFragmentInfo();
Adrian Prantle8450fd2017-03-27 17:36:31 +0000944 if (Fragment) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000945 IsSubfield = true;
Adrian Prantl49797ca2016-12-22 05:27:12 +0000946 StructOffset = Fragment->OffsetInBits / 8;
Adrian Prantle8450fd2017-03-27 17:36:31 +0000947 } else if (DIExpr->getNumElements() > 0) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000948 continue; // Ignore unrecognized exprs.
949 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000950
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000951 // Bail if operand 0 is not a valid register. This means the variable is a
952 // simple constant, or is described by a complex expression.
953 // FIXME: Find a way to represent constant variables, since they are
954 // relatively common.
955 unsigned Reg =
956 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
957 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +0000958 continue;
959
Reid Kleckner876330d2016-02-12 21:48:30 +0000960 // Handle the two cases we can handle: indirect in memory and in register.
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000961 unsigned CVReg = TRI->getCodeViewRegNum(Reg);
962 bool InMemory = DVInst->getOperand(1).isImm();
963 int Offset = InMemory ? DVInst->getOperand(1).getImm() : 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000964 {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000965 LocalVarDefRange DR;
966 DR.CVRegister = CVReg;
967 DR.InMemory = InMemory;
968 DR.DataOffset = Offset;
969 DR.IsSubfield = IsSubfield;
970 DR.StructOffset = StructOffset;
971
Reid Kleckner876330d2016-02-12 21:48:30 +0000972 if (Var.DefRanges.empty() ||
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000973 Var.DefRanges.back().isDifferentLocation(DR)) {
974 Var.DefRanges.emplace_back(std::move(DR));
Reid Kleckner876330d2016-02-12 21:48:30 +0000975 }
976 }
977
978 // Compute the label range.
979 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
980 const MCSymbol *End = getLabelAfterInsn(Range.second);
981 if (!End) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000982 // This range is valid until the next overlapping bitpiece. In the
983 // common case, ranges will not be bitpieces, so they will overlap.
984 auto J = std::next(I);
Adrian Prantl941fa752016-12-05 18:04:47 +0000985 while (J != E &&
986 !fragmentsOverlap(DIExpr, J->first->getDebugExpression()))
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000987 ++J;
988 if (J != E)
989 End = getLabelBeforeInsn(J->first);
Reid Kleckner876330d2016-02-12 21:48:30 +0000990 else
991 End = Asm->getFunctionEnd();
992 }
993
994 // If the last range end is our begin, just extend the last range.
995 // Otherwise make a new range.
996 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
997 Var.DefRanges.back().Ranges;
998 if (!Ranges.empty() && Ranges.back().second == Begin)
999 Ranges.back().second = End;
1000 else
1001 Ranges.emplace_back(Begin, End);
1002
1003 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001004 }
Reid Kleckner876330d2016-02-12 21:48:30 +00001005
1006 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001007 }
1008}
1009
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001010void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001011 const Function *GV = MF->getFunction();
1012 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001013 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +00001014 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001015 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001016
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001017 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1018
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001019 // Find the end of the function prolog. First known non-DBG_VALUE and
1020 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001021 // FIXME: is there a simpler a way to do this? Can we just search
1022 // for the first instruction of the function, not the last of the prolog?
1023 DebugLoc PrologEndLoc;
1024 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001025 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001026 for (const auto &MI : MBB) {
Adrian Prantlfb31da12017-05-22 20:47:09 +00001027 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001028 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001029 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001030 break;
Adrian Prantlfb31da12017-05-22 20:47:09 +00001031 } else if (!MI.isMetaInstruction()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001032 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001033 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001034 }
1035 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001036
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001037 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001038 if (PrologEndLoc && !EmptyPrologue) {
1039 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001040 maybeRecordLocation(FnStartDL, MF);
1041 }
1042}
1043
Hans Wennborg4b63a982016-06-23 22:57:25 +00001044void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001045 // Don't record empty UDTs.
1046 if (Ty->getName().empty())
1047 return;
1048
Hans Wennborg4b63a982016-06-23 22:57:25 +00001049 SmallVector<StringRef, 5> QualifiedNameComponents;
1050 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1051 Ty->getScope().resolve(), QualifiedNameComponents);
1052
1053 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001054 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001055
1056 if (ClosestSubprogram == nullptr)
1057 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1058 else if (ClosestSubprogram == CurrentSubprogram)
1059 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1060
1061 // TODO: What if the ClosestSubprogram is neither null or the current
1062 // subprogram? Currently, the UDT just gets dropped on the floor.
1063 //
1064 // The current behavior is not desirable. To get maximal fidelity, we would
1065 // need to perform all type translation before beginning emission of .debug$S
1066 // and then make LocalUDTs a member of FunctionInfo
1067}
1068
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001069TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001070 // Generic dispatch for lowering an unknown type.
1071 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001072 case dwarf::DW_TAG_array_type:
1073 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001074 case dwarf::DW_TAG_typedef:
1075 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001076 case dwarf::DW_TAG_base_type:
1077 return lowerTypeBasic(cast<DIBasicType>(Ty));
1078 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001079 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1080 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1081 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001082 case dwarf::DW_TAG_reference_type:
1083 case dwarf::DW_TAG_rvalue_reference_type:
1084 return lowerTypePointer(cast<DIDerivedType>(Ty));
1085 case dwarf::DW_TAG_ptr_to_member_type:
1086 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1087 case dwarf::DW_TAG_const_type:
1088 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001089 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001090 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001091 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001092 if (ClassTy) {
1093 // The member function type of a member function pointer has no
1094 // ThisAdjustment.
1095 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1096 /*ThisAdjustment=*/0);
1097 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001098 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001099 case dwarf::DW_TAG_enumeration_type:
1100 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001101 case dwarf::DW_TAG_class_type:
1102 case dwarf::DW_TAG_structure_type:
1103 return lowerTypeClass(cast<DICompositeType>(Ty));
1104 case dwarf::DW_TAG_union_type:
1105 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001106 default:
1107 // Use the null type index.
1108 return TypeIndex();
1109 }
1110}
1111
David Majnemerd065e232016-06-02 06:21:37 +00001112TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001113 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1114 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001115 StringRef TypeName = Ty->getName();
1116
Hans Wennborg4b63a982016-06-23 22:57:25 +00001117 addToUDTs(Ty, UnderlyingTypeIndex);
David Majnemer3128b102016-06-15 18:00:01 +00001118
David Majnemerd065e232016-06-02 06:21:37 +00001119 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001120 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001121 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001122 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001123 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001124 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001125
David Majnemerd065e232016-06-02 06:21:37 +00001126 return UnderlyingTypeIndex;
1127}
1128
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001129TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1130 DITypeRef ElementTypeRef = Ty->getBaseType();
1131 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1132 // IndexType is size_t, which depends on the bitness of the target.
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001133 TypeIndex IndexType = Asm->TM.getPointerSize() == 8
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001134 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1135 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001136
1137 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1138
Amjad Aboudacee5682016-07-12 12:06:34 +00001139 // Add subranges to array type.
1140 DINodeArray Elements = Ty->getElements();
1141 for (int i = Elements.size() - 1; i >= 0; --i) {
1142 const DINode *Element = Elements[i];
1143 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1144
1145 const DISubrange *Subrange = cast<DISubrange>(Element);
1146 assert(Subrange->getLowerBound() == 0 &&
1147 "codeview doesn't support subranges with lower bounds");
1148 int64_t Count = Subrange->getCount();
1149
1150 // Variable Length Array (VLA) has Count equal to '-1'.
1151 // Replace with Count '1', assume it is the minimum VLA length.
1152 // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
Reid Kleckner6b78e162017-03-24 23:28:42 +00001153 if (Count == -1)
Amjad Aboudacee5682016-07-12 12:06:34 +00001154 Count = 1;
Amjad Aboudacee5682016-07-12 12:06:34 +00001155
Amjad Aboudacee5682016-07-12 12:06:34 +00001156 // Update the element size and element type index for subsequent subranges.
1157 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001158
1159 // If this is the outermost array, use the size from the array. It will be
Reid Kleckner6b78e162017-03-24 23:28:42 +00001160 // more accurate if we had a VLA or an incomplete element type size.
Reid Kleckner10762882016-09-09 17:29:36 +00001161 uint64_t ArraySize =
1162 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1163
1164 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner4efa0a42016-11-08 22:24:53 +00001165 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1166 ElementTypeIndex = TypeTable.writeKnownType(AR);
Amjad Aboudacee5682016-07-12 12:06:34 +00001167 }
1168
Amjad Aboudacee5682016-07-12 12:06:34 +00001169 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001170}
1171
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001172TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1173 TypeIndex Index;
1174 dwarf::TypeKind Kind;
1175 uint32_t ByteSize;
1176
1177 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001178 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001179
1180 SimpleTypeKind STK = SimpleTypeKind::None;
1181 switch (Kind) {
1182 case dwarf::DW_ATE_address:
1183 // FIXME: Translate
1184 break;
1185 case dwarf::DW_ATE_boolean:
1186 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001187 case 1: STK = SimpleTypeKind::Boolean8; break;
1188 case 2: STK = SimpleTypeKind::Boolean16; break;
1189 case 4: STK = SimpleTypeKind::Boolean32; break;
1190 case 8: STK = SimpleTypeKind::Boolean64; break;
1191 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001192 }
1193 break;
1194 case dwarf::DW_ATE_complex_float:
1195 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001196 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001197 case 4: STK = SimpleTypeKind::Complex32; break;
1198 case 8: STK = SimpleTypeKind::Complex64; break;
1199 case 10: STK = SimpleTypeKind::Complex80; break;
1200 case 16: STK = SimpleTypeKind::Complex128; break;
1201 }
1202 break;
1203 case dwarf::DW_ATE_float:
1204 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001205 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001206 case 4: STK = SimpleTypeKind::Float32; break;
1207 case 6: STK = SimpleTypeKind::Float48; break;
1208 case 8: STK = SimpleTypeKind::Float64; break;
1209 case 10: STK = SimpleTypeKind::Float80; break;
1210 case 16: STK = SimpleTypeKind::Float128; break;
1211 }
1212 break;
1213 case dwarf::DW_ATE_signed:
1214 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001215 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1216 case 2: STK = SimpleTypeKind::Int16Short; break;
1217 case 4: STK = SimpleTypeKind::Int32; break;
1218 case 8: STK = SimpleTypeKind::Int64Quad; break;
1219 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001220 }
1221 break;
1222 case dwarf::DW_ATE_unsigned:
1223 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001224 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1225 case 2: STK = SimpleTypeKind::UInt16Short; break;
1226 case 4: STK = SimpleTypeKind::UInt32; break;
1227 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1228 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001229 }
1230 break;
1231 case dwarf::DW_ATE_UTF:
1232 switch (ByteSize) {
1233 case 2: STK = SimpleTypeKind::Character16; break;
1234 case 4: STK = SimpleTypeKind::Character32; break;
1235 }
1236 break;
1237 case dwarf::DW_ATE_signed_char:
1238 if (ByteSize == 1)
1239 STK = SimpleTypeKind::SignedCharacter;
1240 break;
1241 case dwarf::DW_ATE_unsigned_char:
1242 if (ByteSize == 1)
1243 STK = SimpleTypeKind::UnsignedCharacter;
1244 break;
1245 default:
1246 break;
1247 }
1248
1249 // Apply some fixups based on the source-level type name.
1250 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1251 STK = SimpleTypeKind::Int32Long;
1252 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1253 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001254 if (STK == SimpleTypeKind::UInt16Short &&
1255 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001256 STK = SimpleTypeKind::WideCharacter;
1257 if ((STK == SimpleTypeKind::SignedCharacter ||
1258 STK == SimpleTypeKind::UnsignedCharacter) &&
1259 Ty->getName() == "char")
1260 STK = SimpleTypeKind::NarrowCharacter;
1261
1262 return TypeIndex(STK);
1263}
1264
1265TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1266 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1267
1268 // Pointers to simple types can use SimpleTypeMode, rather than having a
1269 // dedicated pointer type record.
1270 if (PointeeTI.isSimple() &&
1271 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1272 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1273 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1274 ? SimpleTypeMode::NearPointer64
1275 : SimpleTypeMode::NearPointer32;
1276 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1277 }
1278
1279 PointerKind PK =
1280 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1281 PointerMode PM = PointerMode::Pointer;
1282 switch (Ty->getTag()) {
1283 default: llvm_unreachable("not a pointer tag type");
1284 case dwarf::DW_TAG_pointer_type:
1285 PM = PointerMode::Pointer;
1286 break;
1287 case dwarf::DW_TAG_reference_type:
1288 PM = PointerMode::LValueReference;
1289 break;
1290 case dwarf::DW_TAG_rvalue_reference_type:
1291 PM = PointerMode::RValueReference;
1292 break;
1293 }
1294 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1295 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1296 // do.
1297 PointerOptions PO = PointerOptions::None;
1298 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001299 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001300}
1301
Reid Kleckner6fa15462016-06-17 22:14:39 +00001302static PointerToMemberRepresentation
1303translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1304 // SizeInBytes being zero generally implies that the member pointer type was
1305 // incomplete, which can happen if it is part of a function prototype. In this
1306 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001307 if (IsPMF) {
1308 switch (Flags & DINode::FlagPtrToMemberRep) {
1309 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001310 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1311 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001312 case DINode::FlagSingleInheritance:
1313 return PointerToMemberRepresentation::SingleInheritanceFunction;
1314 case DINode::FlagMultipleInheritance:
1315 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1316 case DINode::FlagVirtualInheritance:
1317 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1318 }
1319 } else {
1320 switch (Flags & DINode::FlagPtrToMemberRep) {
1321 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001322 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1323 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001324 case DINode::FlagSingleInheritance:
1325 return PointerToMemberRepresentation::SingleInheritanceData;
1326 case DINode::FlagMultipleInheritance:
1327 return PointerToMemberRepresentation::MultipleInheritanceData;
1328 case DINode::FlagVirtualInheritance:
1329 return PointerToMemberRepresentation::VirtualInheritanceData;
1330 }
1331 }
1332 llvm_unreachable("invalid ptr to member representation");
1333}
1334
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001335TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1336 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1337 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001338 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001339 PointerKind PK = Asm->TM.getPointerSize() == 8 ? PointerKind::Near64
1340 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001341 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1342 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1343 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001344 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner6fa15462016-06-17 22:14:39 +00001345 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1346 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1347 MemberPointerInfo MPI(
1348 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001349 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001350 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001351}
1352
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001353/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1354/// have a translation, use the NearC convention.
1355static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1356 switch (DwarfCC) {
1357 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1358 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1359 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1360 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1361 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1362 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1363 }
1364 return CallingConvention::NearC;
1365}
1366
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001367TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1368 ModifierOptions Mods = ModifierOptions::None;
1369 bool IsModifier = true;
1370 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001371 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001372 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001373 switch (BaseTy->getTag()) {
1374 case dwarf::DW_TAG_const_type:
1375 Mods |= ModifierOptions::Const;
1376 break;
1377 case dwarf::DW_TAG_volatile_type:
1378 Mods |= ModifierOptions::Volatile;
1379 break;
1380 default:
1381 IsModifier = false;
1382 break;
1383 }
1384 if (IsModifier)
1385 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1386 }
1387 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001388 ModifierRecord MR(ModifiedTI, Mods);
1389 return TypeTable.writeKnownType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001390}
1391
David Majnemer75c3ebf2016-06-02 17:13:53 +00001392TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1393 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1394 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1395 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1396
1397 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1398 ArrayRef<TypeIndex> ArgTypeIndices = None;
1399 if (!ReturnAndArgTypeIndices.empty()) {
1400 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1401 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1402 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1403 }
1404
1405 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001406 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001407
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001408 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1409
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001410 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1411 ArgTypeIndices.size(), ArgListIndex);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001412 return TypeTable.writeKnownType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001413}
1414
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001415TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001416 const DIType *ClassTy,
1417 int ThisAdjustment) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001418 // Lower the containing class type.
1419 TypeIndex ClassType = getTypeIndex(ClassTy);
1420
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001421 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1422 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1423 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1424
1425 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1426 ArrayRef<TypeIndex> ArgTypeIndices = None;
1427 if (!ReturnAndArgTypeIndices.empty()) {
1428 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1429 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1430 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1431 }
1432 TypeIndex ThisTypeIndex = TypeIndex::Void();
1433 if (!ArgTypeIndices.empty()) {
1434 ThisTypeIndex = ArgTypeIndices.front();
1435 ArgTypeIndices = ArgTypeIndices.drop_front();
1436 }
1437
1438 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001439 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001440
1441 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1442
1443 // TODO: Need to use the correct values for:
1444 // FunctionOptions
1445 // ThisPointerAdjustment.
Zachary Turner4efa0a42016-11-08 22:24:53 +00001446 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
1447 FunctionOptions::None, ArgTypeIndices.size(),
1448 ArgListIndex, ThisAdjustment);
1449 TypeIndex TI = TypeTable.writeKnownType(MFR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001450
1451 return TI;
1452}
1453
Reid Kleckner9dac4732016-08-31 15:59:30 +00001454TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001455 unsigned VSlotCount =
1456 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
Reid Kleckner9dac4732016-08-31 15:59:30 +00001457 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001458
1459 VFTableShapeRecord VFTSR(Slots);
1460 return TypeTable.writeKnownType(VFTSR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001461}
1462
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001463static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1464 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001465 case DINode::FlagPrivate: return MemberAccess::Private;
1466 case DINode::FlagPublic: return MemberAccess::Public;
1467 case DINode::FlagProtected: return MemberAccess::Protected;
1468 case 0:
1469 // If there was no explicit access control, provide the default for the tag.
1470 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1471 : MemberAccess::Public;
1472 }
1473 llvm_unreachable("access flags are exclusive");
1474}
1475
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001476static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1477 if (SP->isArtificial())
1478 return MethodOptions::CompilerGenerated;
1479
1480 // FIXME: Handle other MethodOptions.
1481
1482 return MethodOptions::None;
1483}
1484
1485static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1486 bool Introduced) {
1487 switch (SP->getVirtuality()) {
1488 case dwarf::DW_VIRTUALITY_none:
1489 break;
1490 case dwarf::DW_VIRTUALITY_virtual:
1491 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1492 case dwarf::DW_VIRTUALITY_pure_virtual:
1493 return Introduced ? MethodKind::PureIntroducingVirtual
1494 : MethodKind::PureVirtual;
1495 default:
1496 llvm_unreachable("unhandled virtuality case");
1497 }
1498
1499 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1500
1501 return MethodKind::Vanilla;
1502}
1503
Reid Klecknera8d57402016-06-03 15:58:20 +00001504static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1505 switch (Ty->getTag()) {
1506 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1507 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1508 }
1509 llvm_unreachable("unexpected tag");
1510}
1511
Reid Klecknere092dad2016-07-02 00:11:07 +00001512/// Return ClassOptions that should be present on both the forward declaration
1513/// and the defintion of a tag type.
1514static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1515 ClassOptions CO = ClassOptions::None;
1516
1517 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001518 // appear to give every type a linkage name, which may be problematic for us.
1519 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001520 if (!Ty->getIdentifier().empty())
1521 CO |= ClassOptions::HasUniqueName;
1522
1523 // Put the Nested flag on a type if it appears immediately inside a tag type.
1524 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1525 // here. That flag is only set on definitions, and not forward declarations.
1526 const DIScope *ImmediateScope = Ty->getScope().resolve();
1527 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1528 CO |= ClassOptions::Nested;
1529
1530 // Put the Scoped flag on function-local types.
1531 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1532 Scope = Scope->getScope().resolve()) {
1533 if (isa<DISubprogram>(Scope)) {
1534 CO |= ClassOptions::Scoped;
1535 break;
1536 }
1537 }
1538
1539 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001540}
1541
David Majnemer979cb882016-06-16 21:32:16 +00001542TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001543 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001544 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001545 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001546
David Majnemerda9548f2016-06-17 16:13:21 +00001547 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001548 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001549 } else {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001550 FieldListRecordBuilder FLRB(TypeTable);
1551
1552 FLRB.begin();
David Majnemerda9548f2016-06-17 16:13:21 +00001553 for (const DINode *Element : Ty->getElements()) {
1554 // We assume that the frontend provides all members in source declaration
1555 // order, which is what MSVC does.
1556 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001557 EnumeratorRecord ER(MemberAccess::Public,
1558 APSInt::getUnsigned(Enumerator->getValue()),
1559 Enumerator->getName());
1560 FLRB.writeMemberType(ER);
David Majnemerda9548f2016-06-17 16:13:21 +00001561 EnumeratorCount++;
1562 }
1563 }
Zachary Turner7f97c362017-05-25 21:15:37 +00001564 FTI = FLRB.end(true);
David Majnemerda9548f2016-06-17 16:13:21 +00001565 }
David Majnemer979cb882016-06-16 21:32:16 +00001566
David Majnemer6bdc24e2016-07-01 23:12:45 +00001567 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001568
Zachary Turner4efa0a42016-11-08 22:24:53 +00001569 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
1570 getTypeIndex(Ty->getBaseType()));
1571 return TypeTable.writeKnownType(ER);
David Majnemer979cb882016-06-16 21:32:16 +00001572}
1573
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001574//===----------------------------------------------------------------------===//
1575// ClassInfo
1576//===----------------------------------------------------------------------===//
1577
1578struct llvm::ClassInfo {
1579 struct MemberInfo {
1580 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00001581 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001582 };
1583 // [MemberInfo]
1584 typedef std::vector<MemberInfo> MemberList;
1585
Reid Kleckner156a7232016-06-22 18:31:14 +00001586 typedef TinyPtrVector<const DISubprogram *> MethodsList;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001587 // MethodName -> MethodsList
1588 typedef MapVector<MDString *, MethodsList> MethodsMap;
1589
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001590 /// Base classes.
1591 std::vector<const DIDerivedType *> Inheritance;
1592
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001593 /// Direct members.
1594 MemberList Members;
1595 // Direct overloaded methods gathered by name.
1596 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001597
Reid Kleckner9dac4732016-08-31 15:59:30 +00001598 TypeIndex VShapeTI;
1599
Adrian McCarthy820ca542016-07-06 19:49:51 +00001600 std::vector<const DICompositeType *> NestedClasses;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001601};
1602
1603void CodeViewDebug::clear() {
1604 assert(CurFn == nullptr);
1605 FileIdMap.clear();
1606 FnDebugInfo.clear();
1607 FileToFilepathMap.clear();
1608 LocalUDTs.clear();
1609 GlobalUDTs.clear();
1610 TypeIndices.clear();
1611 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001612}
1613
1614void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1615 const DIDerivedType *DDTy) {
1616 if (!DDTy->getName().empty()) {
1617 Info.Members.push_back({DDTy, 0});
1618 return;
1619 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001620 // An unnamed member must represent a nested struct or union. Add all the
1621 // indirect fields to the current record.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001622 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00001623 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001624 const DIType *Ty = DDTy->getBaseType().resolve();
Reid Kleckner9ff936c2016-06-21 14:56:24 +00001625 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001626 ClassInfo NestedInfo = collectClassInfo(DCTy);
1627 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001628 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001629 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001630}
1631
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001632ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1633 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001634 // Add elements to structure type.
1635 DINodeArray Elements = Ty->getElements();
1636 for (auto *Element : Elements) {
1637 // We assume that the frontend provides all members in source declaration
1638 // order, which is what MSVC does.
1639 if (!Element)
1640 continue;
1641 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001642 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001643 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001644 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001645 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001646 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1647 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001648 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1649 DDTy->getName() == "__vtbl_ptr_type") {
1650 Info.VShapeTI = getTypeIndex(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001651 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1652 // Ignore friend members. It appears that MSVC emitted info about
1653 // friends in the past, but modern versions do not.
1654 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001655 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1656 Info.NestedClasses.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001657 }
1658 // Skip other unrecognized kinds of elements.
1659 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001660 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001661}
1662
Reid Klecknera8d57402016-06-03 15:58:20 +00001663TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1664 // First, construct the forward decl. Don't look into Ty to compute the
1665 // forward decl options, since it might not be available in all TUs.
1666 TypeRecordKind Kind = getRecordKind(Ty);
1667 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001668 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001669 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001670 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
1671 FullName, Ty->getIdentifier());
1672 TypeIndex FwdDeclTI = TypeTable.writeKnownType(CR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001673 if (!Ty->isForwardDecl())
1674 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001675 return FwdDeclTI;
1676}
1677
1678TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1679 // Construct the field list and complete type record.
1680 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00001681 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001682 TypeIndex FieldTI;
1683 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001684 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001685 bool ContainsNestedClass;
1686 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1687 lowerRecordFieldList(Ty);
1688
1689 if (ContainsNestedClass)
1690 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00001691
David Majnemer6bdc24e2016-07-01 23:12:45 +00001692 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001693
Reid Klecknera8d57402016-06-03 15:58:20 +00001694 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00001695
Zachary Turner4efa0a42016-11-08 22:24:53 +00001696 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
1697 SizeInBytes, FullName, Ty->getIdentifier());
1698 TypeIndex ClassTI = TypeTable.writeKnownType(CR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001699
Saleem Abdulrasool87f03382017-05-03 21:39:01 +00001700 if (const auto *File = Ty->getFile()) {
1701 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
1702 TypeIndex SIDI = TypeTable.writeKnownType(SIDR);
1703 UdtSourceLineRecord USLR(ClassTI, SIDI, Ty->getLine());
1704 TypeTable.writeKnownType(USLR);
1705 }
Hans Wennborg9a519a02016-06-22 21:22:13 +00001706
Hans Wennborg4b63a982016-06-23 22:57:25 +00001707 addToUDTs(Ty, ClassTI);
1708
Hans Wennborg9a519a02016-06-22 21:22:13 +00001709 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001710}
1711
1712TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1713 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001714 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001715 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001716 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
1717 TypeIndex FwdDeclTI = TypeTable.writeKnownType(UR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001718 if (!Ty->isForwardDecl())
1719 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001720 return FwdDeclTI;
1721}
1722
1723TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00001724 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001725 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001726 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001727 bool ContainsNestedClass;
1728 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1729 lowerRecordFieldList(Ty);
1730
1731 if (ContainsNestedClass)
1732 CO |= ClassOptions::ContainsNestedClass;
1733
Reid Klecknera8d57402016-06-03 15:58:20 +00001734 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00001735 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001736
Zachary Turner4efa0a42016-11-08 22:24:53 +00001737 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
1738 Ty->getIdentifier());
1739 TypeIndex UnionTI = TypeTable.writeKnownType(UR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001740
Zachary Turner4efa0a42016-11-08 22:24:53 +00001741 StringIdRecord SIR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
1742 TypeIndex SIRI = TypeTable.writeKnownType(SIR);
1743 UdtSourceLineRecord USLR(UnionTI, SIRI, Ty->getLine());
1744 TypeTable.writeKnownType(USLR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001745
Hans Wennborg4b63a982016-06-23 22:57:25 +00001746 addToUDTs(Ty, UnionTI);
1747
Hans Wennborg9a519a02016-06-22 21:22:13 +00001748 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001749}
1750
Adrian McCarthy820ca542016-07-06 19:49:51 +00001751std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00001752CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1753 // Manually count members. MSVC appears to count everything that generates a
1754 // field list record. Each individual overload in a method overload group
1755 // contributes to this count, even though the overload group is a single field
1756 // list record.
1757 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001758 ClassInfo Info = collectClassInfo(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001759 FieldListRecordBuilder FLBR(TypeTable);
1760 FLBR.begin();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001761
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001762 // Create base classes.
1763 for (const DIDerivedType *I : Info.Inheritance) {
1764 if (I->getFlags() & DINode::FlagVirtual) {
1765 // Virtual base.
1766 // FIXME: Emit VBPtrOffset when the frontend provides it.
1767 unsigned VBPtrOffset = 0;
1768 // FIXME: Despite the accessor name, the offset is really in bytes.
1769 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00001770 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
1771 ? TypeRecordKind::IndirectVirtualBaseClass
1772 : TypeRecordKind::VirtualBaseClass;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001773 VirtualBaseClassRecord VBCR(
Bob Haarman26a87bd2016-10-25 22:11:52 +00001774 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001775 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
Zachary Turner4efa0a42016-11-08 22:24:53 +00001776 VBTableIndex);
1777
1778 FLBR.writeMemberType(VBCR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001779 } else {
1780 assert(I->getOffsetInBits() % 8 == 0 &&
1781 "bases must be on byte boundaries");
Zachary Turner4efa0a42016-11-08 22:24:53 +00001782 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
1783 getTypeIndex(I->getBaseType()),
1784 I->getOffsetInBits() / 8);
1785 FLBR.writeMemberType(BCR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001786 }
1787 }
1788
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001789 // Create members.
1790 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1791 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1792 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00001793 StringRef MemberName = Member->getName();
1794 MemberAccess Access =
1795 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001796
1797 if (Member->isStaticMember()) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001798 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
1799 FLBR.writeMemberType(SDMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001800 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001801 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00001802 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001803
Reid Kleckner9dac4732016-08-31 15:59:30 +00001804 // Virtual function pointer member.
1805 if ((Member->getFlags() & DINode::FlagArtificial) &&
1806 Member->getName().startswith("_vptr$")) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001807 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
1808 FLBR.writeMemberType(VFPR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001809 MemberCount++;
1810 continue;
1811 }
1812
David Majnemer9319cbc2016-06-30 03:00:20 +00001813 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00001814 uint64_t MemberOffsetInBits =
1815 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001816 if (Member->isBitField()) {
1817 uint64_t StartBitOffset = MemberOffsetInBits;
1818 if (const auto *CI =
1819 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00001820 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001821 }
1822 StartBitOffset -= MemberOffsetInBits;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001823 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
1824 StartBitOffset);
1825 MemberBaseType = TypeTable.writeKnownType(BFR);
David Majnemer9319cbc2016-06-30 03:00:20 +00001826 }
1827 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001828 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
1829 MemberName);
1830 FLBR.writeMemberType(DMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001831 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001832 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001833
1834 // Create methods
1835 for (auto &MethodItr : Info.Methods) {
1836 StringRef Name = MethodItr.first->getString();
1837
1838 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00001839 for (const DISubprogram *SP : MethodItr.second) {
1840 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1841 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001842
1843 unsigned VFTableOffset = -1;
1844 if (Introduced)
1845 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1846
Zachary Turner7251ede2016-11-02 17:05:19 +00001847 Methods.push_back(OneMethodRecord(
1848 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
1849 translateMethodKindFlags(SP, Introduced),
1850 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001851 MemberCount++;
1852 }
1853 assert(Methods.size() > 0 && "Empty methods map entry");
1854 if (Methods.size() == 1)
Zachary Turner4efa0a42016-11-08 22:24:53 +00001855 FLBR.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001856 else {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001857 MethodOverloadListRecord MOLR(Methods);
1858 TypeIndex MethodList = TypeTable.writeKnownType(MOLR);
1859 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
1860 FLBR.writeMemberType(OMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001861 }
1862 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001863
1864 // Create nested classes.
1865 for (const DICompositeType *Nested : Info.NestedClasses) {
1866 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner4efa0a42016-11-08 22:24:53 +00001867 FLBR.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00001868 MemberCount++;
1869 }
1870
Zachary Turner7f97c362017-05-25 21:15:37 +00001871 TypeIndex FieldTI = FLBR.end(true);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001872 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Adrian McCarthy820ca542016-07-06 19:49:51 +00001873 !Info.NestedClasses.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00001874}
1875
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001876TypeIndex CodeViewDebug::getVBPTypeIndex() {
1877 if (!VBPType.getIndex()) {
1878 // Make a 'const int *' type.
1879 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001880 TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001881
1882 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1883 : PointerKind::Near32;
1884 PointerMode PM = PointerMode::Pointer;
1885 PointerOptions PO = PointerOptions::None;
1886 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1887
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001888 VBPType = TypeTable.writeKnownType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001889 }
1890
1891 return VBPType;
1892}
1893
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001894TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001895 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001896 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001897
1898 // The null DIType is the void type. Don't try to hash it.
1899 if (!Ty)
1900 return TypeIndex::Void();
1901
Reid Klecknera8d57402016-06-03 15:58:20 +00001902 // Check if we've already translated this type. Don't try to do a
1903 // get-or-create style insertion that caches the hash lookup across the
1904 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001905 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001906 if (I != TypeIndices.end())
1907 return I->second;
1908
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001909 TypeLoweringScope S(*this);
1910 TypeIndex TI = lowerType(Ty, ClassTy);
1911 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00001912}
1913
1914TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1915 const DIType *Ty = TypeRef.resolve();
1916
1917 // The null DIType is the void type. Don't try to hash it.
1918 if (!Ty)
1919 return TypeIndex::Void();
1920
1921 // If this is a non-record type, the complete type index is the same as the
1922 // normal type index. Just call getTypeIndex.
1923 switch (Ty->getTag()) {
1924 case dwarf::DW_TAG_class_type:
1925 case dwarf::DW_TAG_structure_type:
1926 case dwarf::DW_TAG_union_type:
1927 break;
1928 default:
1929 return getTypeIndex(Ty);
1930 }
1931
1932 // Check if we've already translated the complete record type. Lowering a
1933 // complete type should never trigger lowering another complete type, so we
1934 // can reuse the hash table lookup result.
1935 const auto *CTy = cast<DICompositeType>(Ty);
1936 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1937 if (!InsertResult.second)
1938 return InsertResult.first->second;
1939
Reid Kleckner643dd832016-06-22 17:15:28 +00001940 TypeLoweringScope S(*this);
1941
Reid Klecknera8d57402016-06-03 15:58:20 +00001942 // Make sure the forward declaration is emitted first. It's unclear if this
1943 // is necessary, but MSVC does it, and we should follow suit until we can show
1944 // otherwise.
1945 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1946
1947 // Just use the forward decl if we don't have complete type info. This might
1948 // happen if the frontend is using modules and expects the complete definition
1949 // to be emitted elsewhere.
1950 if (CTy->isForwardDecl())
1951 return FwdDeclTI;
1952
1953 TypeIndex TI;
1954 switch (CTy->getTag()) {
1955 case dwarf::DW_TAG_class_type:
1956 case dwarf::DW_TAG_structure_type:
1957 TI = lowerCompleteTypeClass(CTy);
1958 break;
1959 case dwarf::DW_TAG_union_type:
1960 TI = lowerCompleteTypeUnion(CTy);
1961 break;
1962 default:
1963 llvm_unreachable("not a record");
1964 }
1965
1966 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001967 return TI;
1968}
1969
Reid Kleckner643dd832016-06-22 17:15:28 +00001970/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00001971/// and do this until fixpoint, as each complete record type typically
1972/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00001973/// many other record types.
1974void CodeViewDebug::emitDeferredCompleteTypes() {
1975 SmallVector<const DICompositeType *, 4> TypesToEmit;
1976 while (!DeferredCompleteTypes.empty()) {
1977 std::swap(DeferredCompleteTypes, TypesToEmit);
1978 for (const DICompositeType *RecordTy : TypesToEmit)
1979 getCompleteTypeIndex(RecordTy);
1980 TypesToEmit.clear();
1981 }
1982}
1983
Reid Kleckner10dd55c2016-06-24 17:55:40 +00001984void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
1985 // Get the sorted list of parameters and emit them first.
1986 SmallVector<const LocalVariable *, 6> Params;
1987 for (const LocalVariable &L : Locals)
1988 if (L.DIVar->isParameter())
1989 Params.push_back(&L);
1990 std::sort(Params.begin(), Params.end(),
1991 [](const LocalVariable *L, const LocalVariable *R) {
1992 return L->DIVar->getArg() < R->DIVar->getArg();
1993 });
1994 for (const LocalVariable *L : Params)
1995 emitLocalVariable(*L);
1996
1997 // Next emit all non-parameters in the order that we found them.
1998 for (const LocalVariable &L : Locals)
1999 if (!L.DIVar->isParameter())
2000 emitLocalVariable(L);
2001}
2002
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002003void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
2004 // LocalSym record, see SymbolRecord.h for more info.
2005 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2006 *LocalEnd = MMI->getContext().createTempSymbol();
2007 OS.AddComment("Record length");
2008 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2009 OS.EmitLabel(LocalBegin);
2010
2011 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00002012 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002013
Zachary Turner63a28462016-05-17 23:50:21 +00002014 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002015 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002016 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002017 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002018 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002019
2020 OS.AddComment("TypeIndex");
Reid Klecknera8d57402016-06-03 15:58:20 +00002021 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002022 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002023 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002024 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002025 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002026 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002027 OS.EmitLabel(LocalEnd);
2028
Reid Kleckner876330d2016-02-12 21:48:30 +00002029 // Calculate the on disk prefix of the appropriate def range record. The
2030 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2031 // should be big enough to hold all forms without memory allocation.
2032 SmallString<20> BytePrefix;
2033 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2034 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002035 if (DefRange.InMemory) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002036 uint16_t RegRelFlags = 0;
2037 if (DefRange.IsSubfield) {
2038 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2039 (DefRange.StructOffset
2040 << DefRangeRegisterRelSym::OffsetInParentShift);
2041 }
Zachary Turner46225b12016-12-16 22:48:14 +00002042 DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
2043 Sym.Hdr.Register = DefRange.CVRegister;
2044 Sym.Hdr.Flags = RegRelFlags;
2045 Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +00002046 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00002047 BytePrefix +=
2048 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00002049 BytePrefix +=
Zachary Turner46225b12016-12-16 22:48:14 +00002050 StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
Reid Kleckner876330d2016-02-12 21:48:30 +00002051 } else {
2052 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002053 if (DefRange.IsSubfield) {
2054 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002055 DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
2056 Sym.Hdr.Register = DefRange.CVRegister;
2057 Sym.Hdr.MayHaveNoName = 0;
2058 Sym.Hdr.OffsetInParent = DefRange.StructOffset;
2059
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002060 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2061 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2062 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002063 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2064 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002065 } else {
2066 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002067 DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
2068 Sym.Hdr.Register = DefRange.CVRegister;
2069 Sym.Hdr.MayHaveNoName = 0;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002070 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2071 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2072 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002073 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2074 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002075 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002076 }
2077 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2078 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002079}
2080
David Blaikieb2fbb4b2017-02-16 18:48:33 +00002081void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002082 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00002083 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002084 assert(CurFn == &FnDebugInfo[GV]);
2085
Pete Cooperadebb932016-03-11 02:14:16 +00002086 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002087
Reid Kleckner2214ed82016-01-29 00:49:42 +00002088 // Don't emit anything if we don't have any line tables.
2089 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002090 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002091 CurFn = nullptr;
2092 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002093 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002094
2095 CurFn->End = Asm->getFunctionEnd();
2096
Craig Topper353eda42014-04-24 06:44:33 +00002097 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002098}
2099
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002100void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002101 DebugHandlerBase::beginInstruction(MI);
2102
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002103 // Ignore DBG_VALUE locations and function prologue.
David Majnemer67f684e2016-07-28 05:03:22 +00002104 if (!Asm || !CurFn || MI->isDebugValue() ||
2105 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002106 return;
2107 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00002108 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002109 return;
2110 maybeRecordLocation(DL, Asm->MF);
2111}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002112
Zachary Turner8c099fe2017-05-30 16:36:15 +00002113MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002114 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2115 *EndLabel = MMI->getContext().createTempSymbol();
2116 OS.EmitIntValue(unsigned(Kind), 4);
2117 OS.AddComment("Subsection size");
2118 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2119 OS.EmitLabel(BeginLabel);
2120 return EndLabel;
2121}
2122
2123void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2124 OS.EmitLabel(EndLabel);
2125 // Every subsection must be aligned to a 4-byte boundary.
2126 OS.EmitValueToAlignment(4);
2127}
2128
David Majnemer3128b102016-06-15 18:00:01 +00002129void CodeViewDebug::emitDebugInfoForUDTs(
2130 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
2131 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
2132 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2133 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2134 OS.AddComment("Record length");
2135 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2136 OS.EmitLabel(UDTRecordBegin);
2137
2138 OS.AddComment("Record kind: S_UDT");
2139 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2140
2141 OS.AddComment("Type");
2142 OS.EmitIntValue(UDT.second.getIndex(), 4);
2143
2144 emitNullTerminatedSymbolName(OS, UDT.first);
2145 OS.EmitLabel(UDTRecordEnd);
2146 }
2147}
2148
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002149void CodeViewDebug::emitDebugInfoForGlobals() {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002150 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2151 GlobalMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002152 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002153 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2154 GV.getDebugInfo(GVEs);
2155 for (const auto *GVE : GVEs)
2156 GlobalMap[GVE] = &GV;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002157 }
2158
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002159 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2160 for (const MDNode *Node : CUs->operands()) {
2161 const auto *CU = cast<DICompileUnit>(Node);
2162
2163 // First, emit all globals that are not in a comdat in a single symbol
2164 // substream. MSVC doesn't like it if the substream is empty, so only open
2165 // it if we have at least one global to emit.
2166 switchToDebugSectionForSymbol(nullptr);
2167 MCSymbol *EndLabel = nullptr;
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002168 for (const auto *GVE : CU->getGlobalVariables()) {
2169 if (const auto *GV = GlobalMap.lookup(GVE))
David Majnemer577be0f2016-06-15 00:19:52 +00002170 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002171 if (!EndLabel) {
2172 OS.AddComment("Symbol subsection for globals");
Zachary Turner8c099fe2017-05-30 16:36:15 +00002173 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002174 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002175 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2176 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002177 }
2178 }
2179 if (EndLabel)
2180 endCVSubsection(EndLabel);
2181
2182 // Second, emit each global that is in a comdat into its own .debug$S
2183 // section along with its own symbol substream.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002184 for (const auto *GVE : CU->getGlobalVariables()) {
2185 if (const auto *GV = GlobalMap.lookup(GVE)) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002186 if (GV->hasComdat()) {
2187 MCSymbol *GVSym = Asm->getSymbol(GV);
2188 OS.AddComment("Symbol subsection for " +
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00002189 Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002190 switchToDebugSectionForSymbol(GVSym);
Zachary Turner8c099fe2017-05-30 16:36:15 +00002191 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002192 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2193 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002194 endCVSubsection(EndLabel);
2195 }
2196 }
2197 }
2198 }
2199}
2200
Hans Wennborgb510b452016-06-23 16:33:53 +00002201void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2202 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2203 for (const MDNode *Node : CUs->operands()) {
2204 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2205 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2206 getTypeIndex(RT);
2207 // FIXME: Add to global/local DTU list.
2208 }
2209 }
2210 }
2211}
2212
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002213void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002214 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002215 MCSymbol *GVSym) {
2216 // DataSym record, see SymbolRecord.h for more info.
2217 // FIXME: Thread local data, etc
2218 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2219 *DataEnd = MMI->getContext().createTempSymbol();
2220 OS.AddComment("Record length");
2221 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2222 OS.EmitLabel(DataBegin);
David Majnemer7abd2692016-07-06 21:07:47 +00002223 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002224 if (GV->isThreadLocal()) {
2225 OS.AddComment("Record kind: S_LTHREAD32");
2226 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2227 } else {
2228 OS.AddComment("Record kind: S_LDATA32");
2229 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2230 }
David Majnemer7abd2692016-07-06 21:07:47 +00002231 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002232 if (GV->isThreadLocal()) {
2233 OS.AddComment("Record kind: S_GTHREAD32");
2234 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2235 } else {
2236 OS.AddComment("Record kind: S_GDATA32");
2237 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2238 }
David Majnemer7abd2692016-07-06 21:07:47 +00002239 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002240 OS.AddComment("Type");
2241 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2242 OS.AddComment("DataOffset");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00002243 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002244 OS.AddComment("Segment");
2245 OS.EmitCOFFSectionIndex(GVSym);
2246 OS.AddComment("Name");
2247 emitNullTerminatedSymbolName(OS, DIGV->getName());
2248 OS.EmitLabel(DataEnd);
2249}