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