blob: 760833dba0c50d4d5e9022f019e55fed8d6128c1 [file] [log] [blame]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001//===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
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"
Adrian Prantl032d2382017-08-01 21:45:24 +000015#include "DwarfExpression.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000016#include "llvm/ADT/APSInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/DenseSet.h"
20#include "llvm/ADT/MapVector.h"
21#include "llvm/ADT/None.h"
22#include "llvm/ADT/Optional.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000023#include "llvm/ADT/STLExtras.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000024#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/SmallVector.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000026#include "llvm/ADT/StringRef.h"
Reid Kleckner156a7232016-06-22 18:31:14 +000027#include "llvm/ADT/TinyPtrVector.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000028#include "llvm/ADT/Triple.h"
29#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000030#include "llvm/BinaryFormat/COFF.h"
31#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000032#include "llvm/CodeGen/AsmPrinter.h"
33#include "llvm/CodeGen/LexicalScopes.h"
34#include "llvm/CodeGen/MachineFunction.h"
35#include "llvm/CodeGen/MachineInstr.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineOperand.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000038#include "llvm/CodeGen/TargetFrameLowering.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000039#include "llvm/CodeGen/TargetRegisterInfo.h"
40#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000041#include "llvm/Config/llvm-config.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000042#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000043#include "llvm/DebugInfo/CodeView/CodeView.h"
Zachary Turner6900de12017-11-28 18:33:17 +000044#include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
Zachary Turner8c099fe2017-05-30 16:36:15 +000045#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000046#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000047#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000048#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000049#include "llvm/DebugInfo/CodeView/TypeIndex.h"
50#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000051#include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000052#include "llvm/IR/Constants.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000053#include "llvm/IR/DataLayout.h"
54#include "llvm/IR/DebugInfoMetadata.h"
55#include "llvm/IR/DebugLoc.h"
56#include "llvm/IR/Function.h"
57#include "llvm/IR/GlobalValue.h"
58#include "llvm/IR/GlobalVariable.h"
59#include "llvm/IR/Metadata.h"
60#include "llvm/IR/Module.h"
Reid Kleckner46cb48c2016-07-27 16:03:57 +000061#include "llvm/MC/MCAsmInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000062#include "llvm/MC/MCContext.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000063#include "llvm/MC/MCSectionCOFF.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000064#include "llvm/MC/MCStreamer.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000065#include "llvm/MC/MCSymbol.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000066#include "llvm/Support/BinaryByteStream.h"
67#include "llvm/Support/BinaryStreamReader.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000068#include "llvm/Support/Casting.h"
Zachary Turner048f8f92017-12-13 22:33:58 +000069#include "llvm/Support/CommandLine.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000070#include "llvm/Support/Compiler.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000071#include "llvm/Support/Endian.h"
72#include "llvm/Support/Error.h"
73#include "llvm/Support/ErrorHandling.h"
Zachary Turner048f8f92017-12-13 22:33:58 +000074#include "llvm/Support/FormatVariadic.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000075#include "llvm/Support/SMLoc.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000076#include "llvm/Support/ScopedPrinter.h"
David Blaikie6054e652018-03-23 23:58:19 +000077#include "llvm/Target/TargetLoweringObjectFile.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000078#include "llvm/Target/TargetMachine.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000079#include <algorithm>
80#include <cassert>
81#include <cctype>
82#include <cstddef>
83#include <cstdint>
84#include <iterator>
85#include <limits>
86#include <string>
87#include <utility>
88#include <vector>
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000089
Reid Klecknerf9c275f2016-02-10 20:55:49 +000090using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000091using namespace llvm::codeview;
92
Zachary Turner048f8f92017-12-13 22:33:58 +000093static cl::opt<bool> EmitDebugGlobalHashes("emit-codeview-ghash-section",
94 cl::ReallyHidden, cl::init(false));
95
Reid Klecknerf9c275f2016-02-10 20:55:49 +000096CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
Eugene Zelenkofb69e662017-06-06 22:22:41 +000097 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +000098 // If module doesn't have named metadata anchors or COFF debug section
99 // is not available, skip any debug info related stuff.
100 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
101 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
102 Asm = nullptr;
103 return;
104 }
105
106 // Tell MMI that we have debug info.
107 MMI->setDebugInfoAvailability(true);
108}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000109
Reid Kleckner9533af42016-01-16 00:09:09 +0000110StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
111 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000112 if (!Filepath.empty())
113 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000114
Reid Kleckner9533af42016-01-16 00:09:09 +0000115 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
116
Peter Collingbournecb8a6662018-04-11 18:24:03 +0000117 // If this is a Unix-style path, just use it as is. Don't try to canonicalize
118 // it textually because one of the path components could be a symlink.
119 if (!Dir.empty() && Dir[0] == '/') {
120 Filepath = Dir;
121 if (Dir.back() != '/')
122 Filepath += '/';
123 Filepath += Filename;
124 return Filepath;
125 }
126
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000127 // Clang emits directory and relative filename info into the IR, but CodeView
128 // operates on full paths. We could change Clang to emit full paths too, but
129 // that would increase the IR size and probably not needed for other users.
130 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000131 if (Filename.find(':') == 1)
132 Filepath = Filename;
133 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +0000134 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000135
136 // Canonicalize the path. We have to do it textually because we may no longer
137 // have access the file in the filesystem.
138 // First, replace all slashes with backslashes.
139 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
140
141 // Remove all "\.\" with "\".
142 size_t Cursor = 0;
143 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
144 Filepath.erase(Cursor, 2);
145
146 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
147 // path should be well-formatted, e.g. start with a drive letter, etc.
148 Cursor = 0;
149 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
150 // Something's wrong if the path starts with "\..\", abort.
151 if (Cursor == 0)
152 break;
153
154 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
155 if (PrevSlash == std::string::npos)
156 // Something's wrong, abort.
157 break;
158
159 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
160 // The next ".." might be following the one we've just erased.
161 Cursor = PrevSlash;
162 }
163
164 // Remove all duplicate backslashes.
165 Cursor = 0;
166 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
167 Filepath.erase(Cursor, 1);
168
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000169 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000170}
171
Reid Kleckner2214ed82016-01-29 00:49:42 +0000172unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
Reid Klecknerbc6f52d2017-10-31 21:52:15 +0000173 StringRef FullPath = getFullFilepath(F);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000174 unsigned NextId = FileIdMap.size() + 1;
Reid Klecknerbc6f52d2017-10-31 21:52:15 +0000175 auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
Reid Kleckner2214ed82016-01-29 00:49:42 +0000176 if (Insertion.second) {
177 // We have to compute the full filepath and emit a .cv_file directive.
Scott Linder71603842018-02-12 19:45:54 +0000178 ArrayRef<uint8_t> ChecksumAsBytes;
179 FileChecksumKind CSKind = FileChecksumKind::None;
180 if (F->getChecksum()) {
181 std::string Checksum = fromHex(F->getChecksum()->Value);
182 void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
183 memcpy(CKMem, Checksum.data(), Checksum.size());
184 ChecksumAsBytes = ArrayRef<uint8_t>(
185 reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
186 switch (F->getChecksum()->Kind) {
187 case DIFile::CSK_MD5: CSKind = FileChecksumKind::MD5; break;
188 case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break;
189 }
190 }
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000191 bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
Scott Linder71603842018-02-12 19:45:54 +0000192 static_cast<unsigned>(CSKind));
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000193 (void)Success;
194 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000195 }
196 return Insertion.first->second;
197}
198
Reid Kleckner876330d2016-02-12 21:48:30 +0000199CodeViewDebug::InlineSite &
200CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
201 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000202 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
203 InlineSite *Site = &SiteInsertion.first->second;
204 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000205 unsigned ParentFuncId = CurFn->FuncId;
206 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
207 ParentFuncId =
208 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
209 .SiteFuncId;
210
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000211 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000212 OS.EmitCVInlineSiteIdDirective(
213 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
214 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000215 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000216 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000217 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000218 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000219 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000220}
221
David Majnemer6bdc24e2016-07-01 23:12:45 +0000222static StringRef getPrettyScopeName(const DIScope *Scope) {
223 StringRef ScopeName = Scope->getName();
224 if (!ScopeName.empty())
225 return ScopeName;
226
227 switch (Scope->getTag()) {
228 case dwarf::DW_TAG_enumeration_type:
229 case dwarf::DW_TAG_class_type:
230 case dwarf::DW_TAG_structure_type:
231 case dwarf::DW_TAG_union_type:
232 return "<unnamed-tag>";
233 case dwarf::DW_TAG_namespace:
234 return "`anonymous namespace'";
235 }
236
237 return StringRef();
238}
239
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000240static const DISubprogram *getQualifiedNameComponents(
241 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
242 const DISubprogram *ClosestSubprogram = nullptr;
243 while (Scope != nullptr) {
244 if (ClosestSubprogram == nullptr)
245 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000246 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000247 if (!ScopeName.empty())
248 QualifiedNameComponents.push_back(ScopeName);
249 Scope = Scope->getScope().resolve();
250 }
251 return ClosestSubprogram;
252}
253
254static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
255 StringRef TypeName) {
256 std::string FullyQualifiedName;
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000257 for (StringRef QualifiedNameComponent :
258 llvm::reverse(QualifiedNameComponents)) {
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000259 FullyQualifiedName.append(QualifiedNameComponent);
260 FullyQualifiedName.append("::");
261 }
262 FullyQualifiedName.append(TypeName);
263 return FullyQualifiedName;
264}
265
266static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
267 SmallVector<StringRef, 5> QualifiedNameComponents;
268 getQualifiedNameComponents(Scope, QualifiedNameComponents);
269 return getQualifiedName(QualifiedNameComponents, Name);
270}
271
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000272struct CodeViewDebug::TypeLoweringScope {
273 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
274 ~TypeLoweringScope() {
275 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
276 // inner TypeLoweringScopes don't attempt to emit deferred types.
277 if (CVD.TypeEmissionLevel == 1)
278 CVD.emitDeferredCompleteTypes();
279 --CVD.TypeEmissionLevel;
280 }
281 CodeViewDebug &CVD;
282};
283
David Majnemer6bdc24e2016-07-01 23:12:45 +0000284static std::string getFullyQualifiedName(const DIScope *Ty) {
285 const DIScope *Scope = Ty->getScope().resolve();
286 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
287}
288
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000289TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
290 // No scope means global scope and that uses the zero index.
291 if (!Scope || isa<DIFile>(Scope))
292 return TypeIndex();
293
294 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
295
296 // Check if we've already translated this scope.
297 auto I = TypeIndices.find({Scope, nullptr});
298 if (I != TypeIndices.end())
299 return I->second;
300
301 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000302 std::string ScopeName = getFullyQualifiedName(Scope);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000303 StringIdRecord SID(TypeIndex(), ScopeName);
Zachary Turner6900de12017-11-28 18:33:17 +0000304 auto TI = TypeTable.writeLeafType(SID);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000305 return recordTypeIndexForDINode(Scope, TI);
306}
307
David Majnemer75c3ebf2016-06-02 17:13:53 +0000308TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000309 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000310
David Majnemer75c3ebf2016-06-02 17:13:53 +0000311 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000312 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000313 if (I != TypeIndices.end())
314 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000315
Reid Klecknerac945e22016-06-17 16:11:20 +0000316 // The display name includes function template arguments. Drop them to match
317 // MSVC.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000318 StringRef DisplayName = SP->getName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000319
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000320 const DIScope *Scope = SP->getScope().resolve();
321 TypeIndex TI;
322 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
323 // If the scope is a DICompositeType, then this must be a method. Member
324 // function types take some special handling, and require access to the
325 // subprogram.
326 TypeIndex ClassType = getTypeIndex(Class);
327 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
328 DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000329 TI = TypeTable.writeLeafType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000330 } else {
331 // Otherwise, this must be a free function.
332 TypeIndex ParentScope = getScopeIndex(Scope);
333 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000334 TI = TypeTable.writeLeafType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000335 }
336
337 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000338}
339
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000340TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
341 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000342 // Always use the method declaration as the key for the function type. The
343 // method declaration contains the this adjustment.
344 if (SP->getDeclaration())
345 SP = SP->getDeclaration();
346 assert(!SP->getDeclaration() && "should use declaration as key");
347
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000348 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
349 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000350 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000351 if (I != TypeIndices.end())
352 return I->second;
353
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000354 // Make sure complete type info for the class is emitted *after* the member
355 // function type, as the complete class type is likely to reference this
356 // member function type.
357 TypeLoweringScope S(*this);
Adrian McCarthyd91bf392017-09-13 20:53:55 +0000358 const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
359 TypeIndex TI = lowerTypeMemberFunction(
360 SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000361 return recordTypeIndexForDINode(SP, TI, Class);
362}
363
Amjad Aboudacee5682016-07-12 12:06:34 +0000364TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
365 TypeIndex TI,
366 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000367 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000368 (void)InsertResult;
369 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000370 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000371}
372
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000373unsigned CodeViewDebug::getPointerSizeInBytes() {
374 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
375}
376
Reid Kleckner876330d2016-02-12 21:48:30 +0000377void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
Reid Kleckner5a791ee2018-03-15 21:24:04 +0000378 const LexicalScope *LS) {
379 if (const DILocation *InlinedAt = LS->getInlinedAt()) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000380 // This variable was inlined. Associate it with the InlineSite.
381 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
382 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
383 Site.InlinedLocals.emplace_back(Var);
384 } else {
Reid Kleckner5a791ee2018-03-15 21:24:04 +0000385 // This variable goes into the corresponding lexical scope.
386 ScopeVariables[LS].emplace_back(Var);
Reid Kleckner876330d2016-02-12 21:48:30 +0000387 }
388}
389
Reid Kleckner829365a2016-02-11 19:41:47 +0000390static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
391 const DILocation *Loc) {
392 auto B = Locs.begin(), E = Locs.end();
393 if (std::find(B, E, Loc) == E)
394 Locs.push_back(Loc);
395}
396
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000397void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000398 const MachineFunction *MF) {
399 // Skip this instruction if it has the same location as the previous one.
Reid Kleckner45a74622017-06-30 21:33:44 +0000400 if (!DL || DL == PrevInstLoc)
Reid Kleckner9533af42016-01-16 00:09:09 +0000401 return;
402
403 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000404 if (!Scope)
405 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000406
David Majnemerc3340db2016-01-13 01:05:23 +0000407 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000408 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
409 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
410 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000411 return;
412
Reid Kleckner2214ed82016-01-29 00:49:42 +0000413 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
414 if (CI.getStartColumn() != DL.getCol())
415 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000416
Reid Kleckner2214ed82016-01-29 00:49:42 +0000417 if (!CurFn->HaveLineInfo)
418 CurFn->HaveLineInfo = true;
419 unsigned FileId = 0;
Reid Kleckner45a74622017-06-30 21:33:44 +0000420 if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
Reid Kleckner2214ed82016-01-29 00:49:42 +0000421 FileId = CurFn->LastFileId;
422 else
423 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
Reid Kleckner45a74622017-06-30 21:33:44 +0000424 PrevInstLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000425
426 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000427 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000428 const DILocation *Loc = DL.get();
429
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000430 // If this location was actually inlined from somewhere else, give it the ID
431 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000432 FuncId =
433 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000434
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000435 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000436 bool FirstLoc = true;
437 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000438 InlineSite &Site =
439 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000440 if (!FirstLoc)
441 addLocIfNotPresent(Site.ChildSites, Loc);
442 FirstLoc = false;
443 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000444 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000445 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000446 }
447
Reid Klecknerdac21b42016-02-03 21:15:48 +0000448 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000449 /*PrologueEnd=*/false, /*IsStmt=*/false,
450 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000451}
452
Reid Kleckner5d122f82016-05-25 23:16:12 +0000453void CodeViewDebug::emitCodeViewMagicVersion() {
454 OS.EmitValueToAlignment(4);
455 OS.AddComment("Debug section magic");
456 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
457}
458
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000459void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000460 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000461 return;
462
463 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000464
465 // The COFF .debug$S section consists of several subsections, each starting
466 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
467 // of the payload followed by the payload itself. The subsections are 4-byte
468 // aligned.
469
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000470 // Use the generic .debug$S section, and make a subsection for all the inlined
471 // subprograms.
472 switchToDebugSectionForSymbol(nullptr);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000473
Zachary Turner8c099fe2017-05-30 16:36:15 +0000474 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000475 emitCompilerInformation();
476 endCVSubsection(CompilerInfo);
477
Reid Kleckner5d122f82016-05-25 23:16:12 +0000478 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000479
Reid Kleckner2214ed82016-01-29 00:49:42 +0000480 // Emit per-function debug information.
481 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000482 if (!P.first->isDeclarationForLinker())
Reid Kleckner55baeef2018-03-15 21:12:21 +0000483 emitDebugInfoForFunction(P.first, *P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000484
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000485 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000486 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000487 emitDebugInfoForGlobals();
488
Hans Wennborgb510b452016-06-23 16:33:53 +0000489 // Emit retained types.
490 emitDebugInfoForRetainedTypes();
491
Reid Kleckner5d122f82016-05-25 23:16:12 +0000492 // Switch back to the generic .debug$S section after potentially processing
493 // comdat symbol sections.
494 switchToDebugSectionForSymbol(nullptr);
495
David Majnemer3128b102016-06-15 18:00:01 +0000496 // Emit UDT records for any types used by global variables.
497 if (!GlobalUDTs.empty()) {
Zachary Turner8c099fe2017-05-30 16:36:15 +0000498 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
David Majnemer3128b102016-06-15 18:00:01 +0000499 emitDebugInfoForUDTs(GlobalUDTs);
500 endCVSubsection(SymbolsEnd);
501 }
502
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000503 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000504 OS.AddComment("File index to string table offset subsection");
505 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000506
507 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000508 OS.AddComment("String table");
509 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000510
Zachary Turner048f8f92017-12-13 22:33:58 +0000511 // Emit type information and hashes last, so that any types we translate while
512 // emitting function info are included.
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000513 emitTypeInformation();
514
Zachary Turner048f8f92017-12-13 22:33:58 +0000515 if (EmitDebugGlobalHashes)
516 emitTypeGlobalHashes();
517
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000518 clear();
519}
520
Brock Wyma19e17b32018-02-11 21:26:46 +0000521static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
522 unsigned MaxFixedRecordLength = 0xF00) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000523 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
524 // after a fixed length portion of the record. The fixed length portion should
525 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
526 // overall record size is less than the maximum allowed.
Reid Klecknerbb96df62016-10-05 22:36:07 +0000527 SmallString<32> NullTerminatedString(
528 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
David Majnemerb9456a52016-03-14 05:15:09 +0000529 NullTerminatedString.push_back('\0');
530 OS.EmitBytes(NullTerminatedString);
531}
532
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000533void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000534 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000535 return;
536
Alexandre Ganead9e96742018-04-09 20:17:56 +0000537 // Start the .debug$T or .debug$P section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000538 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000539 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000540
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000541 SmallString<8> CommentPrefix;
542 if (OS.isVerboseAsm()) {
543 CommentPrefix += '\t';
544 CommentPrefix += Asm->MAI->getCommentString();
545 CommentPrefix += ' ';
546 }
547
Zachary Turner526f4f22017-05-19 19:26:58 +0000548 TypeTableCollection Table(TypeTable.records());
549 Optional<TypeIndex> B = Table.getFirst();
550 while (B) {
551 // This will fail if the record data is invalid.
552 CVType Record = Table.getType(*B);
553
Zachary Turner4efa0a42016-11-08 22:24:53 +0000554 if (OS.isVerboseAsm()) {
555 // Emit a block comment describing the type record for readability.
556 SmallString<512> CommentBlock;
557 raw_svector_ostream CommentOS(CommentBlock);
558 ScopedPrinter SP(CommentOS);
559 SP.setPrefix(CommentPrefix);
Zachary Turner526f4f22017-05-19 19:26:58 +0000560 TypeDumpVisitor TDV(Table, &SP, false);
561
562 Error E = codeview::visitTypeRecord(Record, *B, TDV);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000563 if (E) {
564 logAllUnhandledErrors(std::move(E), errs(), "error: ");
565 llvm_unreachable("produced malformed type record");
566 }
567 // emitRawComment will insert its own tab and comment string before
568 // the first line, so strip off our first one. It also prints its own
569 // newline.
570 OS.emitRawComment(
571 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Zachary Turner4efa0a42016-11-08 22:24:53 +0000572 }
Zachary Turner526f4f22017-05-19 19:26:58 +0000573 OS.EmitBinaryData(Record.str_data());
574 B = Table.getNext(*B);
575 }
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000576}
577
Zachary Turner048f8f92017-12-13 22:33:58 +0000578void CodeViewDebug::emitTypeGlobalHashes() {
579 if (TypeTable.empty())
580 return;
581
582 // Start the .debug$H section with the version and hash algorithm, currently
583 // hardcoded to version 0, SHA1.
584 OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
585
586 OS.EmitValueToAlignment(4);
587 OS.AddComment("Magic");
588 OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
589 OS.AddComment("Section Version");
590 OS.EmitIntValue(0, 2);
591 OS.AddComment("Hash Algorithm");
Zachary Turnerc7626662018-05-17 22:55:15 +0000592 OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1_8), 2);
Zachary Turner048f8f92017-12-13 22:33:58 +0000593
594 TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
595 for (const auto &GHR : TypeTable.hashes()) {
596 if (OS.isVerboseAsm()) {
597 // Emit an EOL-comment describing which TypeIndex this hash corresponds
598 // to, as well as the stringified SHA1 hash.
599 SmallString<32> Comment;
600 raw_svector_ostream CommentOS(Comment);
601 CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
602 OS.AddComment(Comment);
603 ++TI;
604 }
Zachary Turnerc7626662018-05-17 22:55:15 +0000605 assert(GHR.Hash.size() == 8);
Zachary Turner048f8f92017-12-13 22:33:58 +0000606 StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
607 GHR.Hash.size());
608 OS.EmitBinaryData(S);
609 }
610}
611
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000612static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
613 switch (DWLang) {
614 case dwarf::DW_LANG_C:
615 case dwarf::DW_LANG_C89:
616 case dwarf::DW_LANG_C99:
617 case dwarf::DW_LANG_C11:
618 case dwarf::DW_LANG_ObjC:
619 return SourceLanguage::C;
620 case dwarf::DW_LANG_C_plus_plus:
621 case dwarf::DW_LANG_C_plus_plus_03:
622 case dwarf::DW_LANG_C_plus_plus_11:
623 case dwarf::DW_LANG_C_plus_plus_14:
624 return SourceLanguage::Cpp;
625 case dwarf::DW_LANG_Fortran77:
626 case dwarf::DW_LANG_Fortran90:
627 case dwarf::DW_LANG_Fortran03:
628 case dwarf::DW_LANG_Fortran08:
629 return SourceLanguage::Fortran;
630 case dwarf::DW_LANG_Pascal83:
631 return SourceLanguage::Pascal;
632 case dwarf::DW_LANG_Cobol74:
633 case dwarf::DW_LANG_Cobol85:
634 return SourceLanguage::Cobol;
635 case dwarf::DW_LANG_Java:
636 return SourceLanguage::Java;
Reid Kleckner898ddf62017-07-24 16:16:42 +0000637 case dwarf::DW_LANG_D:
638 return SourceLanguage::D;
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000639 default:
640 // There's no CodeView representation for this language, and CV doesn't
641 // have an "unknown" option for the language field, so we'll use MASM,
642 // as it's very low level.
643 return SourceLanguage::Masm;
644 }
645}
646
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000647namespace {
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000648struct Version {
649 int Part[4];
650};
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000651} // end anonymous namespace
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000652
653// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
654// the version number.
655static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000656 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000657 int N = 0;
658 for (const char C : Name) {
659 if (isdigit(C)) {
660 V.Part[N] *= 10;
661 V.Part[N] += C - '0';
662 } else if (C == '.') {
663 ++N;
664 if (N >= 4)
665 return V;
666 } else if (N > 0)
667 return V;
668 }
669 return V;
670}
671
672static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
673 switch (Type) {
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000674 case Triple::ArchType::x86:
675 return CPUType::Pentium3;
676 case Triple::ArchType::x86_64:
677 return CPUType::X64;
678 case Triple::ArchType::thumb:
679 return CPUType::Thumb;
680 case Triple::ArchType::aarch64:
681 return CPUType::ARM64;
682 default:
683 report_fatal_error("target architecture doesn't map to a CodeView CPUType");
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000684 }
685}
686
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000687void CodeViewDebug::emitCompilerInformation() {
688 MCContext &Context = MMI->getContext();
689 MCSymbol *CompilerBegin = Context.createTempSymbol(),
690 *CompilerEnd = Context.createTempSymbol();
691 OS.AddComment("Record length");
692 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
693 OS.EmitLabel(CompilerBegin);
694 OS.AddComment("Record kind: S_COMPILE3");
695 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
696 uint32_t Flags = 0;
697
698 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
699 const MDNode *Node = *CUs->operands().begin();
700 const auto *CU = cast<DICompileUnit>(Node);
701
702 // The low byte of the flags indicates the source language.
703 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
704 // TODO: Figure out which other flags need to be set.
705
706 OS.AddComment("Flags and language");
707 OS.EmitIntValue(Flags, 4);
708
709 OS.AddComment("CPUType");
710 CPUType CPU =
711 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
712 OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
713
714 StringRef CompilerVersion = CU->getProducer();
715 Version FrontVer = parseVersion(CompilerVersion);
716 OS.AddComment("Frontend version");
717 for (int N = 0; N < 4; ++N)
718 OS.EmitIntValue(FrontVer.Part[N], 2);
719
720 // Some Microsoft tools, like Binscope, expect a backend version number of at
721 // least 8.something, so we'll coerce the LLVM version into a form that
722 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000723 int Major = 1000 * LLVM_VERSION_MAJOR +
724 10 * LLVM_VERSION_MINOR +
725 LLVM_VERSION_PATCH;
726 // Clamp it for builds that use unusually large version numbers.
727 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
728 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000729 OS.AddComment("Backend version");
730 for (int N = 0; N < 4; ++N)
731 OS.EmitIntValue(BackVer.Part[N], 2);
732
733 OS.AddComment("Null-terminated compiler version string");
734 emitNullTerminatedSymbolName(OS, CompilerVersion);
735
736 OS.EmitLabel(CompilerEnd);
737}
738
Reid Kleckner5d122f82016-05-25 23:16:12 +0000739void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000740 if (InlinedSubprograms.empty())
741 return;
742
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000743 OS.AddComment("Inlinee lines subsection");
Zachary Turner8c099fe2017-05-30 16:36:15 +0000744 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000745
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000746 // We emit the checksum info for files. This is used by debuggers to
747 // determine if a pdb matches the source before loading it. Visual Studio,
748 // for instance, will display a warning that the breakpoints are not valid if
749 // the pdb does not match the source.
David Majnemer30579ec2016-02-02 23:18:23 +0000750 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000751 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
752
753 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000754 assert(TypeIndices.count({SP, nullptr}));
755 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000756
David Majnemer30579ec2016-02-02 23:18:23 +0000757 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000758 unsigned FileId = maybeRecordFile(SP->getFile());
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000759 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000760 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000761 OS.AddBlankLine();
David Majnemer30579ec2016-02-02 23:18:23 +0000762 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000763 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000764 OS.AddComment("Offset into filechecksum table");
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000765 OS.EmitCVFileChecksumOffsetDirective(FileId);
David Majnemer30579ec2016-02-02 23:18:23 +0000766 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000767 OS.EmitIntValue(SP->getLine(), 4);
768 }
769
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000770 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000771}
772
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000773void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
774 const DILocation *InlinedAt,
775 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000776 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
777 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000778
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000779 assert(TypeIndices.count({Site.Inlinee, nullptr}));
780 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000781
782 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000783 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000784 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000785 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000786 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000787 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000788
Reid Klecknerdac21b42016-02-03 21:15:48 +0000789 OS.AddComment("PtrParent");
790 OS.EmitIntValue(0, 4);
791 OS.AddComment("PtrEnd");
792 OS.EmitIntValue(0, 4);
793 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000794 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000795
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000796 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
797 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000798
799 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000800 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000801
802 OS.EmitLabel(InlineEnd);
803
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000804 emitLocalVariableList(Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000805
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000806 // Recurse on child inlined call sites before closing the scope.
807 for (const DILocation *ChildSite : Site.ChildSites) {
808 auto I = FI.InlineSites.find(ChildSite);
809 assert(I != FI.InlineSites.end() &&
810 "child site not in function inline site map");
811 emitInlinedCallSite(FI, ChildSite, I->second);
812 }
813
814 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000815 OS.AddComment("Record length");
816 OS.EmitIntValue(2, 2); // RecordLength
817 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000818 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000819}
820
Reid Kleckner5d122f82016-05-25 23:16:12 +0000821void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
822 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
823 // comdat key. A section may be comdat because of -ffunction-sections or
824 // because it is comdat in the IR.
825 MCSectionCOFF *GVSec =
826 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
827 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
828
829 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
830 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
831 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
832
833 OS.SwitchSection(DebugSec);
834
835 // Emit the magic version number if this is the first time we've switched to
836 // this section.
837 if (ComdatDebugSections.insert(DebugSec).second)
838 emitCodeViewMagicVersion();
839}
840
Brock Wyma94ece8f2018-04-16 16:53:57 +0000841// Emit an S_THUNK32/S_END symbol pair for a thunk routine.
842// The only supported thunk ordinal is currently the standard type.
843void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
844 FunctionInfo &FI,
845 const MCSymbol *Fn) {
846 std::string FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
847 const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
848
849 OS.AddComment("Symbol subsection for " + Twine(FuncName));
850 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
851
852 // Emit S_THUNK32
853 MCSymbol *ThunkRecordBegin = MMI->getContext().createTempSymbol(),
854 *ThunkRecordEnd = MMI->getContext().createTempSymbol();
855 OS.AddComment("Record length");
856 OS.emitAbsoluteSymbolDiff(ThunkRecordEnd, ThunkRecordBegin, 2);
857 OS.EmitLabel(ThunkRecordBegin);
858 OS.AddComment("Record kind: S_THUNK32");
859 OS.EmitIntValue(unsigned(SymbolKind::S_THUNK32), 2);
860 OS.AddComment("PtrParent");
861 OS.EmitIntValue(0, 4);
862 OS.AddComment("PtrEnd");
863 OS.EmitIntValue(0, 4);
864 OS.AddComment("PtrNext");
865 OS.EmitIntValue(0, 4);
866 OS.AddComment("Thunk section relative address");
867 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
868 OS.AddComment("Thunk section index");
869 OS.EmitCOFFSectionIndex(Fn);
870 OS.AddComment("Code size");
871 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
872 OS.AddComment("Ordinal");
873 OS.EmitIntValue(unsigned(ordinal), 1);
874 OS.AddComment("Function name");
875 emitNullTerminatedSymbolName(OS, FuncName);
876 // Additional fields specific to the thunk ordinal would go here.
877 OS.EmitLabel(ThunkRecordEnd);
878
879 // Local variables/inlined routines are purposely omitted here. The point of
880 // marking this as a thunk is so Visual Studio will NOT stop in this routine.
881
882 // Emit S_PROC_ID_END
883 const unsigned RecordLengthForSymbolEnd = 2;
884 OS.AddComment("Record length");
885 OS.EmitIntValue(RecordLengthForSymbolEnd, 2);
886 OS.AddComment("Record kind: S_PROC_ID_END");
887 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
888
889 endCVSubsection(SymbolsEnd);
890}
891
Reid Kleckner2214ed82016-01-29 00:49:42 +0000892void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
893 FunctionInfo &FI) {
Brock Wyma31cc1eb2018-01-30 13:16:50 +0000894 // For each function there is a separate subsection which holds the PC to
895 // file:line table.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000896 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000897 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000898
Reid Kleckner5d122f82016-05-25 23:16:12 +0000899 // Switch to the to a comdat section, if appropriate.
900 switchToDebugSectionForSymbol(Fn);
901
Reid Klecknerac945e22016-06-17 16:11:20 +0000902 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000903 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000904 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000905 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000906
Brock Wyma94ece8f2018-04-16 16:53:57 +0000907 if (SP->isThunk()) {
908 emitDebugInfoForThunk(GV, FI, Fn);
909 return;
910 }
911
Reid Klecknerac945e22016-06-17 16:11:20 +0000912 // If we have a display name, build the fully qualified name by walking the
913 // chain of scopes.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000914 if (!SP->getName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000915 FuncName =
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000916 getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000917
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000918 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000919 if (FuncName.empty())
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +0000920 FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000921
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000922 // Emit FPO data, but only on 32-bit x86. No other platforms use it.
923 if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
924 OS.EmitCVFPOData(Fn);
925
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000926 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000927 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Zachary Turner8c099fe2017-05-30 16:36:15 +0000928 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000929 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000930 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
931 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000932 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000933 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000934 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000935
Reid Kleckner4ad127f2016-09-14 21:49:21 +0000936 if (GV->hasLocalLinkage()) {
937 OS.AddComment("Record kind: S_LPROC32_ID");
938 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
939 } else {
940 OS.AddComment("Record kind: S_GPROC32_ID");
941 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
942 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000943
David Majnemer30579ec2016-02-02 23:18:23 +0000944 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000945 OS.AddComment("PtrParent");
946 OS.EmitIntValue(0, 4);
947 OS.AddComment("PtrEnd");
948 OS.EmitIntValue(0, 4);
949 OS.AddComment("PtrNext");
950 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000951 // This is the important bit that tells the debugger where the function
952 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000953 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000954 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000955 OS.AddComment("Offset after prologue");
956 OS.EmitIntValue(0, 4);
957 OS.AddComment("Offset before epilogue");
958 OS.EmitIntValue(0, 4);
959 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000960 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000961 OS.AddComment("Function section relative address");
Keno Fischerf7d84ee2017-01-02 03:00:19 +0000962 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000963 OS.AddComment("Function section index");
964 OS.EmitCOFFSectionIndex(Fn);
965 OS.AddComment("Flags");
966 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000967 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000968 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000969 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000970 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000971 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000972
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000973 emitLocalVariableList(FI.Locals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +0000974 emitLexicalBlockList(FI.ChildBlocks, FI);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000975
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000976 // Emit inlined call site information. Only emit functions inlined directly
977 // into the parent function. We'll emit the other sites recursively as part
978 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000979 for (const DILocation *InlinedAt : FI.ChildSites) {
980 auto I = FI.InlineSites.find(InlinedAt);
981 assert(I != FI.InlineSites.end() &&
982 "child site not in function inline site map");
983 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000984 }
985
Reid Klecknere33c94f2017-09-05 20:14:58 +0000986 for (auto Annot : FI.Annotations) {
987 MCSymbol *Label = Annot.first;
988 MDTuple *Strs = cast<MDTuple>(Annot.second);
989 MCSymbol *AnnotBegin = MMI->getContext().createTempSymbol(),
990 *AnnotEnd = MMI->getContext().createTempSymbol();
991 OS.AddComment("Record length");
992 OS.emitAbsoluteSymbolDiff(AnnotEnd, AnnotBegin, 2);
993 OS.EmitLabel(AnnotBegin);
994 OS.AddComment("Record kind: S_ANNOTATION");
995 OS.EmitIntValue(SymbolKind::S_ANNOTATION, 2);
996 OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
997 // FIXME: Make sure we don't overflow the max record size.
998 OS.EmitCOFFSectionIndex(Label);
999 OS.EmitIntValue(Strs->getNumOperands(), 2);
1000 for (Metadata *MD : Strs->operands()) {
1001 // MDStrings are null terminated, so we can do EmitBytes and get the
1002 // nice .asciz directive.
1003 StringRef Str = cast<MDString>(MD)->getString();
1004 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1005 OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
1006 }
1007 OS.EmitLabel(AnnotEnd);
1008 }
1009
David Majnemer3128b102016-06-15 18:00:01 +00001010 if (SP != nullptr)
1011 emitDebugInfoForUDTs(LocalUDTs);
1012
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001013 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001014 OS.AddComment("Record length");
1015 OS.EmitIntValue(0x0002, 2);
1016 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +00001017 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001018 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001019 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001020
Reid Kleckner2214ed82016-01-29 00:49:42 +00001021 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001022 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001023}
1024
Reid Kleckner876330d2016-02-12 21:48:30 +00001025CodeViewDebug::LocalVarDefRange
1026CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
1027 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +00001028 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +00001029 DR.DataOffset = Offset;
1030 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00001031 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001032 DR.StructOffset = 0;
1033 DR.CVRegister = CVRegister;
1034 return DR;
1035}
1036
1037CodeViewDebug::LocalVarDefRange
Reid Kleckner2b3e6422016-10-05 21:21:33 +00001038CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
1039 int Offset, bool IsSubfield,
1040 uint16_t StructOffset) {
Reid Kleckner876330d2016-02-12 21:48:30 +00001041 LocalVarDefRange DR;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00001042 DR.InMemory = InMemory;
1043 DR.DataOffset = Offset;
1044 DR.IsSubfield = IsSubfield;
1045 DR.StructOffset = StructOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +00001046 DR.CVRegister = CVRegister;
1047 return DR;
1048}
1049
Matthias Braunef331ef2016-11-30 23:48:50 +00001050void CodeViewDebug::collectVariableInfoFromMFTable(
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001051 DenseSet<InlinedEntity> &Processed) {
Matthias Braunef331ef2016-11-30 23:48:50 +00001052 const MachineFunction &MF = *Asm->MF;
1053 const TargetSubtargetInfo &TSI = MF.getSubtarget();
Reid Kleckner876330d2016-02-12 21:48:30 +00001054 const TargetFrameLowering *TFI = TSI.getFrameLowering();
1055 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1056
Matthias Braunef331ef2016-11-30 23:48:50 +00001057 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001058 if (!VI.Var)
1059 continue;
1060 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1061 "Expected inlined-at fields to agree");
1062
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001063 Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001064 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1065
1066 // If variable scope is not found then skip this variable.
1067 if (!Scope)
1068 continue;
1069
Reid Klecknerb5fced72017-05-09 19:59:29 +00001070 // If the variable has an attached offset expression, extract it.
1071 // FIXME: Try to handle DW_OP_deref as well.
1072 int64_t ExprOffset = 0;
1073 if (VI.Expr)
1074 if (!VI.Expr->extractIfOffset(ExprOffset))
1075 continue;
1076
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001077 // Get the frame register used and the offset.
1078 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001079 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1080 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001081
1082 // Calculate the label ranges.
Reid Klecknerb5fced72017-05-09 19:59:29 +00001083 LocalVarDefRange DefRange =
1084 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001085 for (const InsnRange &Range : Scope->getRanges()) {
1086 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1087 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +00001088 End = End ? End : Asm->getFunctionEnd();
1089 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001090 }
1091
Reid Kleckner876330d2016-02-12 21:48:30 +00001092 LocalVariable Var;
1093 Var.DIVar = VI.Var;
1094 Var.DefRanges.emplace_back(std::move(DefRange));
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001095 recordLocalVariable(std::move(Var), Scope);
Reid Kleckner876330d2016-02-12 21:48:30 +00001096 }
1097}
1098
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001099static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1100 return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1101}
1102
1103static bool needsReferenceType(const DbgVariableLocation &Loc) {
1104 return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1105}
1106
Bob Haarman223303c2017-08-29 20:59:25 +00001107void CodeViewDebug::calculateRanges(
1108 LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
1109 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1110
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001111 // Calculate the definition ranges.
Bob Haarman223303c2017-08-29 20:59:25 +00001112 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1113 const InsnRange &Range = *I;
1114 const MachineInstr *DVInst = Range.first;
1115 assert(DVInst->isDebugValue() && "Invalid History entry");
1116 // FIXME: Find a way to represent constant variables, since they are
1117 // relatively common.
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001118 Optional<DbgVariableLocation> Location =
1119 DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1120 if (!Location)
Bob Haarmana88bce12017-08-29 21:01:55 +00001121 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001122
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001123 // CodeView can only express variables in register and variables in memory
1124 // at a constant offset from a register. However, for variables passed
1125 // indirectly by pointer, it is common for that pointer to be spilled to a
1126 // stack location. For the special case of one offseted load followed by a
1127 // zero offset load (a pointer spilled to the stack), we change the type of
1128 // the local variable from a value type to a reference type. This tricks the
1129 // debugger into doing the load for us.
1130 if (Var.UseReferenceType) {
1131 // We're using a reference type. Drop the last zero offset load.
1132 if (canUseReferenceType(*Location))
1133 Location->LoadChain.pop_back();
1134 else
1135 continue;
1136 } else if (needsReferenceType(*Location)) {
1137 // This location can't be expressed without switching to a reference type.
1138 // Start over using that.
1139 Var.UseReferenceType = true;
Bob Haarman223303c2017-08-29 20:59:25 +00001140 Var.DefRanges.clear();
1141 calculateRanges(Var, Ranges);
1142 return;
1143 }
1144
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001145 // We can only handle a register or an offseted load of a register.
1146 if (Location->Register == 0 || Location->LoadChain.size() > 1)
Bob Haarman223303c2017-08-29 20:59:25 +00001147 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001148 {
1149 LocalVarDefRange DR;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001150 DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001151 DR.InMemory = !Location->LoadChain.empty();
1152 DR.DataOffset =
1153 !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001154 if (Location->FragmentInfo) {
Bob Haarman223303c2017-08-29 20:59:25 +00001155 DR.IsSubfield = true;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001156 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
Bob Haarman223303c2017-08-29 20:59:25 +00001157 } else {
1158 DR.IsSubfield = false;
1159 DR.StructOffset = 0;
1160 }
1161
1162 if (Var.DefRanges.empty() ||
1163 Var.DefRanges.back().isDifferentLocation(DR)) {
1164 Var.DefRanges.emplace_back(std::move(DR));
1165 }
1166 }
1167
1168 // Compute the label range.
1169 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1170 const MCSymbol *End = getLabelAfterInsn(Range.second);
1171 if (!End) {
1172 // This range is valid until the next overlapping bitpiece. In the
1173 // common case, ranges will not be bitpieces, so they will overlap.
1174 auto J = std::next(I);
1175 const DIExpression *DIExpr = DVInst->getDebugExpression();
1176 while (J != E &&
Bjorn Petterssona223f8152018-03-12 18:02:39 +00001177 !DIExpr->fragmentsOverlap(J->first->getDebugExpression()))
Bob Haarman223303c2017-08-29 20:59:25 +00001178 ++J;
1179 if (J != E)
1180 End = getLabelBeforeInsn(J->first);
1181 else
1182 End = Asm->getFunctionEnd();
1183 }
1184
1185 // If the last range end is our begin, just extend the last range.
1186 // Otherwise make a new range.
1187 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1188 Var.DefRanges.back().Ranges;
1189 if (!R.empty() && R.back().second == Begin)
1190 R.back().second = End;
1191 else
1192 R.emplace_back(Begin, End);
1193
1194 // FIXME: Do more range combining.
1195 }
1196}
1197
Reid Kleckner876330d2016-02-12 21:48:30 +00001198void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001199 DenseSet<InlinedEntity> Processed;
Reid Kleckner876330d2016-02-12 21:48:30 +00001200 // Grab the variable info that was squirreled away in the MMI side-table.
Matthias Braunef331ef2016-11-30 23:48:50 +00001201 collectVariableInfoFromMFTable(Processed);
Reid Kleckner876330d2016-02-12 21:48:30 +00001202
Reid Kleckner876330d2016-02-12 21:48:30 +00001203 for (const auto &I : DbgValues) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001204 InlinedEntity IV = I.first;
Reid Kleckner876330d2016-02-12 21:48:30 +00001205 if (Processed.count(IV))
1206 continue;
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001207 const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
Reid Kleckner876330d2016-02-12 21:48:30 +00001208 const DILocation *InlinedAt = IV.second;
1209
1210 // Instruction ranges, specifying where IV is accessible.
1211 const auto &Ranges = I.second;
1212
1213 LexicalScope *Scope = nullptr;
1214 if (InlinedAt)
1215 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1216 else
1217 Scope = LScopes.findLexicalScope(DIVar->getScope());
1218 // If variable scope is not found then skip this variable.
1219 if (!Scope)
1220 continue;
1221
1222 LocalVariable Var;
1223 Var.DIVar = DIVar;
1224
Bob Haarman223303c2017-08-29 20:59:25 +00001225 calculateRanges(Var, Ranges);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001226 recordLocalVariable(std::move(Var), Scope);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001227 }
1228}
1229
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001230void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00001231 const Function &GV = MF->getFunction();
Reid Kleckner55baeef2018-03-15 21:12:21 +00001232 auto Insertion = FnDebugInfo.insert({&GV, llvm::make_unique<FunctionInfo>()});
Reid Klecknere9dc30d2018-03-15 21:18:42 +00001233 assert(Insertion.second && "function already has info");
Reid Kleckner55baeef2018-03-15 21:12:21 +00001234 CurFn = Insertion.first->second.get();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001235 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001236 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001237
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001238 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1239
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001240 // Find the end of the function prolog. First known non-DBG_VALUE and
1241 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001242 // FIXME: is there a simpler a way to do this? Can we just search
1243 // for the first instruction of the function, not the last of the prolog?
1244 DebugLoc PrologEndLoc;
1245 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001246 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001247 for (const auto &MI : MBB) {
Adrian Prantlfb31da12017-05-22 20:47:09 +00001248 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001249 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001250 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001251 break;
Adrian Prantlfb31da12017-05-22 20:47:09 +00001252 } else if (!MI.isMetaInstruction()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001253 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001254 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001255 }
1256 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001257
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001258 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001259 if (PrologEndLoc && !EmptyPrologue) {
1260 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001261 maybeRecordLocation(FnStartDL, MF);
1262 }
1263}
1264
Zachary Turnera7b04172017-08-28 18:49:04 +00001265static bool shouldEmitUdt(const DIType *T) {
Zachary Turner37c74742017-09-05 22:06:39 +00001266 if (!T)
1267 return false;
1268
1269 // MSVC does not emit UDTs for typedefs that are scoped to classes.
1270 if (T->getTag() == dwarf::DW_TAG_typedef) {
1271 if (DIScope *Scope = T->getScope().resolve()) {
1272 switch (Scope->getTag()) {
1273 case dwarf::DW_TAG_structure_type:
1274 case dwarf::DW_TAG_class_type:
1275 case dwarf::DW_TAG_union_type:
1276 return false;
1277 }
1278 }
1279 }
1280
Zachary Turnera7b04172017-08-28 18:49:04 +00001281 while (true) {
1282 if (!T || T->isForwardDecl())
1283 return false;
1284
1285 const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1286 if (!DT)
1287 return true;
1288 T = DT->getBaseType().resolve();
1289 }
1290 return true;
1291}
1292
1293void CodeViewDebug::addToUDTs(const DIType *Ty) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001294 // Don't record empty UDTs.
1295 if (Ty->getName().empty())
1296 return;
Zachary Turnera7b04172017-08-28 18:49:04 +00001297 if (!shouldEmitUdt(Ty))
1298 return;
Reid Klecknerad56ea32016-07-01 22:24:51 +00001299
Hans Wennborg4b63a982016-06-23 22:57:25 +00001300 SmallVector<StringRef, 5> QualifiedNameComponents;
1301 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1302 Ty->getScope().resolve(), QualifiedNameComponents);
1303
1304 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001305 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001306
Zachary Turnera7b04172017-08-28 18:49:04 +00001307 if (ClosestSubprogram == nullptr) {
1308 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1309 } else if (ClosestSubprogram == CurrentSubprogram) {
1310 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1311 }
Hans Wennborg4b63a982016-06-23 22:57:25 +00001312
1313 // TODO: What if the ClosestSubprogram is neither null or the current
1314 // subprogram? Currently, the UDT just gets dropped on the floor.
1315 //
1316 // The current behavior is not desirable. To get maximal fidelity, we would
1317 // need to perform all type translation before beginning emission of .debug$S
1318 // and then make LocalUDTs a member of FunctionInfo
1319}
1320
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001321TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001322 // Generic dispatch for lowering an unknown type.
1323 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001324 case dwarf::DW_TAG_array_type:
1325 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001326 case dwarf::DW_TAG_typedef:
1327 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001328 case dwarf::DW_TAG_base_type:
1329 return lowerTypeBasic(cast<DIBasicType>(Ty));
1330 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001331 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1332 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1333 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001334 case dwarf::DW_TAG_reference_type:
1335 case dwarf::DW_TAG_rvalue_reference_type:
1336 return lowerTypePointer(cast<DIDerivedType>(Ty));
1337 case dwarf::DW_TAG_ptr_to_member_type:
1338 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
Reid Kleckner3acdc672018-02-27 22:08:15 +00001339 case dwarf::DW_TAG_restrict_type:
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001340 case dwarf::DW_TAG_const_type:
1341 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001342 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001343 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001344 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001345 if (ClassTy) {
1346 // The member function type of a member function pointer has no
1347 // ThisAdjustment.
1348 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001349 /*ThisAdjustment=*/0,
1350 /*IsStaticMethod=*/false);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001351 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001352 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001353 case dwarf::DW_TAG_enumeration_type:
1354 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001355 case dwarf::DW_TAG_class_type:
1356 case dwarf::DW_TAG_structure_type:
1357 return lowerTypeClass(cast<DICompositeType>(Ty));
1358 case dwarf::DW_TAG_union_type:
1359 return lowerTypeUnion(cast<DICompositeType>(Ty));
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001360 case dwarf::DW_TAG_unspecified_type:
1361 return TypeIndex::None();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001362 default:
1363 // Use the null type index.
1364 return TypeIndex();
1365 }
1366}
1367
David Majnemerd065e232016-06-02 06:21:37 +00001368TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001369 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1370 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001371 StringRef TypeName = Ty->getName();
1372
Zachary Turnera7b04172017-08-28 18:49:04 +00001373 addToUDTs(Ty);
David Majnemer3128b102016-06-15 18:00:01 +00001374
David Majnemerd065e232016-06-02 06:21:37 +00001375 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001376 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001377 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001378 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001379 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001380 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001381
David Majnemerd065e232016-06-02 06:21:37 +00001382 return UnderlyingTypeIndex;
1383}
1384
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001385TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1386 DITypeRef ElementTypeRef = Ty->getBaseType();
1387 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1388 // IndexType is size_t, which depends on the bitness of the target.
Matt Arsenault41e5ac42018-03-14 00:36:23 +00001389 TypeIndex IndexType = getPointerSizeInBytes() == 8
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001390 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1391 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001392
1393 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1394
Amjad Aboudacee5682016-07-12 12:06:34 +00001395 // Add subranges to array type.
1396 DINodeArray Elements = Ty->getElements();
1397 for (int i = Elements.size() - 1; i >= 0; --i) {
1398 const DINode *Element = Elements[i];
1399 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1400
1401 const DISubrange *Subrange = cast<DISubrange>(Element);
1402 assert(Subrange->getLowerBound() == 0 &&
1403 "codeview doesn't support subranges with lower bounds");
Sander de Smalenfdf40912018-01-24 09:56:07 +00001404 int64_t Count = -1;
1405 if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
1406 Count = CI->getSExtValue();
Amjad Aboudacee5682016-07-12 12:06:34 +00001407
Reid Klecknercd7bba02017-09-13 23:30:01 +00001408 // Forward declarations of arrays without a size and VLAs use a count of -1.
1409 // Emit a count of zero in these cases to match what MSVC does for arrays
1410 // without a size. MSVC doesn't support VLAs, so it's not clear what we
1411 // should do for them even if we could distinguish them.
Reid Kleckner6b78e162017-03-24 23:28:42 +00001412 if (Count == -1)
Reid Kleckner89af1122017-09-13 21:54:20 +00001413 Count = 0;
Amjad Aboudacee5682016-07-12 12:06:34 +00001414
Amjad Aboudacee5682016-07-12 12:06:34 +00001415 // Update the element size and element type index for subsequent subranges.
1416 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001417
1418 // If this is the outermost array, use the size from the array. It will be
Reid Kleckner6b78e162017-03-24 23:28:42 +00001419 // more accurate if we had a VLA or an incomplete element type size.
Reid Kleckner10762882016-09-09 17:29:36 +00001420 uint64_t ArraySize =
1421 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1422
1423 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner4efa0a42016-11-08 22:24:53 +00001424 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00001425 ElementTypeIndex = TypeTable.writeLeafType(AR);
Amjad Aboudacee5682016-07-12 12:06:34 +00001426 }
1427
Amjad Aboudacee5682016-07-12 12:06:34 +00001428 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001429}
1430
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001431TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1432 TypeIndex Index;
1433 dwarf::TypeKind Kind;
1434 uint32_t ByteSize;
1435
1436 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001437 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001438
1439 SimpleTypeKind STK = SimpleTypeKind::None;
1440 switch (Kind) {
1441 case dwarf::DW_ATE_address:
1442 // FIXME: Translate
1443 break;
1444 case dwarf::DW_ATE_boolean:
1445 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001446 case 1: STK = SimpleTypeKind::Boolean8; break;
1447 case 2: STK = SimpleTypeKind::Boolean16; break;
1448 case 4: STK = SimpleTypeKind::Boolean32; break;
1449 case 8: STK = SimpleTypeKind::Boolean64; break;
1450 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001451 }
1452 break;
1453 case dwarf::DW_ATE_complex_float:
1454 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001455 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001456 case 4: STK = SimpleTypeKind::Complex32; break;
1457 case 8: STK = SimpleTypeKind::Complex64; break;
1458 case 10: STK = SimpleTypeKind::Complex80; break;
1459 case 16: STK = SimpleTypeKind::Complex128; break;
1460 }
1461 break;
1462 case dwarf::DW_ATE_float:
1463 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001464 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001465 case 4: STK = SimpleTypeKind::Float32; break;
1466 case 6: STK = SimpleTypeKind::Float48; break;
1467 case 8: STK = SimpleTypeKind::Float64; break;
1468 case 10: STK = SimpleTypeKind::Float80; break;
1469 case 16: STK = SimpleTypeKind::Float128; break;
1470 }
1471 break;
1472 case dwarf::DW_ATE_signed:
1473 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001474 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1475 case 2: STK = SimpleTypeKind::Int16Short; break;
1476 case 4: STK = SimpleTypeKind::Int32; break;
1477 case 8: STK = SimpleTypeKind::Int64Quad; break;
1478 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001479 }
1480 break;
1481 case dwarf::DW_ATE_unsigned:
1482 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001483 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1484 case 2: STK = SimpleTypeKind::UInt16Short; break;
1485 case 4: STK = SimpleTypeKind::UInt32; break;
1486 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1487 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001488 }
1489 break;
1490 case dwarf::DW_ATE_UTF:
1491 switch (ByteSize) {
1492 case 2: STK = SimpleTypeKind::Character16; break;
1493 case 4: STK = SimpleTypeKind::Character32; break;
1494 }
1495 break;
1496 case dwarf::DW_ATE_signed_char:
1497 if (ByteSize == 1)
1498 STK = SimpleTypeKind::SignedCharacter;
1499 break;
1500 case dwarf::DW_ATE_unsigned_char:
1501 if (ByteSize == 1)
1502 STK = SimpleTypeKind::UnsignedCharacter;
1503 break;
1504 default:
1505 break;
1506 }
1507
1508 // Apply some fixups based on the source-level type name.
1509 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1510 STK = SimpleTypeKind::Int32Long;
1511 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1512 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001513 if (STK == SimpleTypeKind::UInt16Short &&
1514 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001515 STK = SimpleTypeKind::WideCharacter;
1516 if ((STK == SimpleTypeKind::SignedCharacter ||
1517 STK == SimpleTypeKind::UnsignedCharacter) &&
1518 Ty->getName() == "char")
1519 STK = SimpleTypeKind::NarrowCharacter;
1520
1521 return TypeIndex(STK);
1522}
1523
Reid Kleckner3acdc672018-02-27 22:08:15 +00001524TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1525 PointerOptions PO) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001526 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1527
Reid Kleckner3acdc672018-02-27 22:08:15 +00001528 // Pointers to simple types without any options can use SimpleTypeMode, rather
1529 // than having a dedicated pointer type record.
1530 if (PointeeTI.isSimple() && PO == PointerOptions::None &&
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001531 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1532 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1533 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1534 ? SimpleTypeMode::NearPointer64
1535 : SimpleTypeMode::NearPointer32;
1536 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1537 }
1538
1539 PointerKind PK =
1540 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1541 PointerMode PM = PointerMode::Pointer;
1542 switch (Ty->getTag()) {
1543 default: llvm_unreachable("not a pointer tag type");
1544 case dwarf::DW_TAG_pointer_type:
1545 PM = PointerMode::Pointer;
1546 break;
1547 case dwarf::DW_TAG_reference_type:
1548 PM = PointerMode::LValueReference;
1549 break;
1550 case dwarf::DW_TAG_rvalue_reference_type:
1551 PM = PointerMode::RValueReference;
1552 break;
1553 }
Reid Kleckner3acdc672018-02-27 22:08:15 +00001554
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001555 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00001556 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001557}
1558
Reid Kleckner6fa15462016-06-17 22:14:39 +00001559static PointerToMemberRepresentation
1560translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1561 // SizeInBytes being zero generally implies that the member pointer type was
1562 // incomplete, which can happen if it is part of a function prototype. In this
1563 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001564 if (IsPMF) {
1565 switch (Flags & DINode::FlagPtrToMemberRep) {
1566 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001567 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1568 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001569 case DINode::FlagSingleInheritance:
1570 return PointerToMemberRepresentation::SingleInheritanceFunction;
1571 case DINode::FlagMultipleInheritance:
1572 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1573 case DINode::FlagVirtualInheritance:
1574 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1575 }
1576 } else {
1577 switch (Flags & DINode::FlagPtrToMemberRep) {
1578 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001579 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1580 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001581 case DINode::FlagSingleInheritance:
1582 return PointerToMemberRepresentation::SingleInheritanceData;
1583 case DINode::FlagMultipleInheritance:
1584 return PointerToMemberRepresentation::MultipleInheritanceData;
1585 case DINode::FlagVirtualInheritance:
1586 return PointerToMemberRepresentation::VirtualInheritanceData;
1587 }
1588 }
1589 llvm_unreachable("invalid ptr to member representation");
1590}
1591
Reid Kleckner3acdc672018-02-27 22:08:15 +00001592TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1593 PointerOptions PO) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001594 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1595 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001596 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Matt Arsenault41e5ac42018-03-14 00:36:23 +00001597 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1598 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001599 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1600 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1601 : PointerMode::PointerToDataMember;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001602
Reid Kleckner6fa15462016-06-17 22:14:39 +00001603 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1604 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1605 MemberPointerInfo MPI(
1606 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001607 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner6900de12017-11-28 18:33:17 +00001608 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001609}
1610
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001611/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1612/// have a translation, use the NearC convention.
1613static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1614 switch (DwarfCC) {
1615 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1616 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1617 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1618 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1619 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1620 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1621 }
1622 return CallingConvention::NearC;
1623}
1624
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001625TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1626 ModifierOptions Mods = ModifierOptions::None;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001627 PointerOptions PO = PointerOptions::None;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001628 bool IsModifier = true;
1629 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001630 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001631 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001632 switch (BaseTy->getTag()) {
1633 case dwarf::DW_TAG_const_type:
1634 Mods |= ModifierOptions::Const;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001635 PO |= PointerOptions::Const;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001636 break;
1637 case dwarf::DW_TAG_volatile_type:
1638 Mods |= ModifierOptions::Volatile;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001639 PO |= PointerOptions::Volatile;
1640 break;
1641 case dwarf::DW_TAG_restrict_type:
1642 // Only pointer types be marked with __restrict. There is no known flag
1643 // for __restrict in LF_MODIFIER records.
1644 PO |= PointerOptions::Restrict;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001645 break;
1646 default:
1647 IsModifier = false;
1648 break;
1649 }
1650 if (IsModifier)
1651 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1652 }
Reid Kleckner3acdc672018-02-27 22:08:15 +00001653
1654 // Check if the inner type will use an LF_POINTER record. If so, the
1655 // qualifiers will go in the LF_POINTER record. This comes up for types like
1656 // 'int *const' and 'int *__restrict', not the more common cases like 'const
1657 // char *'.
1658 if (BaseTy) {
1659 switch (BaseTy->getTag()) {
1660 case dwarf::DW_TAG_pointer_type:
1661 case dwarf::DW_TAG_reference_type:
1662 case dwarf::DW_TAG_rvalue_reference_type:
1663 return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
1664 case dwarf::DW_TAG_ptr_to_member_type:
1665 return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
1666 default:
1667 break;
1668 }
1669 }
1670
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001671 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Reid Kleckner3acdc672018-02-27 22:08:15 +00001672
1673 // Return the base type index if there aren't any modifiers. For example, the
1674 // metadata could contain restrict wrappers around non-pointer types.
1675 if (Mods == ModifierOptions::None)
1676 return ModifiedTI;
1677
Zachary Turner4efa0a42016-11-08 22:24:53 +00001678 ModifierRecord MR(ModifiedTI, Mods);
Zachary Turner6900de12017-11-28 18:33:17 +00001679 return TypeTable.writeLeafType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001680}
1681
David Majnemer75c3ebf2016-06-02 17:13:53 +00001682TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1683 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1684 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1685 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1686
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001687 // MSVC uses type none for variadic argument.
1688 if (ReturnAndArgTypeIndices.size() > 1 &&
1689 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1690 ReturnAndArgTypeIndices.back() = TypeIndex::None();
1691 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001692 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1693 ArrayRef<TypeIndex> ArgTypeIndices = None;
1694 if (!ReturnAndArgTypeIndices.empty()) {
1695 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1696 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1697 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1698 }
1699
1700 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001701 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001702
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001703 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1704
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001705 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1706 ArgTypeIndices.size(), ArgListIndex);
Zachary Turner6900de12017-11-28 18:33:17 +00001707 return TypeTable.writeLeafType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001708}
1709
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001710TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001711 const DIType *ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001712 int ThisAdjustment,
1713 bool IsStaticMethod) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001714 // Lower the containing class type.
1715 TypeIndex ClassType = getTypeIndex(ClassTy);
1716
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001717 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1718 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1719 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1720
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001721 // MSVC uses type none for variadic argument.
1722 if (ReturnAndArgTypeIndices.size() > 1 &&
1723 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1724 ReturnAndArgTypeIndices.back() = TypeIndex::None();
1725 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001726 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1727 ArrayRef<TypeIndex> ArgTypeIndices = None;
1728 if (!ReturnAndArgTypeIndices.empty()) {
1729 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1730 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1731 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1732 }
Reid Kleckner87288b92017-09-15 00:59:07 +00001733 TypeIndex ThisTypeIndex;
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001734 if (!IsStaticMethod && !ArgTypeIndices.empty()) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001735 ThisTypeIndex = ArgTypeIndices.front();
1736 ArgTypeIndices = ArgTypeIndices.drop_front();
1737 }
1738
1739 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001740 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001741
1742 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1743
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001744 // TODO: Need to use the correct values for FunctionOptions.
Zachary Turner4efa0a42016-11-08 22:24:53 +00001745 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
1746 FunctionOptions::None, ArgTypeIndices.size(),
1747 ArgListIndex, ThisAdjustment);
Zachary Turner6900de12017-11-28 18:33:17 +00001748 return TypeTable.writeLeafType(MFR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001749}
1750
Reid Kleckner9dac4732016-08-31 15:59:30 +00001751TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001752 unsigned VSlotCount =
1753 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
Reid Kleckner9dac4732016-08-31 15:59:30 +00001754 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001755
1756 VFTableShapeRecord VFTSR(Slots);
Zachary Turner6900de12017-11-28 18:33:17 +00001757 return TypeTable.writeLeafType(VFTSR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001758}
1759
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001760static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1761 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001762 case DINode::FlagPrivate: return MemberAccess::Private;
1763 case DINode::FlagPublic: return MemberAccess::Public;
1764 case DINode::FlagProtected: return MemberAccess::Protected;
1765 case 0:
1766 // If there was no explicit access control, provide the default for the tag.
1767 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1768 : MemberAccess::Public;
1769 }
1770 llvm_unreachable("access flags are exclusive");
1771}
1772
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001773static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1774 if (SP->isArtificial())
1775 return MethodOptions::CompilerGenerated;
1776
1777 // FIXME: Handle other MethodOptions.
1778
1779 return MethodOptions::None;
1780}
1781
1782static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1783 bool Introduced) {
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001784 if (SP->getFlags() & DINode::FlagStaticMember)
1785 return MethodKind::Static;
1786
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001787 switch (SP->getVirtuality()) {
1788 case dwarf::DW_VIRTUALITY_none:
1789 break;
1790 case dwarf::DW_VIRTUALITY_virtual:
1791 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1792 case dwarf::DW_VIRTUALITY_pure_virtual:
1793 return Introduced ? MethodKind::PureIntroducingVirtual
1794 : MethodKind::PureVirtual;
1795 default:
1796 llvm_unreachable("unhandled virtuality case");
1797 }
1798
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001799 return MethodKind::Vanilla;
1800}
1801
Reid Klecknera8d57402016-06-03 15:58:20 +00001802static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1803 switch (Ty->getTag()) {
1804 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1805 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1806 }
1807 llvm_unreachable("unexpected tag");
1808}
1809
Reid Klecknere092dad2016-07-02 00:11:07 +00001810/// Return ClassOptions that should be present on both the forward declaration
1811/// and the defintion of a tag type.
1812static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1813 ClassOptions CO = ClassOptions::None;
1814
1815 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001816 // appear to give every type a linkage name, which may be problematic for us.
1817 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001818 if (!Ty->getIdentifier().empty())
1819 CO |= ClassOptions::HasUniqueName;
1820
1821 // Put the Nested flag on a type if it appears immediately inside a tag type.
1822 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1823 // here. That flag is only set on definitions, and not forward declarations.
1824 const DIScope *ImmediateScope = Ty->getScope().resolve();
1825 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1826 CO |= ClassOptions::Nested;
1827
1828 // Put the Scoped flag on function-local types.
1829 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1830 Scope = Scope->getScope().resolve()) {
1831 if (isa<DISubprogram>(Scope)) {
1832 CO |= ClassOptions::Scoped;
1833 break;
1834 }
1835 }
1836
1837 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001838}
1839
Aaron Smith122d9e72018-03-06 18:20:22 +00001840void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
1841 switch (Ty->getTag()) {
1842 case dwarf::DW_TAG_class_type:
1843 case dwarf::DW_TAG_structure_type:
1844 case dwarf::DW_TAG_union_type:
1845 case dwarf::DW_TAG_enumeration_type:
1846 break;
1847 default:
1848 return;
1849 }
1850
1851 if (const auto *File = Ty->getFile()) {
1852 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
1853 TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
1854
1855 UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
1856 TypeTable.writeLeafType(USLR);
1857 }
1858}
1859
David Majnemer979cb882016-06-16 21:32:16 +00001860TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001861 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001862 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001863 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001864
David Majnemerda9548f2016-06-17 16:13:21 +00001865 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001866 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001867 } else {
Zachary Turner6900de12017-11-28 18:33:17 +00001868 ContinuationRecordBuilder ContinuationBuilder;
1869 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
David Majnemerda9548f2016-06-17 16:13:21 +00001870 for (const DINode *Element : Ty->getElements()) {
1871 // We assume that the frontend provides all members in source declaration
1872 // order, which is what MSVC does.
1873 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001874 EnumeratorRecord ER(MemberAccess::Public,
1875 APSInt::getUnsigned(Enumerator->getValue()),
1876 Enumerator->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00001877 ContinuationBuilder.writeMemberType(ER);
David Majnemerda9548f2016-06-17 16:13:21 +00001878 EnumeratorCount++;
1879 }
1880 }
Zachary Turner6900de12017-11-28 18:33:17 +00001881 FTI = TypeTable.insertRecord(ContinuationBuilder);
David Majnemerda9548f2016-06-17 16:13:21 +00001882 }
David Majnemer979cb882016-06-16 21:32:16 +00001883
David Majnemer6bdc24e2016-07-01 23:12:45 +00001884 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001885
Zachary Turner4efa0a42016-11-08 22:24:53 +00001886 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
1887 getTypeIndex(Ty->getBaseType()));
Aaron Smith122d9e72018-03-06 18:20:22 +00001888 TypeIndex EnumTI = TypeTable.writeLeafType(ER);
1889
1890 addUDTSrcLine(Ty, EnumTI);
1891
1892 return EnumTI;
David Majnemer979cb882016-06-16 21:32:16 +00001893}
1894
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001895//===----------------------------------------------------------------------===//
1896// ClassInfo
1897//===----------------------------------------------------------------------===//
1898
1899struct llvm::ClassInfo {
1900 struct MemberInfo {
1901 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00001902 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001903 };
1904 // [MemberInfo]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001905 using MemberList = std::vector<MemberInfo>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001906
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001907 using MethodsList = TinyPtrVector<const DISubprogram *>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001908 // MethodName -> MethodsList
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001909 using MethodsMap = MapVector<MDString *, MethodsList>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001910
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001911 /// Base classes.
1912 std::vector<const DIDerivedType *> Inheritance;
1913
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001914 /// Direct members.
1915 MemberList Members;
1916 // Direct overloaded methods gathered by name.
1917 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001918
Reid Kleckner9dac4732016-08-31 15:59:30 +00001919 TypeIndex VShapeTI;
1920
Reid Klecknere2e82062017-08-08 20:30:14 +00001921 std::vector<const DIType *> NestedTypes;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001922};
1923
1924void CodeViewDebug::clear() {
1925 assert(CurFn == nullptr);
1926 FileIdMap.clear();
1927 FnDebugInfo.clear();
1928 FileToFilepathMap.clear();
1929 LocalUDTs.clear();
1930 GlobalUDTs.clear();
1931 TypeIndices.clear();
1932 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001933}
1934
1935void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1936 const DIDerivedType *DDTy) {
1937 if (!DDTy->getName().empty()) {
1938 Info.Members.push_back({DDTy, 0});
1939 return;
1940 }
Shoaib Meenai03303a32018-02-27 21:48:41 +00001941
1942 // An unnamed member may represent a nested struct or union. Attempt to
1943 // interpret the unnamed member as a DICompositeType possibly wrapped in
1944 // qualifier types. Add all the indirect fields to the current record if that
1945 // succeeds, and drop the member if that fails.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001946 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00001947 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001948 const DIType *Ty = DDTy->getBaseType().resolve();
Shoaib Meenai03303a32018-02-27 21:48:41 +00001949 bool FullyResolved = false;
1950 while (!FullyResolved) {
1951 switch (Ty->getTag()) {
1952 case dwarf::DW_TAG_const_type:
1953 case dwarf::DW_TAG_volatile_type:
1954 // FIXME: we should apply the qualifier types to the indirect fields
1955 // rather than dropping them.
1956 Ty = cast<DIDerivedType>(Ty)->getBaseType().resolve();
1957 break;
1958 default:
1959 FullyResolved = true;
1960 break;
1961 }
1962 }
1963
1964 const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
1965 if (!DCTy)
1966 return;
1967
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001968 ClassInfo NestedInfo = collectClassInfo(DCTy);
1969 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001970 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001971 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001972}
1973
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001974ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1975 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001976 // Add elements to structure type.
1977 DINodeArray Elements = Ty->getElements();
1978 for (auto *Element : Elements) {
1979 // We assume that the frontend provides all members in source declaration
1980 // order, which is what MSVC does.
1981 if (!Element)
1982 continue;
1983 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001984 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001985 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001986 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001987 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001988 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1989 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001990 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1991 DDTy->getName() == "__vtbl_ptr_type") {
1992 Info.VShapeTI = getTypeIndex(DDTy);
Reid Klecknere2e82062017-08-08 20:30:14 +00001993 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
1994 Info.NestedTypes.push_back(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001995 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1996 // Ignore friend members. It appears that MSVC emitted info about
1997 // friends in the past, but modern versions do not.
1998 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001999 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
Reid Klecknere2e82062017-08-08 20:30:14 +00002000 Info.NestedTypes.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002001 }
2002 // Skip other unrecognized kinds of elements.
2003 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002004 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002005}
2006
Brock Wymab60532f2018-06-11 01:39:34 +00002007static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
2008 // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2009 // if a complete type should be emitted instead of a forward reference.
2010 return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2011 !Ty->isForwardDecl();
2012}
2013
Reid Klecknera8d57402016-06-03 15:58:20 +00002014TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
Brock Wymab60532f2018-06-11 01:39:34 +00002015 // Emit the complete type for unnamed structs. C++ classes with methods
2016 // which have a circular reference back to the class type are expected to
2017 // be named by the front-end and should not be "unnamed". C unnamed
2018 // structs should not have circular references.
2019 if (shouldAlwaysEmitCompleteClassType(Ty)) {
2020 // If this unnamed complete type is already in the process of being defined
2021 // then the description of the type is malformed and cannot be emitted
2022 // into CodeView correctly so report a fatal error.
2023 auto I = CompleteTypeIndices.find(Ty);
2024 if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2025 report_fatal_error("cannot debug circular reference to unnamed type");
2026 return getCompleteTypeIndex(Ty);
2027 }
2028
Reid Klecknera8d57402016-06-03 15:58:20 +00002029 // First, construct the forward decl. Don't look into Ty to compute the
2030 // forward decl options, since it might not be available in all TUs.
2031 TypeRecordKind Kind = getRecordKind(Ty);
2032 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00002033 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00002034 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00002035 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2036 FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002037 TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
Reid Kleckner643dd832016-06-22 17:15:28 +00002038 if (!Ty->isForwardDecl())
2039 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00002040 return FwdDeclTI;
2041}
2042
2043TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2044 // Construct the field list and complete type record.
2045 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00002046 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002047 TypeIndex FieldTI;
2048 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002049 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002050 bool ContainsNestedClass;
2051 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2052 lowerRecordFieldList(Ty);
2053
2054 if (ContainsNestedClass)
2055 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00002056
David Majnemer6bdc24e2016-07-01 23:12:45 +00002057 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00002058
Reid Klecknera8d57402016-06-03 15:58:20 +00002059 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00002060
Zachary Turner4efa0a42016-11-08 22:24:53 +00002061 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2062 SizeInBytes, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002063 TypeIndex ClassTI = TypeTable.writeLeafType(CR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002064
Aaron Smith122d9e72018-03-06 18:20:22 +00002065 addUDTSrcLine(Ty, ClassTI);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002066
Zachary Turnera7b04172017-08-28 18:49:04 +00002067 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00002068
Hans Wennborg9a519a02016-06-22 21:22:13 +00002069 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002070}
2071
2072TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
Brock Wymab60532f2018-06-11 01:39:34 +00002073 // Emit the complete type for unnamed unions.
2074 if (shouldAlwaysEmitCompleteClassType(Ty))
2075 return getCompleteTypeIndex(Ty);
2076
Reid Klecknera8d57402016-06-03 15:58:20 +00002077 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00002078 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00002079 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00002080 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002081 TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
Reid Kleckner643dd832016-06-22 17:15:28 +00002082 if (!Ty->isForwardDecl())
2083 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00002084 return FwdDeclTI;
2085}
2086
2087TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00002088 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002089 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002090 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002091 bool ContainsNestedClass;
2092 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2093 lowerRecordFieldList(Ty);
2094
2095 if (ContainsNestedClass)
2096 CO |= ClassOptions::ContainsNestedClass;
2097
Reid Klecknera8d57402016-06-03 15:58:20 +00002098 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00002099 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002100
Zachary Turner4efa0a42016-11-08 22:24:53 +00002101 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2102 Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002103 TypeIndex UnionTI = TypeTable.writeLeafType(UR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002104
Aaron Smith122d9e72018-03-06 18:20:22 +00002105 addUDTSrcLine(Ty, UnionTI);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002106
Zachary Turnera7b04172017-08-28 18:49:04 +00002107 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00002108
Hans Wennborg9a519a02016-06-22 21:22:13 +00002109 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002110}
2111
Adrian McCarthy820ca542016-07-06 19:49:51 +00002112std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00002113CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2114 // Manually count members. MSVC appears to count everything that generates a
2115 // field list record. Each individual overload in a method overload group
2116 // contributes to this count, even though the overload group is a single field
2117 // list record.
2118 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002119 ClassInfo Info = collectClassInfo(Ty);
Zachary Turner6900de12017-11-28 18:33:17 +00002120 ContinuationRecordBuilder ContinuationBuilder;
2121 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002122
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002123 // Create base classes.
2124 for (const DIDerivedType *I : Info.Inheritance) {
2125 if (I->getFlags() & DINode::FlagVirtual) {
2126 // Virtual base.
Brock Wyma3db2b102018-05-14 21:21:22 +00002127 unsigned VBPtrOffset = I->getVBPtrOffset();
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002128 // FIXME: Despite the accessor name, the offset is really in bytes.
2129 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00002130 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2131 ? TypeRecordKind::IndirectVirtualBaseClass
2132 : TypeRecordKind::VirtualBaseClass;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002133 VirtualBaseClassRecord VBCR(
Bob Haarman26a87bd2016-10-25 22:11:52 +00002134 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002135 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
Zachary Turner4efa0a42016-11-08 22:24:53 +00002136 VBTableIndex);
2137
Zachary Turner6900de12017-11-28 18:33:17 +00002138 ContinuationBuilder.writeMemberType(VBCR);
Brock Wyma4536c1f2018-02-01 20:37:38 +00002139 MemberCount++;
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002140 } else {
2141 assert(I->getOffsetInBits() % 8 == 0 &&
2142 "bases must be on byte boundaries");
Zachary Turner4efa0a42016-11-08 22:24:53 +00002143 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2144 getTypeIndex(I->getBaseType()),
2145 I->getOffsetInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002146 ContinuationBuilder.writeMemberType(BCR);
Brock Wyma4536c1f2018-02-01 20:37:38 +00002147 MemberCount++;
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002148 }
2149 }
2150
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002151 // Create members.
2152 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2153 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2154 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00002155 StringRef MemberName = Member->getName();
2156 MemberAccess Access =
2157 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002158
2159 if (Member->isStaticMember()) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002160 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002161 ContinuationBuilder.writeMemberType(SDMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002162 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002163 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00002164 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002165
Reid Kleckner9dac4732016-08-31 15:59:30 +00002166 // Virtual function pointer member.
2167 if ((Member->getFlags() & DINode::FlagArtificial) &&
2168 Member->getName().startswith("_vptr$")) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002169 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
Zachary Turner6900de12017-11-28 18:33:17 +00002170 ContinuationBuilder.writeMemberType(VFPR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002171 MemberCount++;
2172 continue;
2173 }
2174
David Majnemer9319cbc2016-06-30 03:00:20 +00002175 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00002176 uint64_t MemberOffsetInBits =
2177 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002178 if (Member->isBitField()) {
2179 uint64_t StartBitOffset = MemberOffsetInBits;
2180 if (const auto *CI =
2181 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00002182 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002183 }
2184 StartBitOffset -= MemberOffsetInBits;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002185 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2186 StartBitOffset);
Zachary Turner6900de12017-11-28 18:33:17 +00002187 MemberBaseType = TypeTable.writeLeafType(BFR);
David Majnemer9319cbc2016-06-30 03:00:20 +00002188 }
2189 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002190 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2191 MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002192 ContinuationBuilder.writeMemberType(DMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002193 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002194 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002195
2196 // Create methods
2197 for (auto &MethodItr : Info.Methods) {
2198 StringRef Name = MethodItr.first->getString();
2199
2200 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00002201 for (const DISubprogram *SP : MethodItr.second) {
2202 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2203 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002204
2205 unsigned VFTableOffset = -1;
2206 if (Introduced)
2207 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2208
Zachary Turner7251ede2016-11-02 17:05:19 +00002209 Methods.push_back(OneMethodRecord(
2210 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2211 translateMethodKindFlags(SP, Introduced),
2212 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002213 MemberCount++;
2214 }
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002215 assert(!Methods.empty() && "Empty methods map entry");
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002216 if (Methods.size() == 1)
Zachary Turner6900de12017-11-28 18:33:17 +00002217 ContinuationBuilder.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002218 else {
Zachary Turner6900de12017-11-28 18:33:17 +00002219 // FIXME: Make this use its own ContinuationBuilder so that
2220 // MethodOverloadList can be split correctly.
Zachary Turner4efa0a42016-11-08 22:24:53 +00002221 MethodOverloadListRecord MOLR(Methods);
Zachary Turner6900de12017-11-28 18:33:17 +00002222 TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2223
Zachary Turner4efa0a42016-11-08 22:24:53 +00002224 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00002225 ContinuationBuilder.writeMemberType(OMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002226 }
2227 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00002228
2229 // Create nested classes.
Reid Klecknere2e82062017-08-08 20:30:14 +00002230 for (const DIType *Nested : Info.NestedTypes) {
Adrian McCarthy820ca542016-07-06 19:49:51 +00002231 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00002232 ContinuationBuilder.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00002233 MemberCount++;
2234 }
2235
Zachary Turner6900de12017-11-28 18:33:17 +00002236 TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002237 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Reid Klecknere2e82062017-08-08 20:30:14 +00002238 !Info.NestedTypes.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00002239}
2240
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002241TypeIndex CodeViewDebug::getVBPTypeIndex() {
2242 if (!VBPType.getIndex()) {
2243 // Make a 'const int *' type.
2244 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner6900de12017-11-28 18:33:17 +00002245 TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002246
2247 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2248 : PointerKind::Near32;
2249 PointerMode PM = PointerMode::Pointer;
2250 PointerOptions PO = PointerOptions::None;
2251 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
Zachary Turner6900de12017-11-28 18:33:17 +00002252 VBPType = TypeTable.writeLeafType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002253 }
2254
2255 return VBPType;
2256}
2257
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002258TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002259 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002260 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002261
2262 // The null DIType is the void type. Don't try to hash it.
2263 if (!Ty)
2264 return TypeIndex::Void();
2265
Reid Klecknera8d57402016-06-03 15:58:20 +00002266 // Check if we've already translated this type. Don't try to do a
2267 // get-or-create style insertion that caches the hash lookup across the
2268 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002269 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002270 if (I != TypeIndices.end())
2271 return I->second;
2272
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002273 TypeLoweringScope S(*this);
2274 TypeIndex TI = lowerType(Ty, ClassTy);
2275 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002276}
2277
Bob Haarman223303c2017-08-29 20:59:25 +00002278TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
2279 DIType *Ty = TypeRef.resolve();
2280 PointerRecord PR(getTypeIndex(Ty),
2281 getPointerSizeInBytes() == 8 ? PointerKind::Near64
2282 : PointerKind::Near32,
2283 PointerMode::LValueReference, PointerOptions::None,
2284 Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002285 return TypeTable.writeLeafType(PR);
Bob Haarman223303c2017-08-29 20:59:25 +00002286}
2287
Reid Klecknera8d57402016-06-03 15:58:20 +00002288TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
2289 const DIType *Ty = TypeRef.resolve();
2290
2291 // The null DIType is the void type. Don't try to hash it.
2292 if (!Ty)
2293 return TypeIndex::Void();
2294
2295 // If this is a non-record type, the complete type index is the same as the
2296 // normal type index. Just call getTypeIndex.
2297 switch (Ty->getTag()) {
2298 case dwarf::DW_TAG_class_type:
2299 case dwarf::DW_TAG_structure_type:
2300 case dwarf::DW_TAG_union_type:
2301 break;
2302 default:
2303 return getTypeIndex(Ty);
2304 }
2305
Brock Wymab60532f2018-06-11 01:39:34 +00002306 // Check if we've already translated the complete record type.
Reid Klecknera8d57402016-06-03 15:58:20 +00002307 const auto *CTy = cast<DICompositeType>(Ty);
2308 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2309 if (!InsertResult.second)
2310 return InsertResult.first->second;
2311
Reid Kleckner643dd832016-06-22 17:15:28 +00002312 TypeLoweringScope S(*this);
2313
Reid Klecknera8d57402016-06-03 15:58:20 +00002314 // Make sure the forward declaration is emitted first. It's unclear if this
2315 // is necessary, but MSVC does it, and we should follow suit until we can show
2316 // otherwise.
Brock Wymab60532f2018-06-11 01:39:34 +00002317 // We only emit a forward declaration for named types.
2318 if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2319 TypeIndex FwdDeclTI = getTypeIndex(CTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002320
Brock Wymab60532f2018-06-11 01:39:34 +00002321 // Just use the forward decl if we don't have complete type info. This
2322 // might happen if the frontend is using modules and expects the complete
2323 // definition to be emitted elsewhere.
2324 if (CTy->isForwardDecl())
2325 return FwdDeclTI;
2326 }
Reid Klecknera8d57402016-06-03 15:58:20 +00002327
2328 TypeIndex TI;
2329 switch (CTy->getTag()) {
2330 case dwarf::DW_TAG_class_type:
2331 case dwarf::DW_TAG_structure_type:
2332 TI = lowerCompleteTypeClass(CTy);
2333 break;
2334 case dwarf::DW_TAG_union_type:
2335 TI = lowerCompleteTypeUnion(CTy);
2336 break;
2337 default:
2338 llvm_unreachable("not a record");
2339 }
2340
Brock Wymab60532f2018-06-11 01:39:34 +00002341 // Update the type index associated with this CompositeType. This cannot
2342 // use the 'InsertResult' iterator above because it is potentially
2343 // invalidated by map insertions which can occur while lowering the class
2344 // type above.
2345 CompleteTypeIndices[CTy] = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002346 return TI;
2347}
2348
Reid Kleckner643dd832016-06-22 17:15:28 +00002349/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00002350/// and do this until fixpoint, as each complete record type typically
2351/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00002352/// many other record types.
2353void CodeViewDebug::emitDeferredCompleteTypes() {
2354 SmallVector<const DICompositeType *, 4> TypesToEmit;
2355 while (!DeferredCompleteTypes.empty()) {
2356 std::swap(DeferredCompleteTypes, TypesToEmit);
2357 for (const DICompositeType *RecordTy : TypesToEmit)
2358 getCompleteTypeIndex(RecordTy);
2359 TypesToEmit.clear();
2360 }
2361}
2362
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002363void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
2364 // Get the sorted list of parameters and emit them first.
2365 SmallVector<const LocalVariable *, 6> Params;
2366 for (const LocalVariable &L : Locals)
2367 if (L.DIVar->isParameter())
2368 Params.push_back(&L);
Mandeep Singh Grange92f0cf2018-04-06 18:08:42 +00002369 llvm::sort(Params.begin(), Params.end(),
2370 [](const LocalVariable *L, const LocalVariable *R) {
2371 return L->DIVar->getArg() < R->DIVar->getArg();
2372 });
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002373 for (const LocalVariable *L : Params)
2374 emitLocalVariable(*L);
2375
2376 // Next emit all non-parameters in the order that we found them.
2377 for (const LocalVariable &L : Locals)
2378 if (!L.DIVar->isParameter())
2379 emitLocalVariable(L);
2380}
2381
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002382void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
2383 // LocalSym record, see SymbolRecord.h for more info.
2384 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2385 *LocalEnd = MMI->getContext().createTempSymbol();
2386 OS.AddComment("Record length");
2387 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2388 OS.EmitLabel(LocalBegin);
2389
2390 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00002391 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002392
Zachary Turner63a28462016-05-17 23:50:21 +00002393 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002394 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002395 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002396 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002397 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002398
2399 OS.AddComment("TypeIndex");
Reid Kleckner08f5fd52017-08-31 15:56:49 +00002400 TypeIndex TI = Var.UseReferenceType
2401 ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2402 : getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002403 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002404 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002405 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002406 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002407 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002408 OS.EmitLabel(LocalEnd);
2409
Reid Kleckner876330d2016-02-12 21:48:30 +00002410 // Calculate the on disk prefix of the appropriate def range record. The
2411 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2412 // should be big enough to hold all forms without memory allocation.
2413 SmallString<20> BytePrefix;
2414 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2415 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002416 if (DefRange.InMemory) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002417 uint16_t RegRelFlags = 0;
2418 if (DefRange.IsSubfield) {
2419 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2420 (DefRange.StructOffset
2421 << DefRangeRegisterRelSym::OffsetInParentShift);
2422 }
Zachary Turner46225b12016-12-16 22:48:14 +00002423 DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
2424 Sym.Hdr.Register = DefRange.CVRegister;
2425 Sym.Hdr.Flags = RegRelFlags;
2426 Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +00002427 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00002428 BytePrefix +=
2429 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00002430 BytePrefix +=
Zachary Turner46225b12016-12-16 22:48:14 +00002431 StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
Reid Kleckner876330d2016-02-12 21:48:30 +00002432 } else {
2433 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002434 if (DefRange.IsSubfield) {
2435 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002436 DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
2437 Sym.Hdr.Register = DefRange.CVRegister;
2438 Sym.Hdr.MayHaveNoName = 0;
2439 Sym.Hdr.OffsetInParent = DefRange.StructOffset;
2440
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002441 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2442 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2443 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002444 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2445 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002446 } else {
2447 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002448 DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
2449 Sym.Hdr.Register = DefRange.CVRegister;
2450 Sym.Hdr.MayHaveNoName = 0;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002451 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2452 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2453 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002454 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2455 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002456 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002457 }
2458 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2459 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002460}
2461
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002462void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2463 const FunctionInfo& FI) {
2464 for (LexicalBlock *Block : Blocks)
2465 emitLexicalBlock(*Block, FI);
2466}
2467
2468/// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2469/// lexical block scope.
2470void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2471 const FunctionInfo& FI) {
2472 MCSymbol *RecordBegin = MMI->getContext().createTempSymbol(),
2473 *RecordEnd = MMI->getContext().createTempSymbol();
2474
2475 // Lexical block symbol record.
2476 OS.AddComment("Record length");
2477 OS.emitAbsoluteSymbolDiff(RecordEnd, RecordBegin, 2); // Record Length
2478 OS.EmitLabel(RecordBegin);
2479 OS.AddComment("Record kind: S_BLOCK32");
2480 OS.EmitIntValue(SymbolKind::S_BLOCK32, 2); // Record Kind
2481 OS.AddComment("PtrParent");
2482 OS.EmitIntValue(0, 4); // PtrParent
2483 OS.AddComment("PtrEnd");
2484 OS.EmitIntValue(0, 4); // PtrEnd
2485 OS.AddComment("Code size");
2486 OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size
2487 OS.AddComment("Function section relative address");
2488 OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset
2489 OS.AddComment("Function section index");
2490 OS.EmitCOFFSectionIndex(FI.Begin); // Func Symbol
2491 OS.AddComment("Lexical block name");
2492 emitNullTerminatedSymbolName(OS, Block.Name); // Name
2493 OS.EmitLabel(RecordEnd);
2494
2495 // Emit variables local to this lexical block.
2496 emitLocalVariableList(Block.Locals);
2497
2498 // Emit lexical blocks contained within this block.
2499 emitLexicalBlockList(Block.Children, FI);
2500
2501 // Close the lexical block scope.
2502 OS.AddComment("Record length");
2503 OS.EmitIntValue(2, 2); // Record Length
2504 OS.AddComment("Record kind: S_END");
2505 OS.EmitIntValue(SymbolKind::S_END, 2); // Record Kind
2506}
2507
2508/// Convenience routine for collecting lexical block information for a list
2509/// of lexical scopes.
2510void CodeViewDebug::collectLexicalBlockInfo(
2511 SmallVectorImpl<LexicalScope *> &Scopes,
2512 SmallVectorImpl<LexicalBlock *> &Blocks,
2513 SmallVectorImpl<LocalVariable> &Locals) {
2514 for (LexicalScope *Scope : Scopes)
2515 collectLexicalBlockInfo(*Scope, Blocks, Locals);
2516}
2517
2518/// Populate the lexical blocks and local variable lists of the parent with
2519/// information about the specified lexical scope.
2520void CodeViewDebug::collectLexicalBlockInfo(
2521 LexicalScope &Scope,
2522 SmallVectorImpl<LexicalBlock *> &ParentBlocks,
2523 SmallVectorImpl<LocalVariable> &ParentLocals) {
2524 if (Scope.isAbstractScope())
2525 return;
2526
2527 auto LocalsIter = ScopeVariables.find(&Scope);
2528 if (LocalsIter == ScopeVariables.end()) {
2529 // This scope does not contain variables and can be eliminated.
2530 collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
2531 return;
2532 }
2533 SmallVectorImpl<LocalVariable> &Locals = LocalsIter->second;
2534
2535 const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
2536 if (!DILB) {
2537 // This scope is not a lexical block and can be eliminated, but keep any
2538 // local variables it contains.
2539 ParentLocals.append(Locals.begin(), Locals.end());
2540 collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
2541 return;
2542 }
2543
2544 const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
2545 if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second)) {
2546 // This lexical block scope has too many address ranges to represent in the
2547 // current CodeView format or does not have a valid address range.
2548 // Eliminate this lexical scope and promote any locals it contains to the
2549 // parent scope.
2550 //
2551 // For lexical scopes with multiple address ranges you may be tempted to
2552 // construct a single range covering every instruction where the block is
2553 // live and everything in between. Unfortunately, Visual Studio only
2554 // displays variables from the first matching lexical block scope. If the
2555 // first lexical block contains exception handling code or cold code which
2556 // is moved to the bottom of the routine creating a single range covering
2557 // nearly the entire routine, then it will hide all other lexical blocks
2558 // and the variables they contain.
2559 //
2560 ParentLocals.append(Locals.begin(), Locals.end());
2561 collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
2562 return;
2563 }
2564
2565 // Create a new CodeView lexical block for this lexical scope. If we've
2566 // seen this DILexicalBlock before then the scope tree is malformed and
2567 // we can handle this gracefully by not processing it a second time.
2568 auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
2569 if (!BlockInsertion.second)
2570 return;
2571
2572 // Create a lexical block containing the local variables and collect the
2573 // the lexical block information for the children.
2574 const InsnRange &Range = Ranges.front();
2575 assert(Range.first && Range.second);
2576 LexicalBlock &Block = BlockInsertion.first->second;
2577 Block.Begin = getLabelBeforeInsn(Range.first);
2578 Block.End = getLabelAfterInsn(Range.second);
2579 assert(Block.Begin && "missing label for scope begin");
2580 assert(Block.End && "missing label for scope end");
2581 Block.Name = DILB->getName();
2582 Block.Locals = std::move(Locals);
2583 ParentBlocks.push_back(&Block);
2584 collectLexicalBlockInfo(Scope.getChildren(), Block.Children, Block.Locals);
2585}
2586
David Blaikieb2fbb4b2017-02-16 18:48:33 +00002587void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002588 const Function &GV = MF->getFunction();
2589 assert(FnDebugInfo.count(&GV));
Reid Kleckner55baeef2018-03-15 21:12:21 +00002590 assert(CurFn == FnDebugInfo[&GV].get());
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002591
Matthias Braunf1caa282017-12-15 22:22:58 +00002592 collectVariableInfo(GV.getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002593
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002594 // Build the lexical block structure to emit for this routine.
2595 if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
2596 collectLexicalBlockInfo(*CFS, CurFn->ChildBlocks, CurFn->Locals);
2597
2598 // Clear the scope and variable information from the map which will not be
2599 // valid after we have finished processing this routine. This also prepares
2600 // the map for the subsequent routine.
2601 ScopeVariables.clear();
2602
Reid Kleckner2214ed82016-01-29 00:49:42 +00002603 // Don't emit anything if we don't have any line tables.
Brock Wyma94ece8f2018-04-16 16:53:57 +00002604 // Thunks are compiler-generated and probably won't have source correlation.
2605 if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002606 FnDebugInfo.erase(&GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002607 CurFn = nullptr;
2608 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002609 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002610
Reid Klecknere33c94f2017-09-05 20:14:58 +00002611 CurFn->Annotations = MF->getCodeViewAnnotations();
2612
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002613 CurFn->End = Asm->getFunctionEnd();
2614
Craig Topper353eda42014-04-24 06:44:33 +00002615 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002616}
2617
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002618void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002619 DebugHandlerBase::beginInstruction(MI);
2620
Shiva Chen801bf7e2018-05-09 02:42:00 +00002621 // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
2622 if (!Asm || !CurFn || MI->isDebugInstr() ||
David Majnemer67f684e2016-07-28 05:03:22 +00002623 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002624 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002625
2626 // If the first instruction of a new MBB has no location, find the first
2627 // instruction with a location and use that.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002628 DebugLoc DL = MI->getDebugLoc();
Reid Kleckner45a74622017-06-30 21:33:44 +00002629 if (!DL && MI->getParent() != PrevInstBB) {
2630 for (const auto &NextMI : *MI->getParent()) {
Shiva Chen801bf7e2018-05-09 02:42:00 +00002631 if (NextMI.isDebugInstr())
Reid Kleckner2de471d2017-07-31 21:03:08 +00002632 continue;
Reid Kleckner45a74622017-06-30 21:33:44 +00002633 DL = NextMI.getDebugLoc();
2634 if (DL)
2635 break;
2636 }
2637 }
2638 PrevInstBB = MI->getParent();
2639
2640 // If we still don't have a debug location, don't record a location.
2641 if (!DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002642 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002643
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002644 maybeRecordLocation(DL, Asm->MF);
2645}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002646
Zachary Turner8c099fe2017-05-30 16:36:15 +00002647MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002648 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2649 *EndLabel = MMI->getContext().createTempSymbol();
2650 OS.EmitIntValue(unsigned(Kind), 4);
2651 OS.AddComment("Subsection size");
2652 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2653 OS.EmitLabel(BeginLabel);
2654 return EndLabel;
2655}
2656
2657void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2658 OS.EmitLabel(EndLabel);
2659 // Every subsection must be aligned to a 4-byte boundary.
2660 OS.EmitValueToAlignment(4);
2661}
2662
David Majnemer3128b102016-06-15 18:00:01 +00002663void CodeViewDebug::emitDebugInfoForUDTs(
Zachary Turnera7b04172017-08-28 18:49:04 +00002664 ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2665 for (const auto &UDT : UDTs) {
2666 const DIType *T = UDT.second;
2667 assert(shouldEmitUdt(T));
2668
David Majnemer3128b102016-06-15 18:00:01 +00002669 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2670 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2671 OS.AddComment("Record length");
2672 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2673 OS.EmitLabel(UDTRecordBegin);
2674
2675 OS.AddComment("Record kind: S_UDT");
2676 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2677
2678 OS.AddComment("Type");
Zachary Turnera7b04172017-08-28 18:49:04 +00002679 OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
David Majnemer3128b102016-06-15 18:00:01 +00002680
2681 emitNullTerminatedSymbolName(OS, UDT.first);
2682 OS.EmitLabel(UDTRecordEnd);
2683 }
2684}
2685
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002686void CodeViewDebug::emitDebugInfoForGlobals() {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002687 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2688 GlobalMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002689 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002690 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2691 GV.getDebugInfo(GVEs);
2692 for (const auto *GVE : GVEs)
2693 GlobalMap[GVE] = &GV;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002694 }
2695
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002696 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2697 for (const MDNode *Node : CUs->operands()) {
2698 const auto *CU = cast<DICompileUnit>(Node);
2699
2700 // First, emit all globals that are not in a comdat in a single symbol
2701 // substream. MSVC doesn't like it if the substream is empty, so only open
2702 // it if we have at least one global to emit.
2703 switchToDebugSectionForSymbol(nullptr);
2704 MCSymbol *EndLabel = nullptr;
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002705 for (const auto *GVE : CU->getGlobalVariables()) {
2706 if (const auto *GV = GlobalMap.lookup(GVE))
David Majnemer577be0f2016-06-15 00:19:52 +00002707 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002708 if (!EndLabel) {
2709 OS.AddComment("Symbol subsection for globals");
Zachary Turner8c099fe2017-05-30 16:36:15 +00002710 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002711 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002712 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2713 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002714 }
2715 }
2716 if (EndLabel)
2717 endCVSubsection(EndLabel);
2718
2719 // Second, emit each global that is in a comdat into its own .debug$S
2720 // section along with its own symbol substream.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002721 for (const auto *GVE : CU->getGlobalVariables()) {
2722 if (const auto *GV = GlobalMap.lookup(GVE)) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002723 if (GV->hasComdat()) {
2724 MCSymbol *GVSym = Asm->getSymbol(GV);
2725 OS.AddComment("Symbol subsection for " +
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00002726 Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002727 switchToDebugSectionForSymbol(GVSym);
Zachary Turner8c099fe2017-05-30 16:36:15 +00002728 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002729 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2730 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002731 endCVSubsection(EndLabel);
2732 }
2733 }
2734 }
2735 }
2736}
2737
Hans Wennborgb510b452016-06-23 16:33:53 +00002738void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2739 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2740 for (const MDNode *Node : CUs->operands()) {
2741 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2742 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2743 getTypeIndex(RT);
2744 // FIXME: Add to global/local DTU list.
2745 }
2746 }
2747 }
2748}
2749
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002750void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002751 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002752 MCSymbol *GVSym) {
2753 // DataSym record, see SymbolRecord.h for more info.
2754 // FIXME: Thread local data, etc
2755 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2756 *DataEnd = MMI->getContext().createTempSymbol();
Brock Wyma19e17b32018-02-11 21:26:46 +00002757 const unsigned FixedLengthOfThisRecord = 12;
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002758 OS.AddComment("Record length");
2759 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2760 OS.EmitLabel(DataBegin);
David Majnemer7abd2692016-07-06 21:07:47 +00002761 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002762 if (GV->isThreadLocal()) {
2763 OS.AddComment("Record kind: S_LTHREAD32");
2764 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2765 } else {
2766 OS.AddComment("Record kind: S_LDATA32");
2767 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2768 }
David Majnemer7abd2692016-07-06 21:07:47 +00002769 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002770 if (GV->isThreadLocal()) {
2771 OS.AddComment("Record kind: S_GTHREAD32");
2772 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2773 } else {
2774 OS.AddComment("Record kind: S_GDATA32");
2775 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2776 }
David Majnemer7abd2692016-07-06 21:07:47 +00002777 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002778 OS.AddComment("Type");
2779 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2780 OS.AddComment("DataOffset");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00002781 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002782 OS.AddComment("Segment");
2783 OS.EmitCOFFSectionIndex(GVSym);
2784 OS.AddComment("Name");
Brock Wyma19e17b32018-02-11 21:26:46 +00002785 emitNullTerminatedSymbolName(OS, DIGV->getName(), FixedLengthOfThisRecord);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002786 OS.EmitLabel(DataEnd);
2787}