Coverage Report

Created: 2022-01-22 13:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGDebugInfo.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This coordinates the debug information generation while generating code.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGDebugInfo.h"
14
#include "CGBlocks.h"
15
#include "CGCXXABI.h"
16
#include "CGObjCRuntime.h"
17
#include "CGRecordLayout.h"
18
#include "CodeGenFunction.h"
19
#include "CodeGenModule.h"
20
#include "ConstantEmitter.h"
21
#include "clang/AST/ASTContext.h"
22
#include "clang/AST/Attr.h"
23
#include "clang/AST/DeclFriend.h"
24
#include "clang/AST/DeclObjC.h"
25
#include "clang/AST/DeclTemplate.h"
26
#include "clang/AST/Expr.h"
27
#include "clang/AST/RecordLayout.h"
28
#include "clang/AST/RecursiveASTVisitor.h"
29
#include "clang/Basic/CodeGenOptions.h"
30
#include "clang/Basic/FileManager.h"
31
#include "clang/Basic/SourceManager.h"
32
#include "clang/Basic/Version.h"
33
#include "clang/Frontend/FrontendOptions.h"
34
#include "clang/Lex/HeaderSearchOptions.h"
35
#include "clang/Lex/ModuleMap.h"
36
#include "clang/Lex/PreprocessorOptions.h"
37
#include "llvm/ADT/DenseSet.h"
38
#include "llvm/ADT/SmallVector.h"
39
#include "llvm/ADT/StringExtras.h"
40
#include "llvm/IR/Constants.h"
41
#include "llvm/IR/DataLayout.h"
42
#include "llvm/IR/DerivedTypes.h"
43
#include "llvm/IR/Instructions.h"
44
#include "llvm/IR/Intrinsics.h"
45
#include "llvm/IR/Metadata.h"
46
#include "llvm/IR/Module.h"
47
#include "llvm/Support/FileSystem.h"
48
#include "llvm/Support/MD5.h"
49
#include "llvm/Support/Path.h"
50
#include "llvm/Support/TimeProfiler.h"
51
using namespace clang;
52
using namespace clang::CodeGen;
53
54
884k
static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
55
884k
  auto TI = Ctx.getTypeInfo(Ty);
56
884k
  return TI.isAlignRequired() ? 
TI.Align984
:
0883k
;
57
884k
}
58
59
302k
static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
60
302k
  return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
61
302k
}
62
63
925k
static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
64
925k
  return D->hasAttr<AlignedAttr>() ? 
D->getMaxAlignment()1.10k
:
0923k
;
65
925k
}
66
67
CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
68
    : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
69
      DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
70
10.4k
      DBuilder(CGM.getModule()) {
71
10.4k
  for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
72
16
    DebugPrefixMap[KV.first] = KV.second;
73
10.4k
  CreateCompileUnit();
74
10.4k
}
75
76
10.4k
CGDebugInfo::~CGDebugInfo() {
77
10.4k
  assert(LexicalBlockStack.empty() &&
78
10.4k
         "Region stack mismatch, stack not empty!");
79
10.4k
}
80
81
ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
82
                                       SourceLocation TemporaryLocation)
83
288k
    : CGF(&CGF) {
84
288k
  init(TemporaryLocation);
85
288k
}
86
87
ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
88
                                       bool DefaultToEmpty,
89
                                       SourceLocation TemporaryLocation)
90
316k
    : CGF(&CGF) {
91
316k
  init(TemporaryLocation, DefaultToEmpty);
92
316k
}
93
94
void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
95
7.23M
                              bool DefaultToEmpty) {
96
7.23M
  auto *DI = CGF->getDebugInfo();
97
7.23M
  if (!DI) {
98
3.47M
    CGF = nullptr;
99
3.47M
    return;
100
3.47M
  }
101
102
3.76M
  OriginalLocation = CGF->Builder.getCurrentDebugLocation();
103
104
3.76M
  if (OriginalLocation && 
!DI->CGM.getExpressionLocationsEnabled()3.75M
)
105
241
    return;
106
107
3.75M
  if (TemporaryLocation.isValid()) {
108
3.71M
    DI->EmitLocation(CGF->Builder, TemporaryLocation);
109
3.71M
    return;
110
3.71M
  }
111
112
39.8k
  if (DefaultToEmpty) {
113
28.0k
    CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
114
28.0k
    return;
115
28.0k
  }
116
117
  // Construct a location that has a valid scope, but no line info.
118
11.8k
  assert(!DI->LexicalBlockStack.empty());
119
0
  CGF->Builder.SetCurrentDebugLocation(
120
11.8k
      llvm::DILocation::get(DI->LexicalBlockStack.back()->getContext(), 0, 0,
121
11.8k
                            DI->LexicalBlockStack.back(), DI->getInlinedAt()));
122
11.8k
}
123
124
ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
125
6.62M
    : CGF(&CGF) {
126
6.62M
  init(E->getExprLoc());
127
6.62M
}
128
129
ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
130
312k
    : CGF(&CGF) {
131
312k
  if (!CGF.getDebugInfo()) {
132
208k
    this->CGF = nullptr;
133
208k
    return;
134
208k
  }
135
103k
  OriginalLocation = CGF.Builder.getCurrentDebugLocation();
136
103k
  if (Loc)
137
48.8k
    CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
138
103k
}
139
140
7.54M
ApplyDebugLocation::~ApplyDebugLocation() {
141
  // Query CGF so the location isn't overwritten when location updates are
142
  // temporarily disabled (for C++ default function arguments)
143
7.54M
  if (CGF)
144
3.86M
    CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
145
7.54M
}
146
147
ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF,
148
                                                   GlobalDecl InlinedFn)
149
47
    : CGF(&CGF) {
150
47
  if (!CGF.getDebugInfo()) {
151
44
    this->CGF = nullptr;
152
44
    return;
153
44
  }
154
3
  auto &DI = *CGF.getDebugInfo();
155
3
  SavedLocation = DI.getLocation();
156
3
  assert((DI.getInlinedAt() ==
157
3
          CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
158
3
         "CGDebugInfo and IRBuilder are out of sync");
159
160
0
  DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
161
3
}
162
163
47
ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
164
47
  if (!CGF)
165
44
    return;
166
3
  auto &DI = *CGF->getDebugInfo();
167
3
  DI.EmitInlineFunctionEnd(CGF->Builder);
168
3
  DI.EmitLocation(CGF->Builder, SavedLocation);
169
3
}
170
171
5.06M
void CGDebugInfo::setLocation(SourceLocation Loc) {
172
  // If the new location isn't valid return.
173
5.06M
  if (Loc.isInvalid())
174
3.67k
    return;
175
176
5.06M
  CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
177
178
  // If we've changed files in the middle of a lexical scope go ahead
179
  // and create a new lexical scope with file node if it's different
180
  // from the one in the scope.
181
5.06M
  if (LexicalBlockStack.empty())
182
4.66k
    return;
183
184
5.06M
  SourceManager &SM = CGM.getContext().getSourceManager();
185
5.06M
  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
186
5.06M
  PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
187
5.06M
  if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))
188
5.06M
    return;
189
190
190
  if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
191
6
    LexicalBlockStack.pop_back();
192
6
    LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
193
6
        LBF->getScope(), getOrCreateFile(CurLoc)));
194
184
  } else if (isa<llvm::DILexicalBlock>(Scope) ||
195
184
             isa<llvm::DISubprogram>(Scope)) {
196
184
    LexicalBlockStack.pop_back();
197
184
    LexicalBlockStack.emplace_back(
198
184
        DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
199
184
  }
200
190
}
201
202
834k
llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
203
834k
  llvm::DIScope *Mod = getParentModuleOrNull(D);
204
834k
  return getContextDescriptor(cast<Decl>(D->getDeclContext()),
205
834k
                              Mod ? 
Mod405k
:
TheCU429k
);
206
834k
}
207
208
llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
209
1.15M
                                                 llvm::DIScope *Default) {
210
1.15M
  if (!Context)
211
0
    return Default;
212
213
1.15M
  auto I = RegionMap.find(Context);
214
1.15M
  if (I != RegionMap.end()) {
215
198k
    llvm::Metadata *V = I->second;
216
198k
    return dyn_cast_or_null<llvm::DIScope>(V);
217
198k
  }
218
219
  // Check namespace.
220
952k
  if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
221
285k
    return getOrCreateNamespace(NSDecl);
222
223
667k
  if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
224
11.7k
    if (!RDecl->isDependentType())
225
9.62k
      return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
226
9.62k
                             TheCU->getFile());
227
657k
  return Default;
228
667k
}
229
230
783k
PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
231
783k
  PrintingPolicy PP = CGM.getContext().getPrintingPolicy();
232
233
  // If we're emitting codeview, it's important to try to match MSVC's naming so
234
  // that visualizers written for MSVC will trigger for our class names. In
235
  // particular, we can't have spaces between arguments of standard templates
236
  // like basic_string and vector, but we must have spaces between consecutive
237
  // angle brackets that close nested template argument lists.
238
783k
  if (CGM.getCodeGenOpts().EmitCodeView) {
239
375
    PP.MSVCFormatting = true;
240
375
    PP.SplitTemplateClosers = true;
241
783k
  } else {
242
    // For DWARF, printing rules are underspecified.
243
    // SplitTemplateClosers yields better interop with GCC and GDB (PR46052).
244
783k
    PP.SplitTemplateClosers = true;
245
783k
  }
246
247
783k
  PP.SuppressInlineNamespace = false;
248
783k
  PP.PrintCanonicalTypes = true;
249
783k
  PP.UsePreferredNames = false;
250
783k
  PP.AlwaysIncludeTypeForTemplateArgument = true;
251
252
  // Apply -fdebug-prefix-map.
253
783k
  PP.Callbacks = &PrintCB;
254
783k
  return PP;
255
783k
}
256
257
709k
StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
258
709k
  return internString(GetName(FD));
259
709k
}
260
261
13.5k
StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
262
13.5k
  SmallString<256> MethodName;
263
13.5k
  llvm::raw_svector_ostream OS(MethodName);
264
13.5k
  OS << (OMD->isInstanceMethod() ? 
'-'10.9k
:
'+'2.53k
) << '[';
265
13.5k
  const DeclContext *DC = OMD->getDeclContext();
266
13.5k
  if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
267
1.34k
    OS << OID->getName();
268
12.1k
  } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
269
8.28k
    OS << OID->getName();
270
8.28k
  } else 
if (const auto *3.88k
OC3.88k
= dyn_cast<ObjCCategoryDecl>(DC)) {
271
3.86k
    if (OC->IsClassExtension()) {
272
48
      OS << OC->getClassInterface()->getName();
273
3.81k
    } else {
274
3.81k
      OS << OC->getIdentifier()->getNameStart() << '('
275
3.81k
         << OC->getIdentifier()->getNameStart() << ')';
276
3.81k
    }
277
3.86k
  } else 
if (const auto *22
OCD22
= dyn_cast<ObjCCategoryImplDecl>(DC)) {
278
22
    OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
279
22
  }
280
13.5k
  OS << ' ' << OMD->getSelector().getAsString() << ']';
281
282
13.5k
  return internString(OS.str());
283
13.5k
}
284
285
618
StringRef CGDebugInfo::getSelectorName(Selector S) {
286
618
  return internString(S.getAsString());
287
618
}
288
289
145k
StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
290
145k
  if (isa<ClassTemplateSpecializationDecl>(RD)) {
291
    // Copy this name on the side and use its reference.
292
71.3k
    return internString(GetName(RD));
293
71.3k
  }
294
295
  // quick optimization to avoid having to intern strings that are already
296
  // stored reliably elsewhere
297
74.4k
  if (const IdentifierInfo *II = RD->getIdentifier())
298
56.6k
    return II->getName();
299
300
  // The CodeView printer in LLVM wants to see the names of unnamed types
301
  // because they need to have a unique identifier.
302
  // These names are used to reconstruct the fully qualified type names.
303
17.7k
  if (CGM.getCodeGenOpts().EmitCodeView) {
304
26
    if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
305
1
      assert(RD->getDeclContext() == D->getDeclContext() &&
306
1
             "Typedef should not be in another decl context!");
307
0
      assert(D->getDeclName().getAsIdentifierInfo() &&
308
1
             "Typedef was not named!");
309
0
      return D->getDeclName().getAsIdentifierInfo()->getName();
310
1
    }
311
312
25
    if (CGM.getLangOpts().CPlusPlus) {
313
24
      StringRef Name;
314
315
24
      ASTContext &Context = CGM.getContext();
316
24
      if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
317
        // Anonymous types without a name for linkage purposes have their
318
        // declarator mangled in if they have one.
319
6
        Name = DD->getName();
320
18
      else if (const TypedefNameDecl *TND =
321
18
                   Context.getTypedefNameForUnnamedTagDecl(RD))
322
        // Anonymous types without a name for linkage purposes have their
323
        // associate typedef mangled in if they have one.
324
1
        Name = TND->getName();
325
326
      // Give lambdas a display name based on their name mangling.
327
24
      if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
328
24
        if (CXXRD->isLambda())
329
16
          return internString(
330
16
              CGM.getCXXABI().getMangleContext().getLambdaString(CXXRD));
331
332
8
      if (!Name.empty()) {
333
7
        SmallString<256> UnnamedType("<unnamed-type-");
334
7
        UnnamedType += Name;
335
7
        UnnamedType += '>';
336
7
        return internString(UnnamedType);
337
7
      }
338
8
    }
339
25
  }
340
341
17.7k
  return StringRef();
342
17.7k
}
343
344
Optional<llvm::DIFile::ChecksumKind>
345
88.2k
CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
346
88.2k
  Checksum.clear();
347
348
88.2k
  if (!CGM.getCodeGenOpts().EmitCodeView &&
349
88.2k
      
CGM.getCodeGenOpts().DwarfVersion < 588.1k
)
350
88.0k
    return None;
351
352
180
  SourceManager &SM = CGM.getContext().getSourceManager();
353
180
  Optional<llvm::MemoryBufferRef> MemBuffer = SM.getBufferOrNone(FID);
354
180
  if (!MemBuffer)
355
15
    return None;
356
357
165
  llvm::toHex(
358
165
      llvm::MD5::hash(llvm::arrayRefFromStringRef(MemBuffer->getBuffer())),
359
165
      /*LowerCase*/ true, Checksum);
360
165
  return llvm::DIFile::CSK_MD5;
361
180
}
362
363
Optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
364
88.6k
                                           FileID FID) {
365
88.6k
  if (!CGM.getCodeGenOpts().EmbedSource)
366
88.6k
    return None;
367
368
2
  bool SourceInvalid = false;
369
2
  StringRef Source = SM.getBufferData(FID, &SourceInvalid);
370
371
2
  if (SourceInvalid)
372
0
    return None;
373
374
2
  return Source;
375
2
}
376
377
7.47M
llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
378
7.47M
  SourceManager &SM = CGM.getContext().getSourceManager();
379
7.47M
  StringRef FileName;
380
7.47M
  FileID FID;
381
382
7.47M
  if (Loc.isInvalid()) {
383
    // The DIFile used by the CU is distinct from the main source file. Call
384
    // createFile() below for canonicalization if the source file was specified
385
    // with an absolute path.
386
8.58k
    FileName = TheCU->getFile()->getFilename();
387
7.46M
  } else {
388
7.46M
    PresumedLoc PLoc = SM.getPresumedLoc(Loc);
389
7.46M
    FileName = PLoc.getFilename();
390
391
7.46M
    if (FileName.empty()) {
392
8
      FileName = TheCU->getFile()->getFilename();
393
7.46M
    } else {
394
7.46M
      FileName = PLoc.getFilename();
395
7.46M
    }
396
7.46M
    FID = PLoc.getFileID();
397
7.46M
  }
398
399
  // Cache the results.
400
7.47M
  auto It = DIFileCache.find(FileName.data());
401
7.47M
  if (It != DIFileCache.end()) {
402
    // Verify that the information still exists.
403
7.39M
    if (llvm::Metadata *V = It->second)
404
7.39M
      return cast<llvm::DIFile>(V);
405
7.39M
  }
406
407
78.1k
  SmallString<32> Checksum;
408
409
78.1k
  Optional<llvm::DIFile::ChecksumKind> CSKind = computeChecksum(FID, Checksum);
410
78.1k
  Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
411
78.1k
  if (CSKind)
412
83
    CSInfo.emplace(*CSKind, Checksum);
413
78.1k
  return createFile(FileName, CSInfo, getSource(SM, SM.getFileID(Loc)));
414
7.47M
}
415
416
llvm::DIFile *
417
CGDebugInfo::createFile(StringRef FileName,
418
                        Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
419
78.1k
                        Optional<StringRef> Source) {
420
78.1k
  StringRef Dir;
421
78.1k
  StringRef File;
422
78.1k
  std::string RemappedFile = remapDIPath(FileName);
423
78.1k
  std::string CurDir = remapDIPath(getCurrentDirname());
424
78.1k
  SmallString<128> DirBuf;
425
78.1k
  SmallString<128> FileBuf;
426
78.1k
  if (llvm::sys::path::is_absolute(RemappedFile)) {
427
    // Strip the common prefix (if it is more than just "/") from current
428
    // directory and FileName for a more space-efficient encoding.
429
74.4k
    auto FileIt = llvm::sys::path::begin(RemappedFile);
430
74.4k
    auto FileE = llvm::sys::path::end(RemappedFile);
431
74.4k
    auto CurDirIt = llvm::sys::path::begin(CurDir);
432
74.4k
    auto CurDirE = llvm::sys::path::end(CurDir);
433
355k
    for (; CurDirIt != CurDirE && 
*CurDirIt == *FileIt355k
;
++CurDirIt, ++FileIt280k
)
434
280k
      llvm::sys::path::append(DirBuf, *CurDirIt);
435
74.4k
    if (std::distance(llvm::sys::path::begin(CurDir), CurDirIt) == 1) {
436
      // Don't strip the common prefix if it is only the root "/"
437
      // since that would make LLVM diagnostic locations confusing.
438
38.9k
      Dir = {};
439
38.9k
      File = RemappedFile;
440
38.9k
    } else {
441
268k
      for (; FileIt != FileE; 
++FileIt233k
)
442
233k
        llvm::sys::path::append(FileBuf, *FileIt);
443
35.5k
      Dir = DirBuf;
444
35.5k
      File = FileBuf;
445
35.5k
    }
446
74.4k
  } else {
447
3.68k
    Dir = CurDir;
448
3.68k
    File = RemappedFile;
449
3.68k
  }
450
78.1k
  llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
451
78.1k
  DIFileCache[FileName.data()].reset(F);
452
78.1k
  return F;
453
78.1k
}
454
455
220k
std::string CGDebugInfo::remapDIPath(StringRef Path) const {
456
220k
  if (DebugPrefixMap.empty())
457
220k
    return Path.str();
458
459
108
  SmallString<256> P = Path;
460
108
  for (const auto &Entry : DebugPrefixMap)
461
123
    if (llvm::sys::path::replace_path_prefix(P, Entry.first, Entry.second))
462
43
      break;
463
108
  return P.str().str();
464
220k
}
465
466
7.16M
unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
467
7.16M
  if (Loc.isInvalid())
468
8.41k
    return 0;
469
7.15M
  SourceManager &SM = CGM.getContext().getSourceManager();
470
7.15M
  return SM.getPresumedLoc(Loc).getLine();
471
7.16M
}
472
473
5.40M
unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
474
  // We may not want column information at all.
475
5.40M
  if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
476
3.44M
    return 0;
477
478
  // If the location is invalid then use the current column.
479
1.95M
  if (Loc.isInvalid() && 
CurLoc.isInvalid()39
)
480
4
    return 0;
481
1.95M
  SourceManager &SM = CGM.getContext().getSourceManager();
482
1.95M
  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? 
Loc1.95M
:
CurLoc35
);
483
1.95M
  return PLoc.isValid() ? PLoc.getColumn() : 
00
;
484
1.95M
}
485
486
88.6k
StringRef CGDebugInfo::getCurrentDirname() {
487
88.6k
  if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
488
47.7k
    return CGM.getCodeGenOpts().DebugCompilationDir;
489
490
40.9k
  if (!CWDName.empty())
491
33.8k
    return CWDName;
492
7.02k
  SmallString<256> CWD;
493
7.02k
  llvm::sys::fs::current_path(CWD);
494
7.02k
  return CWDName = internString(CWD);
495
40.9k
}
496
497
10.4k
void CGDebugInfo::CreateCompileUnit() {
498
10.4k
  SmallString<32> Checksum;
499
10.4k
  Optional<llvm::DIFile::ChecksumKind> CSKind;
500
10.4k
  Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
501
502
  // Should we be asking the SourceManager for the main file name, instead of
503
  // accepting it as an argument? This just causes the main file name to
504
  // mismatch with source locations and create extra lexical scopes or
505
  // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
506
  // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
507
  // because that's what the SourceManager says)
508
509
  // Get absolute path name.
510
10.4k
  SourceManager &SM = CGM.getContext().getSourceManager();
511
10.4k
  std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
512
10.4k
  if (MainFileName.empty())
513
6.74k
    MainFileName = "<stdin>";
514
515
  // The main file name provided via the "-main-file-name" option contains just
516
  // the file name itself with no path information. This file name may have had
517
  // a relative path, so we look into the actual file entry for the main
518
  // file to determine the real absolute path for the file.
519
10.4k
  std::string MainFileDir;
520
10.4k
  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
521
10.0k
    MainFileDir = std::string(MainFile->getDir()->getName());
522
10.0k
    if (!llvm::sys::path::is_absolute(MainFileName)) {
523
10.0k
      llvm::SmallString<1024> MainFileDirSS(MainFileDir);
524
10.0k
      llvm::sys::path::append(MainFileDirSS, MainFileName);
525
10.0k
      MainFileName =
526
10.0k
          std::string(llvm::sys::path::remove_leading_dotslash(MainFileDirSS));
527
10.0k
    }
528
    // If the main file name provided is identical to the input file name, and
529
    // if the input file is a preprocessed source, use the module name for
530
    // debug info. The module name comes from the name specified in the first
531
    // linemarker if the input is a preprocessed source.
532
10.0k
    if (MainFile->getName() == MainFileName &&
533
10.0k
        FrontendOptions::getInputKindForExtension(
534
3.42k
            MainFile->getName().rsplit('.').second)
535
3.42k
            .isPreprocessed())
536
1
      MainFileName = CGM.getModule().getName().str();
537
538
10.0k
    CSKind = computeChecksum(SM.getMainFileID(), Checksum);
539
10.0k
  }
540
541
10.4k
  llvm::dwarf::SourceLanguage LangTag;
542
10.4k
  const LangOptions &LO = CGM.getLangOpts();
543
10.4k
  if (LO.CPlusPlus) {
544
8.54k
    if (LO.ObjC)
545
6.04k
      LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
546
2.49k
    else if (LO.CPlusPlus14 && 
(341
!CGM.getCodeGenOpts().DebugStrictDwarf341
||
547
341
                                
CGM.getCodeGenOpts().DwarfVersion >= 52
))
548
340
      LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
549
2.15k
    else if (LO.CPlusPlus11 && 
(2.13k
!CGM.getCodeGenOpts().DebugStrictDwarf2.13k
||
550
2.13k
                                
CGM.getCodeGenOpts().DwarfVersion >= 53
))
551
2.13k
      LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
552
24
    else
553
24
      LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
554
8.54k
  } else 
if (1.91k
LO.ObjC1.91k
) {
555
562
    LangTag = llvm::dwarf::DW_LANG_ObjC;
556
1.35k
  } else if (LO.OpenCL && 
(10
!CGM.getCodeGenOpts().DebugStrictDwarf10
||
557
10
                           
CGM.getCodeGenOpts().DwarfVersion >= 52
)) {
558
9
    LangTag = llvm::dwarf::DW_LANG_OpenCL;
559
1.34k
  } else if (LO.RenderScript) {
560
1
    LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
561
1.34k
  } else if (LO.C99) {
562
1.34k
    LangTag = llvm::dwarf::DW_LANG_C99;
563
1.34k
  } else {
564
0
    LangTag = llvm::dwarf::DW_LANG_C89;
565
0
  }
566
567
10.4k
  std::string Producer = getClangFullVersion();
568
569
  // Figure out which version of the ObjC runtime we have.
570
10.4k
  unsigned RuntimeVers = 0;
571
10.4k
  if (LO.ObjC)
572
6.61k
    RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 
26.60k
:
16
;
573
574
10.4k
  llvm::DICompileUnit::DebugEmissionKind EmissionKind;
575
10.4k
  switch (DebugKind) {
576
15
  case codegenoptions::NoDebugInfo:
577
72
  case codegenoptions::LocTrackingOnly:
578
72
    EmissionKind = llvm::DICompileUnit::NoDebug;
579
72
    break;
580
70
  case codegenoptions::DebugLineTablesOnly:
581
70
    EmissionKind = llvm::DICompileUnit::LineTablesOnly;
582
70
    break;
583
19
  case codegenoptions::DebugDirectivesOnly:
584
19
    EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
585
19
    break;
586
109
  case codegenoptions::DebugInfoConstructor:
587
593
  case codegenoptions::LimitedDebugInfo:
588
10.2k
  case codegenoptions::FullDebugInfo:
589
10.2k
  case codegenoptions::UnusedTypeInfo:
590
10.2k
    EmissionKind = llvm::DICompileUnit::FullDebug;
591
10.2k
    break;
592
10.4k
  }
593
594
10.4k
  uint64_t DwoId = 0;
595
10.4k
  auto &CGOpts = CGM.getCodeGenOpts();
596
  // The DIFile used by the CU is distinct from the main source
597
  // file. Its directory part specifies what becomes the
598
  // DW_AT_comp_dir (the compilation directory), even if the source
599
  // file was specified with an absolute path.
600
10.4k
  if (CSKind)
601
82
    CSInfo.emplace(*CSKind, Checksum);
602
10.4k
  llvm::DIFile *CUFile = DBuilder.createFile(
603
10.4k
      remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
604
10.4k
      getSource(SM, SM.getMainFileID()));
605
606
10.4k
  StringRef Sysroot, SDK;
607
10.4k
  if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) {
608
3.57k
    Sysroot = CGM.getHeaderSearchOpts().Sysroot;
609
3.57k
    auto B = llvm::sys::path::rbegin(Sysroot);
610
3.57k
    auto E = llvm::sys::path::rend(Sysroot);
611
3.61k
    auto It = std::find_if(B, E, [](auto SDK) { return SDK.endswith(".sdk"); });
612
3.57k
    if (It != E)
613
3.49k
      SDK = *It;
614
3.57k
  }
615
616
  // Create new compile unit.
617
10.4k
  TheCU = DBuilder.createCompileUnit(
618
10.4k
      LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? 
Producer10.4k
:
""2
,
619
10.4k
      LO.Optimize || 
CGOpts.PrepareForLTO10.2k
||
CGOpts.PrepareForThinLTO10.2k
,
620
10.4k
      CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
621
10.4k
      DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
622
10.4k
      CGM.getTarget().getTriple().isNVPTX()
623
10.4k
          ? 
llvm::DICompileUnit::DebugNameTableKind::None12
624
10.4k
          : static_cast<llvm::DICompileUnit::DebugNameTableKind>(
625
10.4k
                CGOpts.DebugNameTable),
626
10.4k
      CGOpts.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);
627
10.4k
}
628
629
177k
llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
630
177k
  llvm::dwarf::TypeKind Encoding;
631
177k
  StringRef BTName;
632
177k
  switch (BT->getKind()) {
633
0
#define BUILTIN_TYPE(Id, SingletonId)
634
0
#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
635
0
#include "clang/AST/BuiltinTypes.def"
636
0
  case BuiltinType::Dependent:
637
0
    llvm_unreachable("Unexpected builtin type");
638
592
  case BuiltinType::NullPtr:
639
592
    return DBuilder.createNullPtrType();
640
137k
  case BuiltinType::Void:
641
137k
    return nullptr;
642
2.70k
  case BuiltinType::ObjCClass:
643
2.70k
    if (!ClassTy)
644
2.55k
      ClassTy =
645
2.55k
          DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
646
2.55k
                                     "objc_class", TheCU, TheCU->getFile(), 0);
647
2.70k
    return ClassTy;
648
857
  case BuiltinType::ObjCId: {
649
    // typedef struct objc_class *Class;
650
    // typedef struct objc_object {
651
    //  Class isa;
652
    // } *id;
653
654
857
    if (ObjTy)
655
0
      return ObjTy;
656
657
857
    if (!ClassTy)
658
822
      ClassTy =
659
822
          DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
660
822
                                     "objc_class", TheCU, TheCU->getFile(), 0);
661
662
857
    unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
663
664
857
    auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
665
666
857
    ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
667
857
                                      0, 0, llvm::DINode::FlagZero, nullptr,
668
857
                                      llvm::DINodeArray());
669
670
857
    DBuilder.replaceArrays(
671
857
        ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
672
857
                   ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
673
857
                   llvm::DINode::FlagZero, ISATy)));
674
857
    return ObjTy;
675
857
  }
676
342
  case BuiltinType::ObjCSel: {
677
342
    if (!SelTy)
678
342
      SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
679
342
                                         "objc_selector", TheCU,
680
342
                                         TheCU->getFile(), 0);
681
342
    return SelTy;
682
857
  }
683
684
0
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
685
0
  case BuiltinType::Id:                                                        \
686
0
    return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t",       \
687
0
                                    SingletonId);
688
342
#include "clang/Basic/OpenCLImageTypes.def"
689
0
  case BuiltinType::OCLSampler:
690
0
    return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
691
0
  case BuiltinType::OCLEvent:
692
0
    return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
693
0
  case BuiltinType::OCLClkEvent:
694
0
    return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
695
1
  case BuiltinType::OCLQueue:
696
1
    return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
697
0
  case BuiltinType::OCLReserveID:
698
0
    return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
699
0
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
700
0
  case BuiltinType::Id: \
701
0
    return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
702
0
#include "clang/Basic/OpenCLExtensionTypes.def"
703
704
1.14k
#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
705
45
#include 
"clang/Basic/AArch64SVEACLETypes.def"0
706
45
    {
707
45
      ASTContext::BuiltinVectorTypeInfo Info =
708
45
          CGM.getContext().getBuiltinVectorTypeInfo(BT);
709
45
      unsigned NumElemsPerVG = (Info.EC.getKnownMinValue() * Info.NumVectors) / 2;
710
711
      // Debuggers can't extract 1bit from a vector, so will display a
712
      // bitpattern for svbool_t instead.
713
45
      if (Info.ElementType == CGM.getContext().BoolTy) {
714
1
        NumElemsPerVG /= 8;
715
1
        Info.ElementType = CGM.getContext().UnsignedCharTy;
716
1
      }
717
718
45
      auto *LowerBound =
719
45
          llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
720
45
              llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
721
45
      SmallVector<uint64_t, 9> Expr(
722
45
          {llvm::dwarf::DW_OP_constu, NumElemsPerVG, llvm::dwarf::DW_OP_bregx,
723
45
           /* AArch64::VG */ 46, 0, llvm::dwarf::DW_OP_mul,
724
45
           llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
725
45
      auto *UpperBound = DBuilder.createExpression(Expr);
726
727
45
      llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
728
45
          /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
729
45
      llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
730
45
      llvm::DIType *ElemTy =
731
45
          getOrCreateType(Info.ElementType, TheCU->getFile());
732
45
      auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
733
45
      return DBuilder.createVectorType(/*Size*/ 0, Align, ElemTy,
734
45
                                       SubscriptArray);
735
1.10k
    }
736
  // It doesn't make sense to generate debug info for PowerPC MMA vector types.
737
  // So we return a safe type here to avoid generating an error.
738
0
#define PPC_VECTOR_TYPE(Name, Id, size) \
739
0
  case BuiltinType::Id:
740
45
#include "clang/Basic/PPCTypes.def"
741
0
    return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));
742
743
140
#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
744
3
#include 
"clang/Basic/RISCVVTypes.def"0
745
3
    {
746
3
      ASTContext::BuiltinVectorTypeInfo Info =
747
3
          CGM.getContext().getBuiltinVectorTypeInfo(BT);
748
749
3
      unsigned ElementCount = Info.EC.getKnownMinValue();
750
3
      unsigned SEW = CGM.getContext().getTypeSize(Info.ElementType);
751
752
3
      bool Fractional = false;
753
3
      unsigned LMUL;
754
3
      unsigned FixedSize = ElementCount * SEW;
755
3
      if (Info.ElementType == CGM.getContext().BoolTy) {
756
        // Mask type only occupies one vector register.
757
0
        LMUL = 1;
758
3
      } else if (FixedSize < 64) {
759
        // In RVV scalable vector types, we encode 64 bits in the fixed part.
760
2
        Fractional = true;
761
2
        LMUL = 64 / FixedSize;
762
2
      } else {
763
1
        LMUL = FixedSize / 64;
764
1
      }
765
766
      // Element count = (VLENB / SEW) x LMUL
767
3
      SmallVector<uint64_t, 12> Expr(
768
          // The DW_OP_bregx operation has two operands: a register which is
769
          // specified by an unsigned LEB128 number, followed by a signed LEB128
770
          // offset.
771
3
          {llvm::dwarf::DW_OP_bregx, // Read the contents of a register.
772
3
           4096 + 0xC22,             // RISC-V VLENB CSR register.
773
3
           0, // Offset for DW_OP_bregx. It is dummy here.
774
3
           llvm::dwarf::DW_OP_constu,
775
3
           SEW / 8, // SEW is in bits.
776
3
           llvm::dwarf::DW_OP_div, llvm::dwarf::DW_OP_constu, LMUL});
777
3
      if (Fractional)
778
2
        Expr.push_back(llvm::dwarf::DW_OP_div);
779
1
      else
780
1
        Expr.push_back(llvm::dwarf::DW_OP_mul);
781
      // Element max index = count - 1
782
3
      Expr.append({llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
783
784
3
      auto *LowerBound =
785
3
          llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
786
3
              llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
787
3
      auto *UpperBound = DBuilder.createExpression(Expr);
788
3
      llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
789
3
          /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
790
3
      llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
791
3
      llvm::DIType *ElemTy =
792
3
          getOrCreateType(Info.ElementType, TheCU->getFile());
793
794
3
      auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
795
3
      return DBuilder.createVectorType(/*Size=*/0, Align, ElemTy,
796
3
                                       SubscriptArray);
797
137
    }
798
3.80k
  case BuiltinType::UChar:
799
3.80k
  case BuiltinType::Char_U:
800
3.80k
    Encoding = llvm::dwarf::DW_ATE_unsigned_char;
801
3.80k
    break;
802
4.69k
  case BuiltinType::Char_S:
803
5.92k
  case BuiltinType::SChar:
804
5.92k
    Encoding = llvm::dwarf::DW_ATE_signed_char;
805
5.92k
    break;
806
7
  case BuiltinType::Char8:
807
36
  case BuiltinType::Char16:
808
64
  case BuiltinType::Char32:
809
64
    Encoding = llvm::dwarf::DW_ATE_UTF;
810
64
    break;
811
714
  case BuiltinType::UShort:
812
6.64k
  case BuiltinType::UInt:
813
6.66k
  case BuiltinType::UInt128:
814
11.4k
  case BuiltinType::ULong:
815
11.4k
  case BuiltinType::WChar_U:
816
13.4k
  case BuiltinType::ULongLong:
817
13.4k
    Encoding = llvm::dwarf::DW_ATE_unsigned;
818
13.4k
    break;
819
841
  case BuiltinType::Short:
820
6.49k
  case BuiltinType::Int:
821
6.51k
  case BuiltinType::Int128:
822
7.54k
  case BuiltinType::Long:
823
8.14k
  case BuiltinType::WChar_S:
824
8.98k
  case BuiltinType::LongLong:
825
8.98k
    Encoding = llvm::dwarf::DW_ATE_signed;
826
8.98k
    break;
827
726
  case BuiltinType::Bool:
828
726
    Encoding = llvm::dwarf::DW_ATE_boolean;
829
726
    break;
830
7
  case BuiltinType::Half:
831
907
  case BuiltinType::Float:
832
1.59k
  case BuiltinType::LongDouble:
833
1.59k
  case BuiltinType::Float16:
834
1.59k
  case BuiltinType::BFloat16:
835
1.59k
  case BuiltinType::Float128:
836
2.48k
  case BuiltinType::Double:
837
2.48k
  case BuiltinType::Ibm128:
838
    // FIXME: For targets where long double, __ibm128 and __float128 have the
839
    // same size, they are currently indistinguishable in the debugger without
840
    // some special treatment. However, there is currently no consensus on
841
    // encoding and this should be updated once a DWARF encoding exists for
842
    // distinct floating point types of the same size.
843
2.48k
    Encoding = llvm::dwarf::DW_ATE_float;
844
2.48k
    break;
845
0
  case BuiltinType::ShortAccum:
846
0
  case BuiltinType::Accum:
847
0
  case BuiltinType::LongAccum:
848
0
  case BuiltinType::ShortFract:
849
0
  case BuiltinType::Fract:
850
0
  case BuiltinType::LongFract:
851
0
  case BuiltinType::SatShortFract:
852
0
  case BuiltinType::SatFract:
853
0
  case BuiltinType::SatLongFract:
854
0
  case BuiltinType::SatShortAccum:
855
0
  case BuiltinType::SatAccum:
856
0
  case BuiltinType::SatLongAccum:
857
0
    Encoding = llvm::dwarf::DW_ATE_signed_fixed;
858
0
    break;
859
0
  case BuiltinType::UShortAccum:
860
0
  case BuiltinType::UAccum:
861
0
  case BuiltinType::ULongAccum:
862
0
  case BuiltinType::UShortFract:
863
0
  case BuiltinType::UFract:
864
0
  case BuiltinType::ULongFract:
865
0
  case BuiltinType::SatUShortAccum:
866
0
  case BuiltinType::SatUAccum:
867
0
  case BuiltinType::SatULongAccum:
868
0
  case BuiltinType::SatUShortFract:
869
0
  case BuiltinType::SatUFract:
870
0
  case BuiltinType::SatULongFract:
871
0
    Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
872
0
    break;
873
177k
  }
874
875
35.4k
  BTName = BT->getName(CGM.getLangOpts());
876
  // Bit size and offset of the type.
877
35.4k
  uint64_t Size = CGM.getContext().getTypeSize(BT);
878
35.4k
  return DBuilder.createBasicType(BTName, Size, Encoding);
879
177k
}
880
881
13
llvm::DIType *CGDebugInfo::CreateType(const AutoType *Ty) {
882
13
  return DBuilder.createUnspecifiedType("auto");
883
13
}
884
885
0
llvm::DIType *CGDebugInfo::CreateType(const BitIntType *Ty) {
886
887
0
  StringRef Name = Ty->isUnsigned() ? "unsigned _BitInt" : "_BitInt";
888
0
  llvm::dwarf::TypeKind Encoding = Ty->isUnsigned()
889
0
                                       ? llvm::dwarf::DW_ATE_unsigned
890
0
                                       : llvm::dwarf::DW_ATE_signed;
891
892
0
  return DBuilder.createBasicType(Name, CGM.getContext().getTypeSize(Ty),
893
0
                                  Encoding);
894
0
}
895
896
96
llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
897
  // Bit size and offset of the type.
898
96
  llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
899
96
  if (Ty->isComplexIntegerType())
900
18
    Encoding = llvm::dwarf::DW_ATE_lo_user;
901
902
96
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
903
96
  return DBuilder.createBasicType("complex", Size, Encoding);
904
96
}
905
906
459k
static void stripUnusedQualifiers(Qualifiers &Q) {
907
  // Ignore these qualifiers for now.
908
459k
  Q.removeObjCGCAttr();
909
459k
  Q.removeAddressSpace();
910
459k
  Q.removeObjCLifetime();
911
459k
  Q.removeUnaligned();
912
459k
}
913
914
459k
static llvm::dwarf::Tag getNextQualifier(Qualifiers &Q) {
915
459k
  if (Q.hasConst()) {
916
69.0k
    Q.removeConst();
917
69.0k
    return llvm::dwarf::DW_TAG_const_type;
918
69.0k
  }
919
389k
  if (Q.hasVolatile()) {
920
1.61k
    Q.removeVolatile();
921
1.61k
    return llvm::dwarf::DW_TAG_volatile_type;
922
1.61k
  }
923
388k
  if (Q.hasRestrict()) {
924
894
    Q.removeRestrict();
925
894
    return llvm::dwarf::DW_TAG_restrict_type;
926
894
  }
927
387k
  return (llvm::dwarf::Tag)0;
928
388k
}
929
930
// Strip MacroQualifiedTypeLoc and AttributedTypeLoc
931
// as their corresponding types will be ignored
932
// during code generation. Stripping them allows
933
// to maintain proper TypeLoc for a given type
934
// during code generation.
935
112k
static TypeLoc StripMacroAttributed(TypeLoc TL) {
936
112k
  if (!TL)
937
733
    return TL;
938
939
112k
  
while (112k
true) {
940
112k
    if (auto MTL = TL.getAs<MacroQualifiedTypeLoc>())
941
14
      TL = MTL.getInnerLoc();
942
112k
    else if (auto ATL = TL.getAs<AttributedTypeLoc>())
943
95
      TL = ATL.getModifiedLoc();
944
112k
    else
945
112k
      break;
946
112k
  }
947
112k
  return TL;
948
112k
}
949
950
llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile *Unit,
951
71.6k
                                               TypeLoc TL) {
952
71.6k
  QualifierCollector Qc;
953
71.6k
  const Type *T = Qc.strip(Ty);
954
955
71.6k
  stripUnusedQualifiers(Qc);
956
957
  // We will create one Derived type for one qualifier and recurse to handle any
958
  // additional ones.
959
71.6k
  llvm::dwarf::Tag Tag = getNextQualifier(Qc);
960
71.6k
  if (!Tag) {
961
72
    assert(Qc.empty() && "Unknown type qualifier for debug info");
962
0
    return getOrCreateType(QualType(T, 0), Unit);
963
72
  }
964
965
71.5k
  QualType NextTy = Qc.apply(CGM.getContext(), T);
966
71.5k
  TypeLoc NextTL;
967
71.5k
  if (NextTy.hasQualifiers())
968
372
    NextTL = TL;
969
71.2k
  else if (TL) {
970
27.2k
    if (auto QTL = TL.getAs<QualifiedTypeLoc>())
971
26.6k
      NextTL = StripMacroAttributed(QTL.getNextTypeLoc());
972
27.2k
  }
973
71.5k
  auto *FromTy = getOrCreateType(NextTy, Unit, NextTL);
974
975
  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
976
  // CVR derived types.
977
71.5k
  return DBuilder.createQualifiedType(Tag, FromTy);
978
71.6k
}
979
980
llvm::DIType *CGDebugInfo::CreateQualifiedType(const FunctionProtoType *F,
981
387k
                                               llvm::DIFile *Unit) {
982
387k
  FunctionProtoType::ExtProtoInfo EPI = F->getExtProtoInfo();
983
387k
  Qualifiers &Q = EPI.TypeQuals;
984
387k
  stripUnusedQualifiers(Q);
985
986
  // We will create one Derived type for one qualifier and recurse to handle any
987
  // additional ones.
988
387k
  llvm::dwarf::Tag Tag = getNextQualifier(Q);
989
387k
  if (!Tag) {
990
387k
    assert(Q.empty() && "Unknown type qualifier for debug info");
991
0
    return nullptr;
992
387k
  }
993
994
15
  auto *FromTy =
995
15
      getOrCreateType(CGM.getContext().getFunctionType(F->getReturnType(),
996
15
                                                       F->getParamTypes(), EPI),
997
15
                      Unit);
998
999
  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
1000
  // CVR derived types.
1001
15
  return DBuilder.createQualifiedType(Tag, FromTy);
1002
387k
}
1003
1004
llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
1005
8.19k
                                      llvm::DIFile *Unit) {
1006
1007
  // The frontend treats 'id' as a typedef to an ObjCObjectType,
1008
  // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
1009
  // debug info, we want to emit 'id' in both cases.
1010
8.19k
  if (Ty->isObjCQualifiedIdType())
1011
246
    return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
1012
1013
7.94k
  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
1014
7.94k
                               Ty->getPointeeType(), Unit);
1015
8.19k
}
1016
1017
llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty, llvm::DIFile *Unit,
1018
125k
                                      TypeLoc TL) {
1019
125k
  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
1020
125k
                               Ty->getPointeeType(), Unit, TL);
1021
125k
}
1022
1023
/// \return whether a C++ mangling exists for the type defined by TD.
1024
161k
static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
1025
161k
  switch (TheCU->getSourceLanguage()) {
1026
176
  case llvm::dwarf::DW_LANG_C_plus_plus:
1027
85.4k
  case llvm::dwarf::DW_LANG_C_plus_plus_11:
1028
103k
  case llvm::dwarf::DW_LANG_C_plus_plus_14:
1029
103k
    return true;
1030
24.9k
  case llvm::dwarf::DW_LANG_ObjC_plus_plus:
1031
24.9k
    return isa<CXXRecordDecl>(TD) || 
isa<EnumDecl>(TD)4.82k
;
1032
32.5k
  default:
1033
32.5k
    return false;
1034
161k
  }
1035
161k
}
1036
1037
// Determines if the debug info for this tag declaration needs a type
1038
// identifier. The purpose of the unique identifier is to deduplicate type
1039
// information for identical types across TUs. Because of the C++ one definition
1040
// rule (ODR), it is valid to assume that the type is defined the same way in
1041
// every TU and its debug info is equivalent.
1042
//
1043
// C does not have the ODR, and it is common for codebases to contain multiple
1044
// different definitions of a struct with the same name in different TUs.
1045
// Therefore, if the type doesn't have a C++ mangling, don't give it an
1046
// identifer. Type information in C is smaller and simpler than C++ type
1047
// information, so the increase in debug info size is negligible.
1048
//
1049
// If the type is not externally visible, it should be unique to the current TU,
1050
// and should not need an identifier to participate in type deduplication.
1051
// However, when emitting CodeView, the format internally uses these
1052
// unique type name identifers for references between debug info. For example,
1053
// the method of a class in an anonymous namespace uses the identifer to refer
1054
// to its parent class. The Microsoft C++ ABI attempts to provide unique names
1055
// for such types, so when emitting CodeView, always use identifiers for C++
1056
// types. This may create problems when attempting to emit CodeView when the MS
1057
// C++ ABI is not in use.
1058
static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
1059
161k
                                llvm::DICompileUnit *TheCU) {
1060
  // We only add a type identifier for types with C++ name mangling.
1061
161k
  if (!hasCXXMangling(TD, TheCU))
1062
32.5k
    return false;
1063
1064
  // Externally visible types with C++ mangling need a type identifier.
1065
128k
  if (TD->isExternallyVisible())
1066
116k
    return true;
1067
1068
  // CodeView types with C++ mangling need a type identifier.
1069
12.1k
  if (CGM.getCodeGenOpts().EmitCodeView)
1070
19
    return true;
1071
1072
12.1k
  return false;
1073
12.1k
}
1074
1075
// Returns a unique type identifier string if one exists, or an empty string.
1076
static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
1077
161k
                                          llvm::DICompileUnit *TheCU) {
1078
161k
  SmallString<256> Identifier;
1079
161k
  const TagDecl *TD = Ty->getDecl();
1080
1081
161k
  if (!needsTypeIdentifier(TD, CGM, TheCU))
1082
44.7k
    return Identifier;
1083
116k
  if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
1084
110k
    if (RD->getDefinition())
1085
99.7k
      if (RD->isDynamicClass() &&
1086
99.7k
          
CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage2.46k
)
1087
1.72k
        return Identifier;
1088
1089
  // TODO: This is using the RTTI name. Is there a better way to get
1090
  // a unique string for a type?
1091
114k
  llvm::raw_svector_ostream Out(Identifier);
1092
114k
  CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
1093
114k
  return Identifier;
1094
116k
}
1095
1096
/// \return the appropriate DWARF tag for a composite type.
1097
132k
static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
1098
132k
  llvm::dwarf::Tag Tag;
1099
132k
  if (RD->isStruct() || 
RD->isInterface()28.6k
)
1100
104k
    Tag = llvm::dwarf::DW_TAG_structure_type;
1101
28.6k
  else if (RD->isUnion())
1102
3.08k
    Tag = llvm::dwarf::DW_TAG_union_type;
1103
25.5k
  else {
1104
    // FIXME: This could be a struct type giving a default visibility different
1105
    // than C++ class type, but needs llvm metadata changes first.
1106
25.5k
    assert(RD->isClass());
1107
0
    Tag = llvm::dwarf::DW_TAG_class_type;
1108
25.5k
  }
1109
0
  return Tag;
1110
132k
}
1111
1112
llvm::DICompositeType *
1113
CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
1114
14.3k
                                      llvm::DIScope *Ctx) {
1115
14.3k
  const RecordDecl *RD = Ty->getDecl();
1116
14.3k
  if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
1117
4
    return cast<llvm::DICompositeType>(T);
1118
14.3k
  llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1119
14.3k
  const unsigned Line =
1120
14.3k
      getLineNumber(RD->getLocation().isValid() ? 
RD->getLocation()14.3k
:
CurLoc59
);
1121
14.3k
  StringRef RDName = getClassName(RD);
1122
1123
14.3k
  uint64_t Size = 0;
1124
14.3k
  uint32_t Align = 0;
1125
1126
14.3k
  const RecordDecl *D = RD->getDefinition();
1127
14.3k
  if (D && 
D->isCompleteDefinition()1.80k
)
1128
1.46k
    Size = CGM.getContext().getTypeSize(Ty);
1129
1130
14.3k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagFwdDecl;
1131
1132
  // Add flag to nontrivial forward declarations. To be consistent with MSVC,
1133
  // add the flag if a record has no definition because we don't know whether
1134
  // it will be trivial or not.
1135
14.3k
  if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1136
12.2k
    if (!CXXRD->hasDefinition() ||
1137
12.2k
        
(1.51k
CXXRD->hasDefinition()1.51k
&&
!CXXRD->isTrivial()1.51k
))
1138
11.2k
      Flags |= llvm::DINode::FlagNonTrivial;
1139
1140
  // Create the type.
1141
14.3k
  SmallString<256> Identifier;
1142
  // Don't include a linkage name in line tables only.
1143
14.3k
  if (CGM.getCodeGenOpts().hasReducedDebugInfo())
1144
14.3k
    Identifier = getTypeIdentifier(Ty, CGM, TheCU);
1145
14.3k
  llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
1146
14.3k
      getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags,
1147
14.3k
      Identifier);
1148
14.3k
  if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
1149
1
    if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1150
1
      DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
1151
1
                             CollectCXXTemplateParams(TSpecial, DefUnit));
1152
14.3k
  ReplaceMap.emplace_back(
1153
14.3k
      std::piecewise_construct, std::make_tuple(Ty),
1154
14.3k
      std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
1155
14.3k
  return RetTy;
1156
14.3k
}
1157
1158
llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
1159
                                                 const Type *Ty,
1160
                                                 QualType PointeeTy,
1161
                                                 llvm::DIFile *Unit,
1162
237k
                                                 TypeLoc TL) {
1163
  // Bit size, align and offset of the type.
1164
  // Size is always the size of a pointer. We can't use getTypeSize here
1165
  // because that does not return the correct value for references.
1166
237k
  unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
1167
237k
  uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
1168
237k
  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
1169
237k
  Optional<unsigned> DWARFAddressSpace =
1170
237k
      CGM.getTarget().getDWARFAddressSpace(AddressSpace);
1171
1172
237k
  llvm::DINodeArray Annotations = nullptr;
1173
237k
  TypeLoc NextTL;
1174
237k
  if (TL) {
1175
86.2k
    SmallVector<llvm::Metadata *, 4> Annots;
1176
86.2k
    NextTL = TL.getNextTypeLoc();
1177
86.2k
    if (NextTL) {
1178
      // Traverse all MacroQualifiedTypeLoc, QualifiedTypeLoc and
1179
      // AttributedTypeLoc type locations so we can collect
1180
      // BTFTypeTag attributes for this pointer.
1181
108k
      while (true) {
1182
108k
        if (auto MTL = NextTL.getAs<MacroQualifiedTypeLoc>()) {
1183
14
          NextTL = MTL.getInnerLoc();
1184
108k
        } else if (auto QTL = NextTL.getAs<QualifiedTypeLoc>()) {
1185
23.1k
          NextTL = QTL.getNextTypeLoc();
1186
85.6k
        } else if (auto ATL = NextTL.getAs<AttributedTypeLoc>()) {
1187
95
          if (const auto *A = ATL.getAttrAs<BTFTypeTagAttr>()) {
1188
14
            StringRef BTFTypeTag = A->getBTFTypeTag();
1189
14
            if (!BTFTypeTag.empty()) {
1190
14
              llvm::Metadata *Ops[2] = {
1191
14
                  llvm::MDString::get(CGM.getLLVMContext(),
1192
14
                                      StringRef("btf_type_tag")),
1193
14
                  llvm::MDString::get(CGM.getLLVMContext(), BTFTypeTag)};
1194
14
              Annots.insert(Annots.begin(),
1195
14
                            llvm::MDNode::get(CGM.getLLVMContext(), Ops));
1196
14
            }
1197
14
          }
1198
95
          NextTL = ATL.getModifiedLoc();
1199
85.5k
        } else {
1200
85.5k
          break;
1201
85.5k
        }
1202
108k
      }
1203
85.5k
    }
1204
1205
86.2k
    NextTL = StripMacroAttributed(TL.getNextTypeLoc());
1206
86.2k
    if (Annots.size() > 0)
1207
10
      Annotations = DBuilder.getOrCreateArray(Annots);
1208
86.2k
  }
1209
1210
237k
  if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1211
237k
      
Tag == llvm::dwarf::DW_TAG_rvalue_reference_type152k
)
1212
104k
    return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
1213
104k
                                        Size, Align, DWARFAddressSpace);
1214
133k
  else
1215
133k
    return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit, NextTL),
1216
133k
                                      Size, Align, DWARFAddressSpace,
1217
133k
                                      StringRef(), Annotations);
1218
237k
}
1219
1220
llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1221
1
                                                    llvm::DIType *&Cache) {
1222
1
  if (Cache)
1223
0
    return Cache;
1224
1
  Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
1225
1
                                     TheCU, TheCU->getFile(), 0);
1226
1
  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1227
1
  Cache = DBuilder.createPointerType(Cache, Size);
1228
1
  return Cache;
1229
1
}
1230
1231
uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1232
    const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1233
824
    unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
1234
824
  QualType FType;
1235
1236
  // Advanced by calls to CreateMemberType in increments of FType, then
1237
  // returned as the overall size of the default elements.
1238
824
  uint64_t FieldOffset = 0;
1239
1240
  // Blocks in OpenCL have unique constraints which make the standard fields
1241
  // redundant while requiring size and align fields for enqueue_kernel. See
1242
  // initializeForBlockHeader in CGBlocks.cpp
1243
824
  if (CGM.getLangOpts().OpenCL) {
1244
4
    FType = CGM.getContext().IntTy;
1245
4
    EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1246
4
    EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1247
820
  } else {
1248
820
    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1249
820
    EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1250
820
    FType = CGM.getContext().IntTy;
1251
820
    EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1252
820
    EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1253
820
    FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1254
820
    EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1255
820
    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1256
820
    uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1257
820
    uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
1258
820
    EltTys.push_back(DBuilder.createMemberType(
1259
820
        Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1260
820
        FieldOffset, llvm::DINode::FlagZero, DescTy));
1261
820
    FieldOffset += FieldSize;
1262
820
  }
1263
1264
824
  return FieldOffset;
1265
824
}
1266
1267
llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1268
824
                                      llvm::DIFile *Unit) {
1269
824
  SmallVector<llvm::Metadata *, 8> EltTys;
1270
824
  QualType FType;
1271
824
  uint64_t FieldOffset;
1272
824
  llvm::DINodeArray Elements;
1273
1274
824
  FieldOffset = 0;
1275
824
  FType = CGM.getContext().UnsignedLongTy;
1276
824
  EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1277
824
  EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1278
1279
824
  Elements = DBuilder.getOrCreateArray(EltTys);
1280
824
  EltTys.clear();
1281
1282
824
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1283
1284
824
  auto *EltTy =
1285
824
      DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1286
824
                                FieldOffset, 0, Flags, nullptr, Elements);
1287
1288
  // Bit size, align and offset of the type.
1289
824
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1290
1291
824
  auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1292
1293
824
  FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1294
824
                                                          0, EltTys);
1295
1296
824
  Elements = DBuilder.getOrCreateArray(EltTys);
1297
1298
  // The __block_literal_generic structs are marked with a special
1299
  // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1300
  // the debugger needs to know about. To allow type uniquing, emit
1301
  // them without a name or a location.
1302
824
  EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
1303
824
                                    Flags, nullptr, Elements);
1304
1305
824
  return DBuilder.createPointerType(EltTy, Size);
1306
824
}
1307
1308
llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1309
7.08k
                                      llvm::DIFile *Unit) {
1310
7.08k
  assert(Ty->isTypeAlias());
1311
0
  llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
1312
1313
7.08k
  auto *AliasDecl =
1314
7.08k
      cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
1315
7.08k
          ->getTemplatedDecl();
1316
1317
7.08k
  if (AliasDecl->hasAttr<NoDebugAttr>())
1318
5.76k
    return Src;
1319
1320
1.32k
  SmallString<128> NS;
1321
1.32k
  llvm::raw_svector_ostream OS(NS);
1322
1.32k
  Ty->getTemplateName().print(OS, getPrintingPolicy(),
1323
1.32k
                              TemplateName::Qualified::None);
1324
1.32k
  printTemplateArgumentList(OS, Ty->template_arguments(), getPrintingPolicy());
1325
1326
1.32k
  SourceLocation Loc = AliasDecl->getLocation();
1327
1.32k
  return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1328
1.32k
                                getLineNumber(Loc),
1329
1.32k
                                getDeclContextDescriptor(AliasDecl));
1330
7.08k
}
1331
1332
llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1333
185k
                                      llvm::DIFile *Unit) {
1334
185k
  TypeLoc TL;
1335
185k
  if (const TypeSourceInfo *TSI = Ty->getDecl()->getTypeSourceInfo())
1336
185k
    TL = TSI->getTypeLoc();
1337
185k
  llvm::DIType *Underlying =
1338
185k
      getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit, TL);
1339
1340
185k
  if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1341
20.9k
    return Underlying;
1342
1343
  // We don't set size information, but do specify where the typedef was
1344
  // declared.
1345
164k
  SourceLocation Loc = Ty->getDecl()->getLocation();
1346
1347
164k
  uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
1348
  // Typedefs are derived from some other type.
1349
164k
  llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(Ty->getDecl());
1350
164k
  return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1351
164k
                                getOrCreateFile(Loc), getLineNumber(Loc),
1352
164k
                                getDeclContextDescriptor(Ty->getDecl()), Align,
1353
164k
                                Annotations);
1354
185k
}
1355
1356
802k
static unsigned getDwarfCC(CallingConv CC) {
1357
802k
  switch (CC) {
1358
802k
  case CC_C:
1359
    // Avoid emitting DW_AT_calling_convention if the C convention was used.
1360
802k
    return 0;
1361
1362
4
  case CC_X86StdCall:
1363
4
    return llvm::dwarf::DW_CC_BORLAND_stdcall;
1364
2
  case CC_X86FastCall:
1365
2
    return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1366
118
  case CC_X86ThisCall:
1367
118
    return llvm::dwarf::DW_CC_BORLAND_thiscall;
1368
3
  case CC_X86VectorCall:
1369
3
    return llvm::dwarf::DW_CC_LLVM_vectorcall;
1370
1
  case CC_X86Pascal:
1371
1
    return llvm::dwarf::DW_CC_BORLAND_pascal;
1372
2
  case CC_Win64:
1373
2
    return llvm::dwarf::DW_CC_LLVM_Win64;
1374
1
  case CC_X86_64SysV:
1375
1
    return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
1376
1
  case CC_AAPCS:
1377
1
  case CC_AArch64VectorCall:
1378
1
    return llvm::dwarf::DW_CC_LLVM_AAPCS;
1379
1
  case CC_AAPCS_VFP:
1380
1
    return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
1381
1
  case CC_IntelOclBicc:
1382
1
    return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
1383
8
  case CC_SpirFunction:
1384
8
    return llvm::dwarf::DW_CC_LLVM_SpirFunction;
1385
5
  case CC_OpenCLKernel:
1386
5
    return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
1387
1
  case CC_Swift:
1388
1
    return llvm::dwarf::DW_CC_LLVM_Swift;
1389
1
  case CC_SwiftAsync:
1390
    // [FIXME: swiftasynccc] Update to SwiftAsync once LLVM support lands.
1391
1
    return llvm::dwarf::DW_CC_LLVM_Swift;
1392
1
  case CC_PreserveMost:
1393
1
    return llvm::dwarf::DW_CC_LLVM_PreserveMost;
1394
1
  case CC_PreserveAll:
1395
1
    return llvm::dwarf::DW_CC_LLVM_PreserveAll;
1396
2
  case CC_X86RegCall:
1397
2
    return llvm::dwarf::DW_CC_LLVM_X86RegCall;
1398
802k
  }
1399
0
  return 0;
1400
802k
}
1401
1402
387k
static llvm::DINode::DIFlags getRefFlags(const FunctionProtoType *Func) {
1403
387k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1404
387k
  if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1405
58
    Flags |= llvm::DINode::FlagLValueReference;
1406
387k
  if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1407
58
    Flags |= llvm::DINode::FlagRValueReference;
1408
387k
  return Flags;
1409
387k
}
1410
1411
llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1412
387k
                                      llvm::DIFile *Unit, TypeLoc TL) {
1413
387k
  const auto *FPT = dyn_cast<FunctionProtoType>(Ty);
1414
387k
  if (FPT) {
1415
387k
    if (llvm::DIType *QTy = CreateQualifiedType(FPT, Unit))
1416
15
      return QTy;
1417
387k
  }
1418
1419
  // Create the type without any qualifiers
1420
1421
387k
  SmallVector<llvm::Metadata *, 16> EltTys;
1422
1423
  // Add the result type at least.
1424
387k
  TypeLoc RetTL;
1425
387k
  if (TL) {
1426
163k
    if (auto FTL = TL.getAs<FunctionTypeLoc>())
1427
150k
      RetTL = FTL.getReturnLoc();
1428
163k
  }
1429
387k
  EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit, RetTL));
1430
1431
387k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1432
  // Set up remainder of arguments if there is a prototype.
1433
  // otherwise emit it as a variadic function.
1434
387k
  if (!FPT) {
1435
6
    EltTys.push_back(DBuilder.createUnspecifiedParameter());
1436
387k
  } else {
1437
387k
    Flags = getRefFlags(FPT);
1438
387k
    bool DoneWithTL = false;
1439
387k
    if (TL) {
1440
163k
      if (auto FTL = TL.getAs<FunctionTypeLoc>()) {
1441
150k
        DoneWithTL = true;
1442
150k
        unsigned Idx = 0;
1443
150k
        unsigned FTL_NumParams = FTL.getNumParams();
1444
341k
        for (const QualType &ParamType : FPT->param_types()) {
1445
341k
          TypeLoc ParamTL;
1446
341k
          if (Idx < FTL_NumParams) {
1447
341k
            if (ParmVarDecl *Param = FTL.getParam(Idx)) {
1448
341k
              if (const TypeSourceInfo *TSI = Param->getTypeSourceInfo())
1449
341k
                ParamTL = TSI->getTypeLoc();
1450
341k
            }
1451
341k
          }
1452
341k
          EltTys.push_back(getOrCreateType(ParamType, Unit, ParamTL));
1453
341k
          Idx++;
1454
341k
        }
1455
150k
      }
1456
163k
    }
1457
1458
387k
    if (!DoneWithTL) {
1459
236k
      for (const QualType &ParamType : FPT->param_types())
1460
287k
        EltTys.push_back(getOrCreateType(ParamType, Unit));
1461
236k
    }
1462
387k
    if (FPT->isVariadic())
1463
172
      EltTys.push_back(DBuilder.createUnspecifiedParameter());
1464
387k
  }
1465
1466
387k
  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1467
387k
  llvm::DIType *F = DBuilder.createSubroutineType(
1468
387k
      EltTypeArray, Flags, getDwarfCC(Ty->getCallConv()));
1469
387k
  return F;
1470
387k
}
1471
1472
/// Convert an AccessSpecifier into the corresponding DINode flag.
1473
/// As an optimization, return 0 if the access specifier equals the
1474
/// default for the containing type.
1475
static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1476
817k
                                           const RecordDecl *RD) {
1477
817k
  AccessSpecifier Default = clang::AS_none;
1478
817k
  if (RD && 
RD->isClass()716k
)
1479
347k
    Default = clang::AS_private;
1480
469k
  else if (RD && 
(368k
RD->isStruct()368k
||
RD->isUnion()17.3k
))
1481
368k
    Default = clang::AS_public;
1482
1483
817k
  if (Access == Default)
1484
519k
    return llvm::DINode::FlagZero;
1485
1486
297k
  switch (Access) {
1487
7.40k
  case clang::AS_private:
1488
7.40k
    return llvm::DINode::FlagPrivate;
1489
29.6k
  case clang::AS_protected:
1490
29.6k
    return llvm::DINode::FlagProtected;
1491
259k
  case clang::AS_public:
1492
259k
    return llvm::DINode::FlagPublic;
1493
446
  case clang::AS_none:
1494
446
    return llvm::DINode::FlagZero;
1495
297k
  }
1496
0
  llvm_unreachable("unexpected access enumerator");
1497
0
}
1498
1499
llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1500
                                              llvm::DIScope *RecordTy,
1501
6.61k
                                              const RecordDecl *RD) {
1502
6.61k
  StringRef Name = BitFieldDecl->getName();
1503
6.61k
  QualType Ty = BitFieldDecl->getType();
1504
6.61k
  SourceLocation Loc = BitFieldDecl->getLocation();
1505
6.61k
  llvm::DIFile *VUnit = getOrCreateFile(Loc);
1506
6.61k
  llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1507
1508
  // Get the location for the field.
1509
6.61k
  llvm::DIFile *File = getOrCreateFile(Loc);
1510
6.61k
  unsigned Line = getLineNumber(Loc);
1511
1512
6.61k
  const CGBitFieldInfo &BitFieldInfo =
1513
6.61k
      CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1514
6.61k
  uint64_t SizeInBits = BitFieldInfo.Size;
1515
6.61k
  assert(SizeInBits > 0 && "found named 0-width bitfield");
1516
0
  uint64_t StorageOffsetInBits =
1517
6.61k
      CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1518
6.61k
  uint64_t Offset = BitFieldInfo.Offset;
1519
  // The bit offsets for big endian machines are reversed for big
1520
  // endian target, compensate for that as the DIDerivedType requires
1521
  // un-reversed offsets.
1522
6.61k
  if (CGM.getDataLayout().isBigEndian())
1523
6
    Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1524
6.61k
  uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1525
6.61k
  llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1526
6.61k
  llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(BitFieldDecl);
1527
6.61k
  return DBuilder.createBitFieldMemberType(
1528
6.61k
      RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1529
6.61k
      Flags, DebugType, Annotations);
1530
6.61k
}
1531
1532
llvm::DIType *
1533
CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
1534
                             AccessSpecifier AS, uint64_t offsetInBits,
1535
                             uint32_t AlignInBits, llvm::DIFile *tunit,
1536
                             llvm::DIScope *scope, const RecordDecl *RD,
1537
293k
                             llvm::DINodeArray Annotations, TypeLoc TL) {
1538
293k
  llvm::DIType *debugType = getOrCreateType(type, tunit, TL);
1539
1540
  // Get the location for the field.
1541
293k
  llvm::DIFile *file = getOrCreateFile(loc);
1542
293k
  const unsigned line = getLineNumber(loc.isValid() ? 
loc290k
:
CurLoc2.72k
);
1543
1544
293k
  uint64_t SizeInBits = 0;
1545
293k
  auto Align = AlignInBits;
1546
293k
  if (!type->isIncompleteArrayType()) {
1547
293k
    TypeInfo TI = CGM.getContext().getTypeInfo(type);
1548
293k
    SizeInBits = TI.Width;
1549
293k
    if (!Align)
1550
293k
      Align = getTypeAlignIfRequired(type, CGM.getContext());
1551
293k
  }
1552
1553
293k
  llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1554
293k
  return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1555
293k
                                   offsetInBits, flags, debugType, Annotations);
1556
293k
}
1557
1558
void CGDebugInfo::CollectRecordLambdaFields(
1559
    const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1560
97
    llvm::DIType *RecordTy) {
1561
  // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1562
  // has the name and the location of the variable so we should iterate over
1563
  // both concurrently.
1564
97
  const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1565
97
  RecordDecl::field_iterator Field = CXXDecl->field_begin();
1566
97
  unsigned fieldno = 0;
1567
97
  for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
1568
97
                                             E = CXXDecl->captures_end();
1569
158
       I != E; 
++I, ++Field, ++fieldno61
) {
1570
61
    const LambdaCapture &C = *I;
1571
61
    if (C.capturesVariable()) {
1572
54
      SourceLocation Loc = C.getLocation();
1573
54
      assert(!Field->isBitField() && "lambdas don't have bitfield members!");
1574
0
      VarDecl *V = C.getCapturedVar();
1575
54
      StringRef VName = V->getName();
1576
54
      llvm::DIFile *VUnit = getOrCreateFile(Loc);
1577
54
      auto Align = getDeclAlignIfRequired(V, CGM.getContext());
1578
54
      llvm::DIType *FieldType = createFieldType(
1579
54
          VName, Field->getType(), Loc, Field->getAccess(),
1580
54
          layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
1581
54
      elements.push_back(FieldType);
1582
54
    } else 
if (7
C.capturesThis()7
) {
1583
      // TODO: Need to handle 'this' in some way by probably renaming the
1584
      // this of the lambda class and having a field member of 'this' or
1585
      // by using AT_object_pointer for the function and having that be
1586
      // used as 'this' for semantic references.
1587
7
      FieldDecl *f = *Field;
1588
7
      llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1589
7
      QualType type = f->getType();
1590
7
      llvm::DIType *fieldType = createFieldType(
1591
7
          "this", type, f->getLocation(), f->getAccess(),
1592
7
          layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1593
1594
7
      elements.push_back(fieldType);
1595
7
    }
1596
61
  }
1597
97
}
1598
1599
llvm::DIDerivedType *
1600
CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1601
33.0k
                                     const RecordDecl *RD) {
1602
  // Create the descriptor for the static variable, with or without
1603
  // constant initializers.
1604
33.0k
  Var = Var->getCanonicalDecl();
1605
33.0k
  llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1606
33.0k
  llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1607
1608
33.0k
  unsigned LineNumber = getLineNumber(Var->getLocation());
1609
33.0k
  StringRef VName = Var->getName();
1610
33.0k
  llvm::Constant *C = nullptr;
1611
33.0k
  if (Var->getInit()) {
1612
31.2k
    const APValue *Value = Var->evaluateValue();
1613
31.2k
    if (Value) {
1614
31.2k
      if (Value->isInt())
1615
31.2k
        C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1616
31.2k
      if (Value->isFloat())
1617
4
        C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1618
31.2k
    }
1619
31.2k
  }
1620
1621
33.0k
  llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
1622
33.0k
  auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
1623
33.0k
  llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1624
33.0k
      RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
1625
33.0k
  StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1626
33.0k
  return GV;
1627
33.0k
}
1628
1629
void CGDebugInfo::CollectRecordNormalField(
1630
    const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1631
    SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1632
298k
    const RecordDecl *RD) {
1633
298k
  StringRef name = field->getName();
1634
298k
  QualType type = field->getType();
1635
1636
  // Ignore unnamed fields unless they're anonymous structs/unions.
1637
298k
  if (name.empty() && 
!type->isRecordType()868
)
1638
141
    return;
1639
1640
297k
  llvm::DIType *FieldType;
1641
297k
  if (field->isBitField()) {
1642
6.61k
    FieldType = createBitFieldType(field, RecordTy, RD);
1643
291k
  } else {
1644
291k
    auto Align = getDeclAlignIfRequired(field, CGM.getContext());
1645
291k
    llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(field);
1646
291k
    TypeLoc TL;
1647
291k
    if (const TypeSourceInfo *TSI = field->getTypeSourceInfo())
1648
288k
      TL = TSI->getTypeLoc();
1649
291k
    FieldType = createFieldType(name, type, field->getLocation(),
1650
291k
                                field->getAccess(), OffsetInBits, Align, tunit,
1651
291k
                                RecordTy, RD, Annotations, TL);
1652
291k
  }
1653
1654
297k
  elements.push_back(FieldType);
1655
297k
}
1656
1657
void CGDebugInfo::CollectRecordNestedType(
1658
12
    const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1659
12
  QualType Ty = CGM.getContext().getTypeDeclType(TD);
1660
  // Injected class names are not considered nested records.
1661
12
  if (isa<InjectedClassNameType>(Ty))
1662
1
    return;
1663
11
  SourceLocation Loc = TD->getLocation();
1664
11
  llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1665
11
  elements.push_back(nestedType);
1666
11
}
1667
1668
void CGDebugInfo::CollectRecordFields(
1669
    const RecordDecl *record, llvm::DIFile *tunit,
1670
    SmallVectorImpl<llvm::Metadata *> &elements,
1671
118k
    llvm::DICompositeType *RecordTy) {
1672
118k
  const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1673
1674
118k
  if (CXXDecl && 
CXXDecl->isLambda()102k
)
1675
97
    CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1676
118k
  else {
1677
118k
    const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1678
1679
    // Field number for non-static fields.
1680
118k
    unsigned fieldNo = 0;
1681
1682
    // Static and non-static members should appear in the same order as
1683
    // the corresponding declarations in the source program.
1684
118k
    for (const auto *I : record->decls())
1685
1.18M
      if (const auto *V = dyn_cast<VarDecl>(I)) {
1686
32.9k
        if (V->hasAttr<NoDebugAttr>())
1687
2
          continue;
1688
1689
        // Skip variable template specializations when emitting CodeView. MSVC
1690
        // doesn't emit them.
1691
32.9k
        if (CGM.getCodeGenOpts().EmitCodeView &&
1692
32.9k
            
isa<VarTemplateSpecializationDecl>(V)15
)
1693
5
          continue;
1694
1695
32.9k
        if (isa<VarTemplatePartialSpecializationDecl>(V))
1696
1
          continue;
1697
1698
        // Reuse the existing static member declaration if one exists
1699
32.9k
        auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1700
32.9k
        if (MI != StaticDataMemberCache.end()) {
1701
0
          assert(MI->second &&
1702
0
                 "Static data member declaration should still exist");
1703
0
          elements.push_back(MI->second);
1704
32.9k
        } else {
1705
32.9k
          auto Field = CreateRecordStaticField(V, RecordTy, record);
1706
32.9k
          elements.push_back(Field);
1707
32.9k
        }
1708
1.15M
      } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1709
298k
        CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1710
298k
                                 elements, RecordTy, record);
1711
1712
        // Bump field number for next field.
1713
298k
        ++fieldNo;
1714
854k
      } else if (CGM.getCodeGenOpts().EmitCodeView) {
1715
        // Debug info for nested types is included in the member list only for
1716
        // CodeView.
1717
399
        if (const auto *nestedType = dyn_cast<TypeDecl>(I))
1718
93
          if (!nestedType->isImplicit() &&
1719
93
              
nestedType->getDeclContext() == record12
)
1720
12
            CollectRecordNestedType(nestedType, elements);
1721
399
      }
1722
118k
  }
1723
118k
}
1724
1725
llvm::DISubroutineType *
1726
CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1727
428k
                                   llvm::DIFile *Unit, bool decl) {
1728
428k
  const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1729
428k
  if (Method->isStatic())
1730
33.7k
    return cast_or_null<llvm::DISubroutineType>(
1731
33.7k
        getOrCreateType(QualType(Func, 0), Unit));
1732
394k
  return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit, decl);
1733
428k
}
1734
1735
llvm::DISubroutineType *
1736
CGDebugInfo::getOrCreateInstanceMethodType(QualType ThisPtr,
1737
                                           const FunctionProtoType *Func,
1738
394k
                                           llvm::DIFile *Unit, bool decl) {
1739
394k
  FunctionProtoType::ExtProtoInfo EPI = Func->getExtProtoInfo();
1740
394k
  Qualifiers &Qc = EPI.TypeQuals;
1741
394k
  Qc.removeConst();
1742
394k
  Qc.removeVolatile();
1743
394k
  Qc.removeRestrict();
1744
394k
  Qc.removeUnaligned();
1745
  // Keep the removed qualifiers in sync with
1746
  // CreateQualifiedType(const FunctionPrototype*, DIFile *Unit)
1747
  // On a 'real' member function type, these qualifiers are carried on the type
1748
  // of the first parameter, not as separate DW_TAG_const_type (etc) decorator
1749
  // tags around them. (But, in the raw function types with qualifiers, they have
1750
  // to use wrapper types.)
1751
1752
  // Add "this" pointer.
1753
394k
  const auto *OriginalFunc = cast<llvm::DISubroutineType>(
1754
394k
      getOrCreateType(CGM.getContext().getFunctionType(
1755
394k
                          Func->getReturnType(), Func->getParamTypes(), EPI),
1756
394k
                      Unit));
1757
394k
  llvm::DITypeRefArray Args = OriginalFunc->getTypeArray();
1758
394k
  assert(Args.size() && "Invalid number of arguments!");
1759
1760
0
  SmallVector<llvm::Metadata *, 16> Elts;
1761
  // First element is always return type. For 'void' functions it is NULL.
1762
394k
  QualType temp = Func->getReturnType();
1763
394k
  if (temp->getTypeClass() == Type::Auto && 
decl30
)
1764
13
    Elts.push_back(CreateType(cast<AutoType>(temp)));
1765
394k
  else
1766
394k
    Elts.push_back(Args[0]);
1767
1768
  // "this" pointer is always first argument.
1769
394k
  const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1770
394k
  if (isa<ClassTemplateSpecializationDecl>(RD)) {
1771
    // Create pointer type directly in this case.
1772
328k
    const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1773
328k
    QualType PointeeTy = ThisPtrTy->getPointeeType();
1774
328k
    unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1775
328k
    uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1776
328k
    auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
1777
328k
    llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1778
328k
    llvm::DIType *ThisPtrType =
1779
328k
        DBuilder.createPointerType(PointeeType, Size, Align);
1780
328k
    TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1781
    // TODO: This and the artificial type below are misleading, the
1782
    // types aren't artificial the argument is, but the current
1783
    // metadata doesn't represent that.
1784
328k
    ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1785
328k
    Elts.push_back(ThisPtrType);
1786
328k
  } else {
1787
66.4k
    llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1788
66.4k
    TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1789
66.4k
    ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1790
66.4k
    Elts.push_back(ThisPtrType);
1791
66.4k
  }
1792
1793
  // Copy rest of the arguments.
1794
743k
  for (unsigned i = 1, e = Args.size(); i != e; 
++i348k
)
1795
348k
    Elts.push_back(Args[i]);
1796
1797
394k
  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1798
1799
394k
  return DBuilder.createSubroutineType(EltTypeArray, OriginalFunc->getFlags(),
1800
394k
                                       getDwarfCC(Func->getCallConv()));
1801
394k
}
1802
1803
/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1804
/// inside a function.
1805
285k
static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1806
285k
  if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1807
1.20k
    return isFunctionLocalClass(NRD);
1808
284k
  if (isa<FunctionDecl>(RD->getDeclContext()))
1809
129
    return true;
1810
284k
  return false;
1811
284k
}
1812
1813
llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1814
358k
    const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1815
358k
  bool IsCtorOrDtor =
1816
358k
      isa<CXXConstructorDecl>(Method) || 
isa<CXXDestructorDecl>(Method)293k
;
1817
1818
358k
  StringRef MethodName = getFunctionName(Method);
1819
358k
  llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit, true);
1820
1821
  // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1822
  // make sense to give a single ctor/dtor a linkage name.
1823
358k
  StringRef MethodLinkageName;
1824
  // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1825
  // property to use here. It may've been intended to model "is non-external
1826
  // type" but misses cases of non-function-local but non-external classes such
1827
  // as those in anonymous namespaces as well as the reverse - external types
1828
  // that are function local, such as those in (non-local) inline functions.
1829
358k
  if (!IsCtorOrDtor && 
!isFunctionLocalClass(Method->getParent())284k
)
1830
284k
    MethodLinkageName = CGM.getMangledName(Method);
1831
1832
  // Get the location for the method.
1833
358k
  llvm::DIFile *MethodDefUnit = nullptr;
1834
358k
  unsigned MethodLine = 0;
1835
358k
  if (!Method->isImplicit()) {
1836
356k
    MethodDefUnit = getOrCreateFile(Method->getLocation());
1837
356k
    MethodLine = getLineNumber(Method->getLocation());
1838
356k
  }
1839
1840
  // Collect virtual method info.
1841
358k
  llvm::DIType *ContainingType = nullptr;
1842
358k
  unsigned VIndex = 0;
1843
358k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1844
358k
  llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
1845
358k
  int ThisAdjustment = 0;
1846
1847
358k
  if (Method->isVirtual()) {
1848
7.58k
    if (Method->isPure())
1849
381
      SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
1850
7.20k
    else
1851
7.20k
      SPFlags |= llvm::DISubprogram::SPFlagVirtual;
1852
1853
7.58k
    if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1854
      // It doesn't make sense to give a virtual destructor a vtable index,
1855
      // since a single destructor has two entries in the vtable.
1856
7.55k
      if (!isa<CXXDestructorDecl>(Method))
1857
5.84k
        VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1858
7.55k
    } else {
1859
      // Emit MS ABI vftable information.  There is only one entry for the
1860
      // deleting dtor.
1861
33
      const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1862
33
      GlobalDecl GD = DD ? 
GlobalDecl(DD, Dtor_Deleting)2
:
GlobalDecl(Method)31
;
1863
33
      MethodVFTableLocation ML =
1864
33
          CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1865
33
      VIndex = ML.Index;
1866
1867
      // CodeView only records the vftable offset in the class that introduces
1868
      // the virtual method. This is possible because, unlike Itanium, the MS
1869
      // C++ ABI does not include all virtual methods from non-primary bases in
1870
      // the vtable for the most derived class. For example, if C inherits from
1871
      // A and B, C's primary vftable will not include B's virtual methods.
1872
33
      if (Method->size_overridden_methods() == 0)
1873
20
        Flags |= llvm::DINode::FlagIntroducedVirtual;
1874
1875
      // The 'this' adjustment accounts for both the virtual and non-virtual
1876
      // portions of the adjustment. Presumably the debugger only uses it when
1877
      // it knows the dynamic type of an object.
1878
33
      ThisAdjustment = CGM.getCXXABI()
1879
33
                           .getVirtualFunctionPrologueThisAdjustment(GD)
1880
33
                           .getQuantity();
1881
33
    }
1882
7.58k
    ContainingType = RecordTy;
1883
7.58k
  }
1884
1885
  // We're checking for deleted C++ special member functions
1886
  // [Ctors,Dtors, Copy/Move]
1887
358k
  auto checkAttrDeleted = [&](const auto *Method) {
1888
84.8k
    if (Method->getCanonicalDecl()->isDeleted())
1889
5.14k
      SPFlags |= llvm::DISubprogram::SPFlagDeleted;
1890
84.8k
  };
1891
1892
358k
  switch (Method->getKind()) {
1893
1894
64.4k
  case Decl::CXXConstructor:
1895
73.5k
  case Decl::CXXDestructor:
1896
73.5k
    checkAttrDeleted(Method);
1897
73.5k
    break;
1898
280k
  case Decl::CXXMethod:
1899
280k
    if (Method->isCopyAssignmentOperator() ||
1900
280k
        
Method->isMoveAssignmentOperator()272k
)
1901
11.2k
      checkAttrDeleted(Method);
1902
280k
    break;
1903
4.70k
  default:
1904
4.70k
    break;
1905
358k
  }
1906
1907
358k
  if (Method->isNoReturn())
1908
1.96k
    Flags |= llvm::DINode::FlagNoReturn;
1909
1910
358k
  if (Method->isStatic())
1911
28.4k
    Flags |= llvm::DINode::FlagStaticMember;
1912
358k
  if (Method->isImplicit())
1913
1.56k
    Flags |= llvm::DINode::FlagArtificial;
1914
358k
  Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1915
358k
  if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1916
64.4k
    if (CXXC->isExplicit())
1917
10.5k
      Flags |= llvm::DINode::FlagExplicit;
1918
293k
  } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
1919
4.70k
    if (CXXC->isExplicit())
1920
3.10k
      Flags |= llvm::DINode::FlagExplicit;
1921
4.70k
  }
1922
358k
  if (Method->hasPrototype())
1923
358k
    Flags |= llvm::DINode::FlagPrototyped;
1924
358k
  if (Method->getRefQualifier() == RQ_LValue)
1925
56
    Flags |= llvm::DINode::FlagLValueReference;
1926
358k
  if (Method->getRefQualifier() == RQ_RValue)
1927
56
    Flags |= llvm::DINode::FlagRValueReference;
1928
358k
  if (!Method->isExternallyVisible())
1929
4.39k
    SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
1930
358k
  if (CGM.getLangOpts().Optimize)
1931
29
    SPFlags |= llvm::DISubprogram::SPFlagOptimized;
1932
1933
  // In this debug mode, emit type info for a class when its constructor type
1934
  // info is emitted.
1935
358k
  if (DebugKind == codegenoptions::DebugInfoConstructor)
1936
169
    if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1937
76
      completeUnusedClass(*CD->getParent());
1938
1939
358k
  llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1940
358k
  llvm::DISubprogram *SP = DBuilder.createMethod(
1941
358k
      RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1942
358k
      MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
1943
358k
      TParamsArray.get());
1944
1945
358k
  SPCache[Method->getCanonicalDecl()].reset(SP);
1946
1947
358k
  return SP;
1948
358k
}
1949
1950
void CGDebugInfo::CollectCXXMemberFunctions(
1951
    const CXXRecordDecl *RD, llvm::DIFile *Unit,
1952
102k
    SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1953
1954
  // Since we want more than just the individual member decls if we
1955
  // have templated functions iterate over every declaration to gather
1956
  // the functions.
1957
1.09M
  for (const auto *I : RD->decls()) {
1958
1.09M
    const auto *Method = dyn_cast<CXXMethodDecl>(I);
1959
    // If the member is implicit, don't add it to the member list. This avoids
1960
    // the member being added to type units by LLVM, while still allowing it
1961
    // to be emitted into the type declaration/reference inside the compile
1962
    // unit.
1963
    // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
1964
    // FIXME: Handle Using(Shadow?)Decls here to create
1965
    // DW_TAG_imported_declarations inside the class for base decls brought into
1966
    // derived classes. GDB doesn't seem to notice/leverage these when I tried
1967
    // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1968
    // referenced)
1969
1.09M
    if (!Method || 
Method->isImplicit()430k
||
Method->hasAttr<NoDebugAttr>()345k
)
1970
751k
      continue;
1971
1972
345k
    if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
1973
43
      continue;
1974
1975
    // Reuse the existing member function declaration if it exists.
1976
    // It may be associated with the declaration of the type & should be
1977
    // reused as we're building the definition.
1978
    //
1979
    // This situation can arise in the vtable-based debug info reduction where
1980
    // implicit members are emitted in a non-vtable TU.
1981
345k
    auto MI = SPCache.find(Method->getCanonicalDecl());
1982
345k
    EltTys.push_back(MI == SPCache.end()
1983
345k
                         ? 
CreateCXXMemberFunction(Method, Unit, RecordTy)345k
1984
345k
                         : 
static_cast<llvm::Metadata *>(MI->second)74
);
1985
345k
  }
1986
102k
}
1987
1988
void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1989
                                  SmallVectorImpl<llvm::Metadata *> &EltTys,
1990
102k
                                  llvm::DIType *RecordTy) {
1991
102k
  llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
1992
102k
  CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1993
102k
                     llvm::DINode::FlagZero);
1994
1995
  // If we are generating CodeView debug info, we also need to emit records for
1996
  // indirect virtual base classes.
1997
102k
  if (CGM.getCodeGenOpts().EmitCodeView) {
1998
94
    CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1999
94
                       llvm::DINode::FlagIndirectVirtualBase);
2000
94
  }
2001
102k
}
2002
2003
void CGDebugInfo::CollectCXXBasesAux(
2004
    const CXXRecordDecl *RD, llvm::DIFile *Unit,
2005
    SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
2006
    const CXXRecordDecl::base_class_const_range &Bases,
2007
    llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
2008
102k
    llvm::DINode::DIFlags StartingFlags) {
2009
102k
  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2010
102k
  for (const auto &BI : Bases) {
2011
23.5k
    const auto *Base =
2012
23.5k
        cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
2013
23.5k
    if (!SeenTypes.insert(Base).second)
2014
3
      continue;
2015
23.5k
    auto *BaseTy = getOrCreateType(BI.getType(), Unit);
2016
23.5k
    llvm::DINode::DIFlags BFlags = StartingFlags;
2017
23.5k
    uint64_t BaseOffset;
2018
23.5k
    uint32_t VBPtrOffset = 0;
2019
2020
23.5k
    if (BI.isVirtual()) {
2021
103
      if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
2022
        // virtual base offset offset is -ve. The code generator emits dwarf
2023
        // expression where it expects +ve number.
2024
98
        BaseOffset = 0 - CGM.getItaniumVTableContext()
2025
98
                             .getVirtualBaseOffsetOffset(RD, Base)
2026
98
                             .getQuantity();
2027
98
      } else {
2028
        // In the MS ABI, store the vbtable offset, which is analogous to the
2029
        // vbase offset offset in Itanium.
2030
5
        BaseOffset =
2031
5
            4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
2032
5
        VBPtrOffset = CGM.getContext()
2033
5
                          .getASTRecordLayout(RD)
2034
5
                          .getVBPtrOffset()
2035
5
                          .getQuantity();
2036
5
      }
2037
103
      BFlags |= llvm::DINode::FlagVirtual;
2038
103
    } else
2039
23.4k
      BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
2040
    // FIXME: Inconsistent units for BaseOffset. It is in bytes when
2041
    // BI->isVirtual() and bits when not.
2042
2043
23.5k
    BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
2044
23.5k
    llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
2045
23.5k
                                                   VBPtrOffset, BFlags);
2046
23.5k
    EltTys.push_back(DTy);
2047
23.5k
  }
2048
102k
}
2049
2050
llvm::DINodeArray
2051
CGDebugInfo::CollectTemplateParams(Optional<TemplateArgs> OArgs,
2052
783k
                                   llvm::DIFile *Unit) {
2053
783k
  if (!OArgs)
2054
666k
    return llvm::DINodeArray();
2055
117k
  TemplateArgs &Args = *OArgs;
2056
117k
  SmallVector<llvm::Metadata *, 16> TemplateParams;
2057
314k
  for (unsigned i = 0, e = Args.Args.size(); i != e; 
++i197k
) {
2058
197k
    const TemplateArgument &TA = Args.Args[i];
2059
197k
    StringRef Name;
2060
197k
    bool defaultParameter = false;
2061
197k
    if (Args.TList)
2062
175k
      Name = Args.TList->getParam(i)->getName();
2063
197k
    switch (TA.getKind()) {
2064
145k
    case TemplateArgument::Type: {
2065
145k
      llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
2066
2067
145k
      if (Args.TList)
2068
127k
        if (auto *templateType =
2069
127k
                dyn_cast_or_null<TemplateTypeParmDecl>(Args.TList->getParam(i)))
2070
127k
          if (templateType->hasDefaultArgument())
2071
20.9k
            defaultParameter =
2072
20.9k
                templateType->getDefaultArgument() == TA.getAsType();
2073
2074
145k
      TemplateParams.push_back(DBuilder.createTemplateTypeParameter(
2075
145k
          TheCU, Name, TTy, defaultParameter));
2076
2077
145k
    } break;
2078
33.5k
    case TemplateArgument::Integral: {
2079
33.5k
      llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
2080
33.5k
      if (Args.TList && 
CGM.getCodeGenOpts().DwarfVersion >= 530.5k
)
2081
6
        if (auto *templateType = dyn_cast_or_null<NonTypeTemplateParmDecl>(
2082
6
                Args.TList->getParam(i)))
2083
6
          if (templateType->hasDefaultArgument() &&
2084
6
              !templateType->getDefaultArgument()->isValueDependent())
2085
4
            defaultParameter = llvm::APSInt::isSameValue(
2086
4
                templateType->getDefaultArgument()->EvaluateKnownConstInt(
2087
4
                    CGM.getContext()),
2088
4
                TA.getAsIntegral());
2089
2090
33.5k
      TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2091
33.5k
          TheCU, Name, TTy, defaultParameter,
2092
33.5k
          llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
2093
33.5k
    } break;
2094
25
    case TemplateArgument::Declaration: {
2095
25
      const ValueDecl *D = TA.getAsDecl();
2096
25
      QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
2097
25
      llvm::DIType *TTy = getOrCreateType(T, Unit);
2098
25
      llvm::Constant *V = nullptr;
2099
      // Skip retrieve the value if that template parameter has cuda device
2100
      // attribute, i.e. that value is not available at the host side.
2101
25
      if (!CGM.getLangOpts().CUDA || 
CGM.getLangOpts().CUDAIsDevice1
||
2102
25
          
!D->hasAttr<CUDADeviceAttr>()1
) {
2103
24
        const CXXMethodDecl *MD;
2104
        // Variable pointer template parameters have a value that is the address
2105
        // of the variable.
2106
24
        if (const auto *VD = dyn_cast<VarDecl>(D))
2107
7
          V = CGM.GetAddrOfGlobalVar(VD);
2108
        // Member function pointers have special support for building them,
2109
        // though this is currently unsupported in LLVM CodeGen.
2110
17
        else if ((MD = dyn_cast<CXXMethodDecl>(D)) && 
MD->isInstance()2
)
2111
1
          V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
2112
16
        else if (const auto *FD = dyn_cast<FunctionDecl>(D))
2113
8
          V = CGM.GetAddrOfFunction(FD);
2114
        // Member data pointers have special handling too to compute the fixed
2115
        // offset within the object.
2116
8
        else if (const auto *MPT =
2117
8
                     dyn_cast<MemberPointerType>(T.getTypePtr())) {
2118
          // These five lines (& possibly the above member function pointer
2119
          // handling) might be able to be refactored to use similar code in
2120
          // CodeGenModule::getMemberPointerConstant
2121
2
          uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
2122
2
          CharUnits chars =
2123
2
              CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
2124
2
          V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
2125
6
        } else if (const auto *GD = dyn_cast<MSGuidDecl>(D)) {
2126
4
          V = CGM.GetAddrOfMSGuidDecl(GD).getPointer();
2127
4
        } else 
if (const auto *2
TPO2
= dyn_cast<TemplateParamObjectDecl>(D)) {
2128
2
          if (T->isRecordType())
2129
1
            V = ConstantEmitter(CGM).emitAbstract(
2130
1
                SourceLocation(), TPO->getValue(), TPO->getType());
2131
1
          else
2132
1
            V = CGM.GetAddrOfTemplateParamObject(TPO).getPointer();
2133
2
        }
2134
24
        assert(V && "Failed to find template parameter pointer");
2135
0
        V = V->stripPointerCasts();
2136
24
      }
2137
0
      TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2138
25
          TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));
2139
25
    } break;
2140
454
    case TemplateArgument::NullPtr: {
2141
454
      QualType T = TA.getNullPtrType();
2142
454
      llvm::DIType *TTy = getOrCreateType(T, Unit);
2143
454
      llvm::Constant *V = nullptr;
2144
      // Special case member data pointer null values since they're actually -1
2145
      // instead of zero.
2146
454
      if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
2147
        // But treat member function pointers as simple zero integers because
2148
        // it's easier than having a special case in LLVM's CodeGen. If LLVM
2149
        // CodeGen grows handling for values of non-null member function
2150
        // pointers then perhaps we could remove this special case and rely on
2151
        // EmitNullMemberPointer for member function pointers.
2152
2
        if (MPT->isMemberDataPointer())
2153
1
          V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
2154
454
      if (!V)
2155
453
        V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
2156
454
      TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2157
454
          TheCU, Name, TTy, defaultParameter, V));
2158
454
    } break;
2159
345
    case TemplateArgument::Template: {
2160
345
      std::string QualName;
2161
345
      llvm::raw_string_ostream OS(QualName);
2162
345
      TA.getAsTemplate().getAsTemplateDecl()->printQualifiedName(
2163
345
          OS, getPrintingPolicy());
2164
345
      TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
2165
345
          TheCU, Name, nullptr, OS.str()));
2166
345
      break;
2167
0
    }
2168
17.4k
    case TemplateArgument::Pack:
2169
17.4k
      TemplateParams.push_back(DBuilder.createTemplateParameterPack(
2170
17.4k
          TheCU, Name, nullptr,
2171
17.4k
          CollectTemplateParams({{nullptr, TA.getPackAsArray()}}, Unit)));
2172
17.4k
      break;
2173
0
    case TemplateArgument::Expression: {
2174
0
      const Expr *E = TA.getAsExpr();
2175
0
      QualType T = E->getType();
2176
0
      if (E->isGLValue())
2177
0
        T = CGM.getContext().getLValueReferenceType(T);
2178
0
      llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
2179
0
      assert(V && "Expression in template argument isn't constant");
2180
0
      llvm::DIType *TTy = getOrCreateType(T, Unit);
2181
0
      TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2182
0
          TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));
2183
0
    } break;
2184
    // And the following should never occur:
2185
0
    case TemplateArgument::TemplateExpansion:
2186
0
    case TemplateArgument::Null:
2187
0
      llvm_unreachable(
2188
197k
          "These argument types shouldn't exist in concrete types");
2189
197k
    }
2190
197k
  }
2191
117k
  return DBuilder.getOrCreateArray(TemplateParams);
2192
117k
}
2193
2194
Optional<CGDebugInfo::TemplateArgs>
2195
1.41M
CGDebugInfo::GetTemplateArgs(const FunctionDecl *FD) const {
2196
1.41M
  if (FD->getTemplatedKind() ==
2197
1.41M
      FunctionDecl::TK_FunctionTemplateSpecialization) {
2198
83.5k
    const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
2199
83.5k
                                             ->getTemplate()
2200
83.5k
                                             ->getTemplateParameters();
2201
83.5k
    return {{TList, FD->getTemplateSpecializationArgs()->asArray()}};
2202
83.5k
  }
2203
1.33M
  return None;
2204
1.41M
}
2205
Optional<CGDebugInfo::TemplateArgs>
2206
19
CGDebugInfo::GetTemplateArgs(const VarDecl *VD) const {
2207
  // Always get the full list of parameters, not just the ones from the
2208
  // specialization. A partial specialization may have fewer parameters than
2209
  // there are arguments.
2210
19
  auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VD);
2211
19
  if (!TS)
2212
0
    return None;
2213
19
  VarTemplateDecl *T = TS->getSpecializedTemplate();
2214
19
  const TemplateParameterList *TList = T->getTemplateParameters();
2215
19
  auto TA = TS->getTemplateArgs().asArray();
2216
19
  return {{TList, TA}};
2217
19
}
2218
Optional<CGDebugInfo::TemplateArgs>
2219
129k
CGDebugInfo::GetTemplateArgs(const RecordDecl *RD) const {
2220
129k
  if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
2221
    // Always get the full list of parameters, not just the ones from the
2222
    // specialization. A partial specialization may have fewer parameters than
2223
    // there are arguments.
2224
129k
    TemplateParameterList *TPList =
2225
129k
        TSpecial->getSpecializedTemplate()->getTemplateParameters();
2226
129k
    const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
2227
129k
    return {{TPList, TAList.asArray()}};
2228
129k
  }
2229
0
  return None;
2230
129k
}
2231
2232
llvm::DINodeArray
2233
CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
2234
708k
                                           llvm::DIFile *Unit) {
2235
708k
  return CollectTemplateParams(GetTemplateArgs(FD), Unit);
2236
708k
}
2237
2238
llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
2239
19
                                                        llvm::DIFile *Unit) {
2240
19
  return CollectTemplateParams(GetTemplateArgs(VL), Unit);
2241
19
}
2242
2243
llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(const RecordDecl *RD,
2244
58.0k
                                                        llvm::DIFile *Unit) {
2245
58.0k
  return CollectTemplateParams(GetTemplateArgs(RD), Unit);
2246
58.0k
}
2247
2248
990k
llvm::DINodeArray CGDebugInfo::CollectBTFDeclTagAnnotations(const Decl *D) {
2249
990k
  if (!D->hasAttr<BTFDeclTagAttr>())
2250
990k
    return nullptr;
2251
2252
18
  SmallVector<llvm::Metadata *, 4> Annotations;
2253
34
  for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {
2254
34
    llvm::Metadata *Ops[2] = {
2255
34
        llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_decl_tag")),
2256
34
        llvm::MDString::get(CGM.getLLVMContext(), I->getBTFDeclTag())};
2257
34
    Annotations.push_back(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2258
34
  }
2259
18
  return DBuilder.getOrCreateArray(Annotations);
2260
990k
}
2261
2262
664
llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
2263
664
  if (VTablePtrType)
2264
456
    return VTablePtrType;
2265
2266
208
  ASTContext &Context = CGM.getContext();
2267
2268
  /* Function type */
2269
208
  llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
2270
208
  llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
2271
208
  llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
2272
208
  unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
2273
208
  unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2274
208
  Optional<unsigned> DWARFAddressSpace =
2275
208
      CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2276
2277
208
  llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
2278
208
      SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2279
208
  VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
2280
208
  return VTablePtrType;
2281
664
}
2282
2283
671
StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
2284
  // Copy the gdb compatible name on the side and use its reference.
2285
671
  return internString("_vptr$", RD->getNameAsString());
2286
671
}
2287
2288
StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
2289
                                                 DynamicInitKind StubKind,
2290
527
                                                 llvm::Function *InitFn) {
2291
  // If we're not emitting codeview, use the mangled name. For Itanium, this is
2292
  // arbitrary.
2293
527
  if (!CGM.getCodeGenOpts().EmitCodeView ||
2294
527
      
StubKind == DynamicInitKind::GlobalArrayDestructor22
)
2295
507
    return InitFn->getName();
2296
2297
  // Print the normal qualified name for the variable, then break off the last
2298
  // NNS, and add the appropriate other text. Clang always prints the global
2299
  // variable name without template arguments, so we can use rsplit("::") and
2300
  // then recombine the pieces.
2301
20
  SmallString<128> QualifiedGV;
2302
20
  StringRef Quals;
2303
20
  StringRef GVName;
2304
20
  {
2305
20
    llvm::raw_svector_ostream OS(QualifiedGV);
2306
20
    VD->printQualifiedName(OS, getPrintingPolicy());
2307
20
    std::tie(Quals, GVName) = OS.str().rsplit("::");
2308
20
    if (GVName.empty())
2309
15
      std::swap(Quals, GVName);
2310
20
  }
2311
2312
20
  SmallString<128> InitName;
2313
20
  llvm::raw_svector_ostream OS(InitName);
2314
20
  if (!Quals.empty())
2315
5
    OS << Quals << "::";
2316
2317
20
  switch (StubKind) {
2318
0
  case DynamicInitKind::NoStub:
2319
0
  case DynamicInitKind::GlobalArrayDestructor:
2320
0
    llvm_unreachable("not an initializer");
2321
13
  case DynamicInitKind::Initializer:
2322
13
    OS << "`dynamic initializer for '";
2323
13
    break;
2324
7
  case DynamicInitKind::AtExit:
2325
7
    OS << "`dynamic atexit destructor for '";
2326
7
    break;
2327
20
  }
2328
2329
20
  OS << GVName;
2330
2331
  // Add any template specialization args.
2332
20
  if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2333
2
    printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
2334
2
                              getPrintingPolicy());
2335
2
  }
2336
2337
20
  OS << '\'';
2338
2339
20
  return internString(OS.str());
2340
20
}
2341
2342
void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2343
102k
                                    SmallVectorImpl<llvm::Metadata *> &EltTys) {
2344
  // If this class is not dynamic then there is not any vtable info to collect.
2345
102k
  if (!RD->isDynamicClass())
2346
99.9k
    return;
2347
2348
  // Don't emit any vtable shape or vptr info if this class doesn't have an
2349
  // extendable vfptr. This can happen if the class doesn't have virtual
2350
  // methods, or in the MS ABI if those virtual methods only come from virtually
2351
  // inherited bases.
2352
2.14k
  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2353
2.14k
  if (!RL.hasExtendableVFPtr())
2354
3
    return;
2355
2356
  // CodeView needs to know how large the vtable of every dynamic class is, so
2357
  // emit a special named pointer type into the element list. The vptr type
2358
  // points to this type as well.
2359
2.13k
  llvm::DIType *VPtrTy = nullptr;
2360
2.13k
  bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2361
2.13k
                         
CGM.getTarget().getCXXABI().isMicrosoft()10
;
2362
2.13k
  if (NeedVTableShape) {
2363
10
    uint64_t PtrWidth =
2364
10
        CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2365
10
    const VTableLayout &VFTLayout =
2366
10
        CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
2367
10
    unsigned VSlotCount =
2368
10
        VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
2369
10
    unsigned VTableWidth = PtrWidth * VSlotCount;
2370
10
    unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2371
10
    Optional<unsigned> DWARFAddressSpace =
2372
10
        CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2373
2374
    // Create a very wide void* type and insert it directly in the element list.
2375
10
    llvm::DIType *VTableType = DBuilder.createPointerType(
2376
10
        nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2377
10
    EltTys.push_back(VTableType);
2378
2379
    // The vptr is a pointer to this special vtable type.
2380
10
    VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2381
10
  }
2382
2383
  // If there is a primary base then the artificial vptr member lives there.
2384
2.13k
  if (RL.getPrimaryBase())
2385
1.46k
    return;
2386
2387
671
  if (!VPtrTy)
2388
664
    VPtrTy = getOrCreateVTablePtrType(Unit);
2389
2390
671
  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2391
671
  llvm::DIType *VPtrMember =
2392
671
      DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2393
671
                                llvm::DINode::FlagArtificial, VPtrTy);
2394
671
  EltTys.push_back(VPtrMember);
2395
671
}
2396
2397
llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
2398
0
                                                 SourceLocation Loc) {
2399
0
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2400
0
  llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
2401
0
  return T;
2402
0
}
2403
2404
llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
2405
520
                                                    SourceLocation Loc) {
2406
520
  return getOrCreateStandaloneType(D, Loc);
2407
520
}
2408
2409
llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
2410
163k
                                                     SourceLocation Loc) {
2411
163k
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2412
0
  assert(!D.isNull() && "null type");
2413
0
  llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
2414
163k
  assert(T && "could not create debug info for type");
2415
2416
0
  RetainedTypes.push_back(D.getAsOpaquePtr());
2417
163k
  return T;
2418
163k
}
2419
2420
void CGDebugInfo::addHeapAllocSiteMetadata(llvm::CallBase *CI,
2421
                                           QualType AllocatedTy,
2422
692
                                           SourceLocation Loc) {
2423
692
  if (CGM.getCodeGenOpts().getDebugInfo() <=
2424
692
      codegenoptions::DebugLineTablesOnly)
2425
1
    return;
2426
691
  llvm::MDNode *node;
2427
691
  if (AllocatedTy->isVoidType())
2428
3
    node = llvm::MDNode::get(CGM.getLLVMContext(), None);
2429
688
  else
2430
688
    node = getOrCreateType(AllocatedTy, getOrCreateFile(Loc));
2431
2432
691
  CI->setMetadata("heapallocsite", node);
2433
691
}
2434
2435
437k
void CGDebugInfo::completeType(const EnumDecl *ED) {
2436
437k
  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2437
4
    return;
2438
437k
  QualType Ty = CGM.getContext().getEnumType(ED);
2439
437k
  void *TyPtr = Ty.getAsOpaquePtr();
2440
437k
  auto I = TypeCache.find(TyPtr);
2441
437k
  if (I == TypeCache.end() || 
!cast<llvm::DIType>(I->second)->isForwardDecl()2.11k
)
2442
436k
    return;
2443
1.02k
  llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
2444
1.02k
  assert(!Res->isForwardDecl());
2445
0
  TypeCache[TyPtr].reset(Res);
2446
1.02k
}
2447
2448
1.21M
void CGDebugInfo::completeType(const RecordDecl *RD) {
2449
1.21M
  if (DebugKind > codegenoptions::LimitedDebugInfo ||
2450
1.21M
      
!CGM.getLangOpts().CPlusPlus1.45k
)
2451
1.21M
    completeRequiredType(RD);
2452
1.21M
}
2453
2454
/// Return true if the class or any of its methods are marked dllimport.
2455
800
static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
2456
800
  if (RD->hasAttr<DLLImportAttr>())
2457
4
    return true;
2458
796
  for (const CXXMethodDecl *MD : RD->methods())
2459
2.88k
    if (MD->hasAttr<DLLImportAttr>())
2460
2
      return true;
2461
794
  return false;
2462
796
}
2463
2464
/// Does a type definition exist in an imported clang module?
2465
249k
static bool isDefinedInClangModule(const RecordDecl *RD) {
2466
  // Only definitions that where imported from an AST file come from a module.
2467
249k
  if (!RD || 
!RD->isFromASTFile()243k
)
2468
246k
    return false;
2469
  // Anonymous entities cannot be addressed. Treat them as not from module.
2470
3.22k
  if (!RD->isExternallyVisible() && 
RD->getName().empty()20
)
2471
16
    return false;
2472
3.20k
  if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
2473
2.83k
    if (!CXXDecl->isCompleteDefinition())
2474
1
      return false;
2475
    // Check wether RD is a template.
2476
2.83k
    auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2477
2.83k
    if (TemplateKind != TSK_Undeclared) {
2478
      // Unfortunately getOwningModule() isn't accurate enough to find the
2479
      // owning module of a ClassTemplateSpecializationDecl that is inside a
2480
      // namespace spanning multiple modules.
2481
1.98k
      bool Explicit = false;
2482
1.98k
      if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2483
1.71k
        Explicit = TD->isExplicitInstantiationOrSpecialization();
2484
1.98k
      if (!Explicit && 
CXXDecl->getEnclosingNamespaceContext()1.82k
)
2485
1.82k
        return false;
2486
      // This is a template, check the origin of the first member.
2487
157
      if (CXXDecl->field_begin() == CXXDecl->field_end())
2488
129
        return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2489
28
      if (!CXXDecl->field_begin()->isFromASTFile())
2490
0
        return false;
2491
28
    }
2492
2.83k
  }
2493
1.24k
  return true;
2494
3.20k
}
2495
2496
3.08k
void CGDebugInfo::completeClassData(const RecordDecl *RD) {
2497
3.08k
  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2498
2.91k
    if (CXXRD->isDynamicClass() &&
2499
2.91k
        CGM.getVTableLinkage(CXXRD) ==
2500
918
            llvm::GlobalValue::AvailableExternallyLinkage &&
2501
2.91k
        
!isClassOrMethodDLLImport(CXXRD)2
)
2502
1
      return;
2503
2504
3.08k
  if (DebugTypeExtRefs && 
isDefinedInClangModule(RD->getDefinition())1.72k
)
2505
5
    return;
2506
2507
3.08k
  completeClass(RD);
2508
3.08k
}
2509
2510
3.08k
void CGDebugInfo::completeClass(const RecordDecl *RD) {
2511
3.08k
  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2512
20
    return;
2513
3.06k
  QualType Ty = CGM.getContext().getRecordType(RD);
2514
3.06k
  void *TyPtr = Ty.getAsOpaquePtr();
2515
3.06k
  auto I = TypeCache.find(TyPtr);
2516
3.06k
  if (I != TypeCache.end() && 
!cast<llvm::DIType>(I->second)->isForwardDecl()3.05k
)
2517
627
    return;
2518
2.43k
  llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
2519
2.43k
  assert(!Res->isForwardDecl());
2520
0
  TypeCache[TyPtr].reset(Res);
2521
2.43k
}
2522
2523
static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
2524
38
                                        CXXRecordDecl::method_iterator End) {
2525
38
  for (CXXMethodDecl *MD : llvm::make_range(I, End))
2526
69
    if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
2527
27
      if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
2528
27
          
!MD->getMemberSpecializationInfo()->isExplicitSpecialization()10
)
2529
8
        return true;
2530
30
  return false;
2531
38
}
2532
2533
174
static bool canUseCtorHoming(const CXXRecordDecl *RD) {
2534
  // Constructor homing can be used for classes that cannnot be constructed
2535
  // without emitting code for one of their constructors. This is classes that
2536
  // don't have trivial or constexpr constructors, or can be created from
2537
  // aggregate initialization. Also skip lambda objects because they don't call
2538
  // constructors.
2539
2540
  // Skip this optimization if the class or any of its methods are marked
2541
  // dllimport.
2542
174
  if (isClassOrMethodDLLImport(RD))
2543
0
    return false;
2544
2545
174
  return !RD->isLambda() && 
!RD->isAggregate()172
&&
2546
174
         
!RD->hasTrivialDefaultConstructor()64
&&
2547
174
         
!RD->hasConstexprNonCopyMoveConstructor()54
;
2548
174
}
2549
2550
static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
2551
                                 bool DebugTypeExtRefs, const RecordDecl *RD,
2552
2.30M
                                 const LangOptions &LangOpts) {
2553
2.30M
  if (DebugTypeExtRefs && 
isDefinedInClangModule(RD->getDefinition())247k
)
2554
1.24k
    return true;
2555
2556
2.30M
  if (auto *ES = RD->getASTContext().getExternalSource())
2557
279k
    if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2558
9
      return true;
2559
2560
  // Only emit forward declarations in line tables only to keep debug info size
2561
  // small. This only applies to CodeView, since we don't emit types in DWARF
2562
  // line tables only.
2563
2.30M
  if (DebugKind == codegenoptions::DebugLineTablesOnly)
2564
129
    return true;
2565
2566
2.29M
  if (DebugKind > codegenoptions::LimitedDebugInfo ||
2567
2.29M
      
RD->hasAttr<StandaloneDebugAttr>()3.07k
)
2568
2.29M
    return false;
2569
2570
3.06k
  if (!LangOpts.CPlusPlus)
2571
801
    return false;
2572
2573
2.26k
  if (!RD->isCompleteDefinitionRequired())
2574
207
    return true;
2575
2576
2.05k
  const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2577
2578
2.05k
  if (!CXXDecl)
2579
0
    return false;
2580
2581
  // Only emit complete debug info for a dynamic class when its vtable is
2582
  // emitted.  However, Microsoft debuggers don't resolve type information
2583
  // across DLL boundaries, so skip this optimization if the class or any of its
2584
  // methods are marked dllimport. This isn't a complete solution, since objects
2585
  // without any dllimport methods can be used in one DLL and constructed in
2586
  // another, but it is the current behavior of LimitedDebugInfo.
2587
2.05k
  if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
2588
2.05k
      
!isClassOrMethodDLLImport(CXXDecl)624
)
2589
619
    return true;
2590
2591
1.43k
  TemplateSpecializationKind Spec = TSK_Undeclared;
2592
1.43k
  if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2593
606
    Spec = SD->getSpecializationKind();
2594
2595
1.43k
  if (Spec == TSK_ExplicitInstantiationDeclaration &&
2596
1.43k
      hasExplicitMemberDefinition(CXXDecl->method_begin(),
2597
38
                                  CXXDecl->method_end()))
2598
8
    return true;
2599
2600
  // In constructor homing mode, only emit complete debug info for a class
2601
  // when its constructor is emitted.
2602
1.43k
  if ((DebugKind == codegenoptions::DebugInfoConstructor) &&
2603
1.43k
      
canUseCtorHoming(CXXDecl)174
)
2604
28
    return true;
2605
2606
1.40k
  return false;
2607
1.43k
}
2608
2609
2.17M
void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
2610
2.17M
  if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2611
705
    return;
2612
2613
2.17M
  QualType Ty = CGM.getContext().getRecordType(RD);
2614
2.17M
  llvm::DIType *T = getTypeOrNull(Ty);
2615
2.17M
  if (T && 
T->isForwardDecl()83.8k
)
2616
2.28k
    completeClassData(RD);
2617
2.17M
}
2618
2619
130k
llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
2620
130k
  RecordDecl *RD = Ty->getDecl();
2621
130k
  llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
2622
130k
  if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2623
130k
                                CGM.getLangOpts())) {
2624
1.54k
    if (!T)
2625
1.54k
      T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
2626
1.54k
    return T;
2627
1.54k
  }
2628
2629
128k
  return CreateTypeDefinition(Ty);
2630
130k
}
2631
2632
131k
llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
2633
131k
  RecordDecl *RD = Ty->getDecl();
2634
2635
  // Get overall information about the record type for the debug info.
2636
131k
  llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2637
2638
  // Records and classes and unions can all be recursive.  To handle them, we
2639
  // first generate a debug descriptor for the struct as a forward declaration.
2640
  // Then (if it is a definition) we go through and get debug info for all of
2641
  // its members.  Finally, we create a descriptor for the complete type (which
2642
  // may refer to the forward decl if the struct is recursive) and replace all
2643
  // uses of the forward declaration with the final definition.
2644
131k
  llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty);
2645
2646
131k
  const RecordDecl *D = RD->getDefinition();
2647
131k
  if (!D || 
!D->isCompleteDefinition()118k
)
2648
12.8k
    return FwdDecl;
2649
2650
118k
  if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
2651
102k
    CollectContainingType(CXXDecl, FwdDecl);
2652
2653
  // Push the struct on region stack.
2654
118k
  LexicalBlockStack.emplace_back(&*FwdDecl);
2655
118k
  RegionMap[Ty->getDecl()].reset(FwdDecl);
2656
2657
  // Convert all the elements.
2658
118k
  SmallVector<llvm::Metadata *, 16> EltTys;
2659
  // what about nested types?
2660
2661
  // Note: The split of CXXDecl information here is intentional, the
2662
  // gdb tests will depend on a certain ordering at printout. The debug
2663
  // information offsets are still correct if we merge them all together
2664
  // though.
2665
118k
  const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2666
118k
  if (CXXDecl) {
2667
102k
    CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
2668
102k
    CollectVTableInfo(CXXDecl, DefUnit, EltTys);
2669
102k
  }
2670
2671
  // Collect data fields (including static variables and any initializers).
2672
118k
  CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
2673
118k
  if (CXXDecl)
2674
102k
    CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
2675
2676
118k
  LexicalBlockStack.pop_back();
2677
118k
  RegionMap.erase(Ty->getDecl());
2678
2679
118k
  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2680
118k
  DBuilder.replaceArrays(FwdDecl, Elements);
2681
2682
118k
  if (FwdDecl->isTemporary())
2683
0
    FwdDecl =
2684
0
        llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
2685
2686
118k
  RegionMap[Ty->getDecl()].reset(FwdDecl);
2687
118k
  return FwdDecl;
2688
131k
}
2689
2690
llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2691
4.67k
                                      llvm::DIFile *Unit) {
2692
  // Ignore protocols.
2693
4.67k
  return getOrCreateType(Ty->getBaseType(), Unit);
2694
4.67k
}
2695
2696
llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2697
667
                                      llvm::DIFile *Unit) {
2698
  // Ignore protocols.
2699
667
  SourceLocation Loc = Ty->getDecl()->getLocation();
2700
2701
  // Use Typedefs to represent ObjCTypeParamType.
2702
667
  return DBuilder.createTypedef(
2703
667
      getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2704
667
      Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2705
667
      getDeclContextDescriptor(Ty->getDecl()));
2706
667
}
2707
2708
/// \return true if Getter has the default name for the property PD.
2709
static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2710
12.0k
                                 const ObjCMethodDecl *Getter) {
2711
12.0k
  assert(PD);
2712
12.0k
  if (!Getter)
2713
0
    return true;
2714
2715
12.0k
  assert(Getter->getDeclName().isObjCZeroArgSelector());
2716
0
  return PD->getName() ==
2717
12.0k
         Getter->getDeclName().getObjCSelector().getNameForSlot(0);
2718
12.0k
}
2719
2720
/// \return true if Setter has the default name for the property PD.
2721
static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2722
12.0k
                                 const ObjCMethodDecl *Setter) {
2723
12.0k
  assert(PD);
2724
12.0k
  if (!Setter)
2725
7.44k
    return true;
2726
2727
4.58k
  assert(Setter->getDeclName().isObjCOneArgSelector());
2728
0
  return SelectorTable::constructSetterName(PD->getName()) ==
2729
4.58k
         Setter->getDeclName().getObjCSelector().getNameForSlot(0);
2730
12.0k
}
2731
2732
llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2733
4.08k
                                      llvm::DIFile *Unit) {
2734
4.08k
  ObjCInterfaceDecl *ID = Ty->getDecl();
2735
4.08k
  if (!ID)
2736
0
    return nullptr;
2737
2738
  // Return a forward declaration if this type was imported from a clang module,
2739
  // and this is not the compile unit with the implementation of the type (which
2740
  // may contain hidden ivars).
2741
4.08k
  if (DebugTypeExtRefs && 
ID->isFromASTFile()2.32k
&&
ID->getDefinition()682
&&
2742
4.08k
      
!ID->getImplementation()656
)
2743
650
    return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2744
650
                                      ID->getName(),
2745
650
                                      getDeclContextDescriptor(ID), Unit, 0);
2746
2747
  // Get overall information about the record type for the debug info.
2748
3.43k
  llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2749
3.43k
  unsigned Line = getLineNumber(ID->getLocation());
2750
3.43k
  auto RuntimeLang =
2751
3.43k
      static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2752
2753
  // If this is just a forward declaration return a special forward-declaration
2754
  // debug type since we won't be able to lay out the entire type.
2755
3.43k
  ObjCInterfaceDecl *Def = ID->getDefinition();
2756
3.43k
  if (!Def || 
!Def->getImplementation()2.89k
) {
2757
2.92k
    llvm::DIScope *Mod = getParentModuleOrNull(ID);
2758
2.92k
    llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
2759
2.92k
        llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? 
Mod1.49k
:
TheCU1.43k
,
2760
2.92k
        DefUnit, Line, RuntimeLang);
2761
2.92k
    ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
2762
2.92k
    return FwdDecl;
2763
2.92k
  }
2764
2765
517
  return CreateTypeDefinition(Ty, Unit);
2766
3.43k
}
2767
2768
llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
2769
598k
                                                  bool CreateSkeletonCU) {
2770
  // Use the Module pointer as the key into the cache. This is a
2771
  // nullptr if the "Module" is a PCH, which is safe because we don't
2772
  // support chained PCH debug info, so there can only be a single PCH.
2773
598k
  const Module *M = Mod.getModuleOrNull();
2774
598k
  auto ModRef = ModuleCache.find(M);
2775
598k
  if (ModRef != ModuleCache.end())
2776
572k
    return cast<llvm::DIModule>(ModRef->second);
2777
2778
  // Macro definitions that were defined with "-D" on the command line.
2779
26.2k
  SmallString<128> ConfigMacros;
2780
26.2k
  {
2781
26.2k
    llvm::raw_svector_ostream OS(ConfigMacros);
2782
26.2k
    const auto &PPOpts = CGM.getPreprocessorOpts();
2783
26.2k
    unsigned I = 0;
2784
    // Translate the macro definitions back into a command line.
2785
35.6k
    for (auto &M : PPOpts.Macros) {
2786
35.6k
      if (++I > 1)
2787
9.49k
        OS << " ";
2788
35.6k
      const std::string &Macro = M.first;
2789
35.6k
      bool Undef = M.second;
2790
35.6k
      OS << "\"-" << (Undef ? 
'U'1
:
'D'35.6k
);
2791
35.6k
      for (char c : Macro)
2792
883k
        switch (c) {
2793
0
        case '\\':
2794
0
          OS << "\\\\";
2795
0
          break;
2796
0
        case '"':
2797
0
          OS << "\\\"";
2798
0
          break;
2799
883k
        default:
2800
883k
          OS << c;
2801
883k
        }
2802
35.6k
      OS << '\"';
2803
35.6k
    }
2804
26.2k
  }
2805
2806
26.2k
  bool IsRootModule = M ? 
!M->Parent26.1k
:
true103
;
2807
  // When a module name is specified as -fmodule-name, that module gets a
2808
  // clang::Module object, but it won't actually be built or imported; it will
2809
  // be textual.
2810
26.2k
  if (CreateSkeletonCU && 
IsRootModule9.78k
&&
Mod.getASTFile().empty()1.51k
&&
M1
)
2811
1
    assert(StringRef(M->Name).startswith(CGM.getLangOpts().ModuleName) &&
2812
26.2k
           "clang module without ASTFile must be specified by -fmodule-name");
2813
2814
  // Return a StringRef to the remapped Path.
2815
27.7k
  auto RemapPath = [this](StringRef Path) -> std::string {
2816
27.7k
    std::string Remapped = remapDIPath(Path);
2817
27.7k
    StringRef Relative(Remapped);
2818
27.7k
    StringRef CompDir = TheCU->getDirectory();
2819
27.7k
    if (Relative.consume_front(CompDir))
2820
114
      Relative.consume_front(llvm::sys::path::get_separator());
2821
2822
27.7k
    return Relative.str();
2823
27.7k
  };
2824
2825
26.2k
  if (CreateSkeletonCU && 
IsRootModule9.78k
&&
!Mod.getASTFile().empty()1.51k
) {
2826
    // PCH files don't have a signature field in the control block,
2827
    // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2828
    // We use the lower 64 bits for debug info.
2829
2830
1.51k
    uint64_t Signature = 0;
2831
1.51k
    if (const auto &ModSig = Mod.getSignature())
2832
1.49k
      Signature = ModSig.truncatedValue();
2833
22
    else
2834
22
      Signature = ~1ULL;
2835
2836
1.51k
    llvm::DIBuilder DIB(CGM.getModule());
2837
1.51k
    SmallString<0> PCM;
2838
1.51k
    if (!llvm::sys::path::is_absolute(Mod.getASTFile()))
2839
10
      PCM = Mod.getPath();
2840
1.51k
    llvm::sys::path::append(PCM, Mod.getASTFile());
2841
1.51k
    DIB.createCompileUnit(
2842
1.51k
        TheCU->getSourceLanguage(),
2843
        // TODO: Support "Source" from external AST providers?
2844
1.51k
        DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
2845
1.51k
        TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
2846
1.51k
        llvm::DICompileUnit::FullDebug, Signature);
2847
1.51k
    DIB.finalize();
2848
1.51k
  }
2849
2850
26.2k
  llvm::DIModule *Parent =
2851
26.2k
      IsRootModule ? 
nullptr1.85k
2852
26.2k
                   : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
2853
24.3k
                                          CreateSkeletonCU);
2854
26.2k
  std::string IncludePath = Mod.getPath().str();
2855
26.2k
  llvm::DIModule *DIMod =
2856
26.2k
      DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2857
26.2k
                            RemapPath(IncludePath));
2858
26.2k
  ModuleCache[M].reset(DIMod);
2859
26.2k
  return DIMod;
2860
26.2k
}
2861
2862
llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2863
3.24k
                                                llvm::DIFile *Unit) {
2864
3.24k
  ObjCInterfaceDecl *ID = Ty->getDecl();
2865
3.24k
  llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2866
3.24k
  unsigned Line = getLineNumber(ID->getLocation());
2867
3.24k
  unsigned RuntimeLang = TheCU->getSourceLanguage();
2868
2869
  // Bit size, align and offset of the type.
2870
3.24k
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
2871
3.24k
  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2872
2873
3.24k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2874
3.24k
  if (ID->getImplementation())
2875
521
    Flags |= llvm::DINode::FlagObjcClassComplete;
2876
2877
3.24k
  llvm::DIScope *Mod = getParentModuleOrNull(ID);
2878
3.24k
  llvm::DICompositeType *RealDecl = DBuilder.createStructType(
2879
3.24k
      Mod ? 
Mod1.33k
:
Unit1.91k
, ID->getName(), DefUnit, Line, Size, Align, Flags,
2880
3.24k
      nullptr, llvm::DINodeArray(), RuntimeLang);
2881
2882
3.24k
  QualType QTy(Ty, 0);
2883
3.24k
  TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
2884
2885
  // Push the struct on region stack.
2886
3.24k
  LexicalBlockStack.emplace_back(RealDecl);
2887
3.24k
  RegionMap[Ty->getDecl()].reset(RealDecl);
2888
2889
  // Convert all the elements.
2890
3.24k
  SmallVector<llvm::Metadata *, 16> EltTys;
2891
2892
3.24k
  ObjCInterfaceDecl *SClass = ID->getSuperClass();
2893
3.24k
  if (SClass) {
2894
2.85k
    llvm::DIType *SClassTy =
2895
2.85k
        getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
2896
2.85k
    if (!SClassTy)
2897
0
      return nullptr;
2898
2899
2.85k
    llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
2900
2.85k
                                                      llvm::DINode::FlagZero);
2901
2.85k
    EltTys.push_back(InhTag);
2902
2.85k
  }
2903
2904
  // Create entries for all of the properties.
2905
11.8k
  
auto AddProperty = [&](const ObjCPropertyDecl *PD) 3.24k
{
2906
11.8k
    SourceLocation Loc = PD->getLocation();
2907
11.8k
    llvm::DIFile *PUnit = getOrCreateFile(Loc);
2908
11.8k
    unsigned PLine = getLineNumber(Loc);
2909
11.8k
    ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2910
11.8k
    ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2911
11.8k
    llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2912
11.8k
        PD->getName(), PUnit, PLine,
2913
11.8k
        hasDefaultGetterName(PD, Getter) ? 
""11.2k
2914
11.8k
                                         : 
getSelectorName(PD->getGetterName())605
,
2915
11.8k
        hasDefaultSetterName(PD, Setter) ? 
""11.8k
2916
11.8k
                                         : 
getSelectorName(PD->getSetterName())5
,
2917
11.8k
        PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
2918
11.8k
    EltTys.push_back(PropertyNode);
2919
11.8k
  };
2920
3.24k
  {
2921
    // Use 'char' for the isClassProperty bit as DenseSet requires space for
2922
    // empty/tombstone keys in the data type (and bool is too small for that).
2923
3.24k
    typedef std::pair<char, const IdentifierInfo *> IsClassAndIdent;
2924
    /// List of already emitted properties. Two distinct class and instance
2925
    /// properties can share the same identifier (but not two instance
2926
    /// properties or two class properties).
2927
3.24k
    llvm::DenseSet<IsClassAndIdent> PropertySet;
2928
    /// Returns the IsClassAndIdent key for the given property.
2929
11.8k
    auto GetIsClassAndIdent = [](const ObjCPropertyDecl *PD) {
2930
11.8k
      return std::make_pair(PD->isClassProperty(), PD->getIdentifier());
2931
11.8k
    };
2932
3.24k
    for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
2933
51
      for (auto *PD : ClassExt->properties()) {
2934
38
        PropertySet.insert(GetIsClassAndIdent(PD));
2935
38
        AddProperty(PD);
2936
38
      }
2937
11.7k
    for (const auto *PD : ID->properties()) {
2938
      // Don't emit duplicate metadata for properties that were already in a
2939
      // class extension.
2940
11.7k
      if (!PropertySet.insert(GetIsClassAndIdent(PD)).second)
2941
2
        continue;
2942
11.7k
      AddProperty(PD);
2943
11.7k
    }
2944
3.24k
  }
2945
2946
3.24k
  const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2947
3.24k
  unsigned FieldNo = 0;
2948
7.27k
  for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2949
4.02k
       Field = Field->getNextIvar(), ++FieldNo) {
2950
4.02k
    llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2951
4.02k
    if (!FieldTy)
2952
0
      return nullptr;
2953
2954
4.02k
    StringRef FieldName = Field->getName();
2955
2956
    // Ignore unnamed fields.
2957
4.02k
    if (FieldName.empty())
2958
14
      continue;
2959
2960
    // Get the location for the field.
2961
4.01k
    llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
2962
4.01k
    unsigned FieldLine = getLineNumber(Field->getLocation());
2963
4.01k
    QualType FType = Field->getType();
2964
4.01k
    uint64_t FieldSize = 0;
2965
4.01k
    uint32_t FieldAlign = 0;
2966
2967
4.01k
    if (!FType->isIncompleteArrayType()) {
2968
2969
      // Bit size, align and offset of the type.
2970
4.01k
      FieldSize = Field->isBitField()
2971
4.01k
                      ? 
Field->getBitWidthValue(CGM.getContext())245
2972
4.01k
                      : 
CGM.getContext().getTypeSize(FType)3.76k
;
2973
4.01k
      FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2974
4.01k
    }
2975
2976
4.01k
    uint64_t FieldOffset;
2977
4.01k
    if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2978
      // We don't know the runtime offset of an ivar if we're using the
2979
      // non-fragile ABI.  For bitfields, use the bit offset into the first
2980
      // byte of storage of the bitfield.  For other fields, use zero.
2981
4.00k
      if (Field->isBitField()) {
2982
245
        FieldOffset =
2983
245
            CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
2984
245
        FieldOffset %= CGM.getContext().getCharWidth();
2985
3.76k
      } else {
2986
3.76k
        FieldOffset = 0;
2987
3.76k
      }
2988
4.00k
    } else {
2989
6
      FieldOffset = RL.getFieldOffset(FieldNo);
2990
6
    }
2991
2992
4.01k
    llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2993
4.01k
    if (Field->getAccessControl() == ObjCIvarDecl::Protected)
2994
1.16k
      Flags = llvm::DINode::FlagProtected;
2995
2.84k
    else if (Field->getAccessControl() == ObjCIvarDecl::Private)
2996
2.69k
      Flags = llvm::DINode::FlagPrivate;
2997
157
    else if (Field->getAccessControl() == ObjCIvarDecl::Public)
2998
121
      Flags = llvm::DINode::FlagPublic;
2999
3000
4.01k
    llvm::MDNode *PropertyNode = nullptr;
3001
4.01k
    if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
3002
688
      if (ObjCPropertyImplDecl *PImpD =
3003
688
              ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
3004
218
        if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
3005
218
          SourceLocation Loc = PD->getLocation();
3006
218
          llvm::DIFile *PUnit = getOrCreateFile(Loc);
3007
218
          unsigned PLine = getLineNumber(Loc);
3008
218
          ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
3009
218
          ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
3010
218
          PropertyNode = DBuilder.createObjCProperty(
3011
218
              PD->getName(), PUnit, PLine,
3012
218
              hasDefaultGetterName(PD, Getter)
3013
218
                  ? 
""214
3014
218
                  : 
getSelectorName(PD->getGetterName())4
,
3015
218
              hasDefaultSetterName(PD, Setter)
3016
218
                  ? 
""214
3017
218
                  : 
getSelectorName(PD->getSetterName())4
,
3018
218
              PD->getPropertyAttributes(),
3019
218
              getOrCreateType(PD->getType(), PUnit));
3020
218
        }
3021
218
      }
3022
688
    }
3023
4.01k
    FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
3024
4.01k
                                      FieldSize, FieldAlign, FieldOffset, Flags,
3025
4.01k
                                      FieldTy, PropertyNode);
3026
4.01k
    EltTys.push_back(FieldTy);
3027
4.01k
  }
3028
3029
3.24k
  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3030
3.24k
  DBuilder.replaceArrays(RealDecl, Elements);
3031
3032
3.24k
  LexicalBlockStack.pop_back();
3033
3.24k
  return RealDecl;
3034
3.24k
}
3035
3036
llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
3037
1.40k
                                      llvm::DIFile *Unit) {
3038
1.40k
  llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3039
1.40k
  int64_t Count = Ty->getNumElements();
3040
3041
1.40k
  llvm::Metadata *Subscript;
3042
1.40k
  QualType QTy(Ty, 0);
3043
1.40k
  auto SizeExpr = SizeExprCache.find(QTy);
3044
1.40k
  if (SizeExpr != SizeExprCache.end())
3045
0
    Subscript = DBuilder.getOrCreateSubrange(
3046
0
        SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/,
3047
0
        nullptr /*upperBound*/, nullptr /*stride*/);
3048
1.40k
  else {
3049
1.40k
    auto *CountNode =
3050
1.40k
        llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3051
1.40k
            llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : 
-10
));
3052
1.40k
    Subscript = DBuilder.getOrCreateSubrange(
3053
1.40k
        CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3054
1.40k
        nullptr /*stride*/);
3055
1.40k
  }
3056
1.40k
  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
3057
3058
1.40k
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
3059
1.40k
  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3060
3061
1.40k
  return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
3062
1.40k
}
3063
3064
llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty,
3065
1
                                      llvm::DIFile *Unit) {
3066
  // FIXME: Create another debug type for matrices
3067
  // For the time being, it treats it like a nested ArrayType.
3068
3069
1
  llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3070
1
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
3071
1
  uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3072
3073
  // Create ranges for both dimensions.
3074
1
  llvm::SmallVector<llvm::Metadata *, 2> Subscripts;
3075
1
  auto *ColumnCountNode =
3076
1
      llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3077
1
          llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns()));
3078
1
  auto *RowCountNode =
3079
1
      llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3080
1
          llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows()));
3081
1
  Subscripts.push_back(DBuilder.getOrCreateSubrange(
3082
1
      ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3083
1
      nullptr /*stride*/));
3084
1
  Subscripts.push_back(DBuilder.getOrCreateSubrange(
3085
1
      RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3086
1
      nullptr /*stride*/));
3087
1
  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3088
1
  return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray);
3089
1
}
3090
3091
11.3k
llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
3092
11.3k
  uint64_t Size;
3093
11.3k
  uint32_t Align;
3094
3095
  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
3096
11.3k
  if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3097
42
    Size = 0;
3098
42
    Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
3099
42
                                   CGM.getContext());
3100
11.3k
  } else if (Ty->isIncompleteArrayType()) {
3101
147
    Size = 0;
3102
147
    if (Ty->getElementType()->isIncompleteType())
3103
1
      Align = 0;
3104
146
    else
3105
146
      Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
3106
11.2k
  } else if (Ty->isIncompleteType()) {
3107
2
    Size = 0;
3108
2
    Align = 0;
3109
11.2k
  } else {
3110
    // Size and align of the whole array, not the element type.
3111
11.2k
    Size = CGM.getContext().getTypeSize(Ty);
3112
11.2k
    Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3113
11.2k
  }
3114
3115
  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
3116
  // interior arrays, do we care?  Why aren't nested arrays represented the
3117
  // obvious/recursive way?
3118
11.3k
  SmallVector<llvm::Metadata *, 8> Subscripts;
3119
11.3k
  QualType EltTy(Ty, 0);
3120
22.8k
  while ((Ty = dyn_cast<ArrayType>(EltTy))) {
3121
    // If the number of elements is known, then count is that number. Otherwise,
3122
    // it's -1. This allows us to represent a subrange with an array of 0
3123
    // elements, like this:
3124
    //
3125
    //   struct foo {
3126
    //     int x[0];
3127
    //   };
3128
11.4k
    int64_t Count = -1; // Count == -1 is an unbounded array.
3129
11.4k
    if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
3130
11.2k
      Count = CAT->getSize().getZExtValue();
3131
190
    else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3132
43
      if (Expr *Size = VAT->getSizeExpr()) {
3133
42
        Expr::EvalResult Result;
3134
42
        if (Size->EvaluateAsInt(Result, CGM.getContext()))
3135
1
          Count = Result.Val.getInt().getExtValue();
3136
42
      }
3137
43
    }
3138
3139
11.4k
    auto SizeNode = SizeExprCache.find(EltTy);
3140
11.4k
    if (SizeNode != SizeExprCache.end())
3141
38
      Subscripts.push_back(DBuilder.getOrCreateSubrange(
3142
38
          SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/,
3143
38
          nullptr /*upperBound*/, nullptr /*stride*/));
3144
11.4k
    else {
3145
11.4k
      auto *CountNode =
3146
11.4k
          llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3147
11.4k
              llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count));
3148
11.4k
      Subscripts.push_back(DBuilder.getOrCreateSubrange(
3149
11.4k
          CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3150
11.4k
          nullptr /*stride*/));
3151
11.4k
    }
3152
11.4k
    EltTy = Ty->getElementType();
3153
11.4k
  }
3154
3155
11.3k
  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3156
3157
11.3k
  return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
3158
11.3k
                                  SubscriptArray);
3159
11.3k
}
3160
3161
llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
3162
85.5k
                                      llvm::DIFile *Unit) {
3163
85.5k
  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
3164
85.5k
                               Ty->getPointeeType(), Unit);
3165
85.5k
}
3166
3167
llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
3168
18.5k
                                      llvm::DIFile *Unit) {
3169
18.5k
  llvm::dwarf::Tag Tag = llvm::dwarf::DW_TAG_rvalue_reference_type;
3170
  // DW_TAG_rvalue_reference_type was introduced in DWARF 4.
3171
18.5k
  if (CGM.getCodeGenOpts().DebugStrictDwarf &&
3172
18.5k
      
CGM.getCodeGenOpts().DwarfVersion < 42
)
3173
1
    Tag = llvm::dwarf::DW_TAG_reference_type;
3174
3175
18.5k
  return CreatePointerLikeType(Tag, Ty, Ty->getPointeeType(), Unit);
3176
18.5k
}
3177
3178
llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
3179
53
                                      llvm::DIFile *U) {
3180
53
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3181
53
  uint64_t Size = 0;
3182
3183
53
  if (!Ty->isIncompleteType()) {
3184
50
    Size = CGM.getContext().getTypeSize(Ty);
3185
3186
    // Set the MS inheritance model. There is no flag for the unspecified model.
3187
50
    if (CGM.getTarget().getCXXABI().isMicrosoft()) {
3188
16
      switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
3189
10
      case MSInheritanceModel::Single:
3190
10
        Flags |= llvm::DINode::FlagSingleInheritance;
3191
10
        break;
3192
2
      case MSInheritanceModel::Multiple:
3193
2
        Flags |= llvm::DINode::FlagMultipleInheritance;
3194
2
        break;
3195
2
      case MSInheritanceModel::Virtual:
3196
2
        Flags |= llvm::DINode::FlagVirtualInheritance;
3197
2
        break;
3198
2
      case MSInheritanceModel::Unspecified:
3199
2
        break;
3200
16
      }
3201
16
    }
3202
50
  }
3203
3204
53
  llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
3205
53
  if (Ty->isMemberDataPointerType())
3206
23
    return DBuilder.createMemberPointerType(
3207
23
        getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
3208
23
        Flags);
3209
3210
30
  const FunctionProtoType *FPT =
3211
30
      Ty->getPointeeType()->getAs<FunctionProtoType>();
3212
30
  return DBuilder.createMemberPointerType(
3213
30
      getOrCreateInstanceMethodType(
3214
30
          CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),
3215
30
          FPT, U, false),
3216
30
      ClassType, Size, /*Align=*/0, Flags);
3217
53
}
3218
3219
977
llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
3220
977
  auto *FromTy = getOrCreateType(Ty->getValueType(), U);
3221
977
  return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
3222
977
}
3223
3224
0
llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
3225
0
  return getOrCreateType(Ty->getElementType(), U);
3226
0
}
3227
3228
14.2k
llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
3229
14.2k
  const EnumDecl *ED = Ty->getDecl();
3230
3231
14.2k
  uint64_t Size = 0;
3232
14.2k
  uint32_t Align = 0;
3233
14.2k
  if (!ED->getTypeForDecl()->isIncompleteType()) {
3234
14.2k
    Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
3235
14.2k
    Align = getDeclAlignIfRequired(ED, CGM.getContext());
3236
14.2k
  }
3237
3238
14.2k
  SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3239
3240
14.2k
  bool isImportedFromModule =
3241
14.2k
      DebugTypeExtRefs && 
ED->isFromASTFile()12.5k
&&
ED->getDefinition()199
;
3242
3243
  // If this is just a forward declaration, construct an appropriately
3244
  // marked node and just return it.
3245
14.2k
  if (isImportedFromModule || 
!ED->getDefinition()14.0k
) {
3246
    // Note that it is possible for enums to be created as part of
3247
    // their own declcontext. In this case a FwdDecl will be created
3248
    // twice. This doesn't cause a problem because both FwdDecls are
3249
    // entered into the ReplaceMap: finalize() will replace the first
3250
    // FwdDecl with the second and then replace the second with
3251
    // complete type.
3252
1.23k
    llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
3253
1.23k
    llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3254
1.23k
    llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
3255
1.23k
        llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
3256
3257
1.23k
    unsigned Line = getLineNumber(ED->getLocation());
3258
1.23k
    StringRef EDName = ED->getName();
3259
1.23k
    llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
3260
1.23k
        llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
3261
1.23k
        0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
3262
3263
1.23k
    ReplaceMap.emplace_back(
3264
1.23k
        std::piecewise_construct, std::make_tuple(Ty),
3265
1.23k
        std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
3266
1.23k
    return RetTy;
3267
1.23k
  }
3268
3269
13.0k
  return CreateTypeDefinition(Ty);
3270
14.2k
}
3271
3272
14.0k
llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
3273
14.0k
  const EnumDecl *ED = Ty->getDecl();
3274
14.0k
  uint64_t Size = 0;
3275
14.0k
  uint32_t Align = 0;
3276
14.0k
  if (!ED->getTypeForDecl()->isIncompleteType()) {
3277
14.0k
    Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
3278
14.0k
    Align = getDeclAlignIfRequired(ED, CGM.getContext());
3279
14.0k
  }
3280
3281
14.0k
  SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3282
3283
14.0k
  SmallVector<llvm::Metadata *, 16> Enumerators;
3284
14.0k
  ED = ED->getDefinition();
3285
114k
  for (const auto *Enum : ED->enumerators()) {
3286
114k
    Enumerators.push_back(
3287
114k
        DBuilder.createEnumerator(Enum->getName(), Enum->getInitVal()));
3288
114k
  }
3289
3290
  // Return a CompositeType for the enum itself.
3291
14.0k
  llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
3292
3293
14.0k
  llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3294
14.0k
  unsigned Line = getLineNumber(ED->getLocation());
3295
14.0k
  llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
3296
14.0k
  llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
3297
14.0k
  return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
3298
14.0k
                                        Line, Size, Align, EltArray, ClassTy,
3299
14.0k
                                        Identifier, ED->isScoped());
3300
14.0k
}
3301
3302
llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
3303
                                        unsigned MType, SourceLocation LineLoc,
3304
1.40k
                                        StringRef Name, StringRef Value) {
3305
1.40k
  unsigned Line = LineLoc.isInvalid() ? 
01.36k
:
getLineNumber(LineLoc)45
;
3306
1.40k
  return DBuilder.createMacro(Parent, Line, MType, Name, Value);
3307
1.40k
}
3308
3309
llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
3310
                                                    SourceLocation LineLoc,
3311
20
                                                    SourceLocation FileLoc) {
3312
20
  llvm::DIFile *FName = getOrCreateFile(FileLoc);
3313
20
  unsigned Line = LineLoc.isInvalid() ? 
010
:
getLineNumber(LineLoc)10
;
3314
20
  return DBuilder.createTempMacroFile(Parent, Line, FName);
3315
20
}
3316
3317
10.2M
static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
3318
10.2M
  Qualifiers Quals;
3319
10.6M
  do {
3320
10.6M
    Qualifiers InnerQuals = T.getLocalQualifiers();
3321
    // Qualifiers::operator+() doesn't like it if you add a Qualifier
3322
    // that is already there.
3323
10.6M
    Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
3324
10.6M
    Quals += InnerQuals;
3325
10.6M
    QualType LastT = T;
3326
10.6M
    switch (T->getTypeClass()) {
3327
10.2M
    default:
3328
10.2M
      return C.getQualifiedType(T.getTypePtr(), Quals);
3329
81.6k
    case Type::TemplateSpecialization: {
3330
81.6k
      const auto *Spec = cast<TemplateSpecializationType>(T);
3331
81.6k
      if (Spec->isTypeAlias())
3332
17.0k
        return C.getQualifiedType(T.getTypePtr(), Quals);
3333
64.6k
      T = Spec->desugar();
3334
64.6k
      break;
3335
81.6k
    }
3336
5
    case Type::TypeOfExpr:
3337
5
      T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
3338
5
      break;
3339
0
    case Type::TypeOf:
3340
0
      T = cast<TypeOfType>(T)->getUnderlyingType();
3341
0
      break;
3342
1.09k
    case Type::Decltype:
3343
1.09k
      T = cast<DecltypeType>(T)->getUnderlyingType();
3344
1.09k
      break;
3345
183
    case Type::UnaryTransform:
3346
183
      T = cast<UnaryTransformType>(T)->getUnderlyingType();
3347
183
      break;
3348
54.5k
    case Type::Attributed:
3349
54.5k
      T = cast<AttributedType>(T)->getEquivalentType();
3350
54.5k
      break;
3351
128k
    case Type::Elaborated:
3352
128k
      T = cast<ElaboratedType>(T)->getNamedType();
3353
128k
      break;
3354
23.9k
    case Type::Using:
3355
23.9k
      T = cast<UsingType>(T)->getUnderlyingType();
3356
23.9k
      break;
3357
15.3k
    case Type::Paren:
3358
15.3k
      T = cast<ParenType>(T)->getInnerType();
3359
15.3k
      break;
3360
797
    case Type::MacroQualified:
3361
797
      T = cast<MacroQualifiedType>(T)->getUnderlyingType();
3362
797
      break;
3363
80.1k
    case Type::SubstTemplateTypeParm:
3364
80.1k
      T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
3365
80.1k
      break;
3366
360
    case Type::Auto:
3367
361
    case Type::DeducedTemplateSpecialization: {
3368
361
      QualType DT = cast<DeducedType>(T)->getDeducedType();
3369
361
      assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
3370
0
      T = DT;
3371
361
      break;
3372
360
    }
3373
0
    case Type::Adjusted:
3374
8.81k
    case Type::Decayed:
3375
      // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3376
8.81k
      T = cast<AdjustedType>(T)->getAdjustedType();
3377
8.81k
      break;
3378
10.6M
    }
3379
3380
378k
    assert(T != LastT && "Type unwrapping failed to unwrap!");
3381
0
    (void)LastT;
3382
378k
  } while (true);
3383
10.2M
}
3384
3385
6.42M
llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
3386
6.42M
  assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext()));
3387
0
  auto It = TypeCache.find(Ty.getAsOpaquePtr());
3388
6.42M
  if (It != TypeCache.end()) {
3389
    // Verify that the debug info still exists.
3390
2.83M
    if (llvm::Metadata *V = It->second)
3391
2.70M
      return cast<llvm::DIType>(V);
3392
2.83M
  }
3393
3394
3.72M
  return nullptr;
3395
6.42M
}
3396
3397
void CGDebugInfo::completeTemplateDefinition(
3398
8
    const ClassTemplateSpecializationDecl &SD) {
3399
8
  completeUnusedClass(SD);
3400
8
}
3401
3402
90
void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
3403
90
  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3404
4
    return;
3405
3406
86
  completeClassData(&D);
3407
  // In case this type has no member function definitions being emitted, ensure
3408
  // it is retained
3409
86
  RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
3410
86
}
3411
3412
llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit,
3413
3.83M
                                           TypeLoc TL) {
3414
3.83M
  if (Ty.isNull())
3415
0
    return nullptr;
3416
3417
3.83M
  llvm::TimeTraceScope TimeScope("DebugType", [&]() {
3418
0
    std::string Name;
3419
0
    llvm::raw_string_ostream OS(Name);
3420
0
    Ty.print(OS, getPrintingPolicy());
3421
0
    return Name;
3422
0
  });
3423
3424
  // Unwrap the type as needed for debug information.
3425
3.83M
  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
3426
3427
3.83M
  if (auto *T = getTypeOrNull(Ty))
3428
2.60M
    return T;
3429
3430
1.23M
  llvm::DIType *Res = CreateTypeNode(Ty, Unit, TL);
3431
1.23M
  void *TyPtr = Ty.getAsOpaquePtr();
3432
3433
  // And update the type cache.
3434
1.23M
  TypeCache[TyPtr].reset(Res);
3435
3436
1.23M
  return Res;
3437
3.83M
}
3438
3439
1.15M
llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
3440
  // A forward declaration inside a module header does not belong to the module.
3441
1.15M
  if (isa<RecordDecl>(D) && 
!cast<RecordDecl>(D)->getDefinition()202k
)
3442
12.5k
    return nullptr;
3443
1.14M
  if (DebugTypeExtRefs && 
D->isFromASTFile()530k
) {
3444
    // Record a reference to an imported clang module or precompiled header.
3445
20.7k
    auto *Reader = CGM.getContext().getExternalSource();
3446
20.7k
    auto Idx = D->getOwningModuleID();
3447
20.7k
    auto Info = Reader->getSourceDescriptor(Idx);
3448
20.7k
    if (Info)
3449
20.7k
      return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3450
1.12M
  } else if (ClangModuleMap) {
3451
    // We are building a clang module or a precompiled header.
3452
    //
3453
    // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3454
    // and it wouldn't be necessary to specify the parent scope
3455
    // because the type is already unique by definition (it would look
3456
    // like the output of -fno-standalone-debug). On the other hand,
3457
    // the parent scope helps a consumer to quickly locate the object
3458
    // file where the type's definition is located, so it might be
3459
    // best to make this behavior a command line or debugger tuning
3460
    // option.
3461
471k
    if (Module *M = D->getOwningModule()) {
3462
      // This is a (sub-)module.
3463
470k
      auto Info = ASTSourceDescriptor(*M);
3464
470k
      return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
3465
470k
    } else {
3466
      // This the precompiled header being built.
3467
343
      return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
3468
343
    }
3469
471k
  }
3470
3471
653k
  return nullptr;
3472
1.14M
}
3473
3474
llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit,
3475
1.23M
                                          TypeLoc TL) {
3476
  // Handle qualifiers, which recursively handles what they refer to.
3477
1.23M
  if (Ty.hasLocalQualifiers())
3478
71.6k
    return CreateQualifiedType(Ty, Unit, TL);
3479
3480
  // Work out details of type.
3481
1.16M
  switch (Ty->getTypeClass()) {
3482
0
#define TYPE(Class, Base)
3483
0
#define ABSTRACT_TYPE(Class, Base)
3484
0
#define NON_CANONICAL_TYPE(Class, Base)
3485
0
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3486
0
#include "clang/AST/TypeNodes.inc"
3487
0
    llvm_unreachable("Dependent types cannot show up in debug information");
3488
3489
43
  case Type::ExtVector:
3490
1.40k
  case Type::Vector:
3491
1.40k
    return CreateType(cast<VectorType>(Ty), Unit);
3492
1
  case Type::ConstantMatrix:
3493
1
    return CreateType(cast<ConstantMatrixType>(Ty), Unit);
3494
8.19k
  case Type::ObjCObjectPointer:
3495
8.19k
    return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3496
4.67k
  case Type::ObjCObject:
3497
4.67k
    return CreateType(cast<ObjCObjectType>(Ty), Unit);
3498
667
  case Type::ObjCTypeParam:
3499
667
    return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
3500
4.08k
  case Type::ObjCInterface:
3501
4.08k
    return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3502
177k
  case Type::Builtin:
3503
177k
    return CreateType(cast<BuiltinType>(Ty));
3504
96
  case Type::Complex:
3505
96
    return CreateType(cast<ComplexType>(Ty));
3506
125k
  case Type::Pointer:
3507
125k
    return CreateType(cast<PointerType>(Ty), Unit, TL);
3508
824
  case Type::BlockPointer:
3509
824
    return CreateType(cast<BlockPointerType>(Ty), Unit);
3510
185k
  case Type::Typedef:
3511
185k
    return CreateType(cast<TypedefType>(Ty), Unit);
3512
130k
  case Type::Record:
3513
130k
    return CreateType(cast<RecordType>(Ty));
3514
14.2k
  case Type::Enum:
3515
14.2k
    return CreateEnumType(cast<EnumType>(Ty));
3516
387k
  case Type::FunctionProto:
3517
387k
  case Type::FunctionNoProto:
3518
387k
    return CreateType(cast<FunctionType>(Ty), Unit, TL);
3519
11.2k
  case Type::ConstantArray:
3520
11.2k
  case Type::VariableArray:
3521
11.3k
  case Type::IncompleteArray:
3522
11.3k
    return CreateType(cast<ArrayType>(Ty), Unit);
3523
3524
85.5k
  case Type::LValueReference:
3525
85.5k
    return CreateType(cast<LValueReferenceType>(Ty), Unit);
3526
18.5k
  case Type::RValueReference:
3527
18.5k
    return CreateType(cast<RValueReferenceType>(Ty), Unit);
3528
3529
53
  case Type::MemberPointer:
3530
53
    return CreateType(cast<MemberPointerType>(Ty), Unit);
3531
3532
977
  case Type::Atomic:
3533
977
    return CreateType(cast<AtomicType>(Ty), Unit);
3534
3535
0
  case Type::BitInt:
3536
0
    return CreateType(cast<BitIntType>(Ty));
3537
0
  case Type::Pipe:
3538
0
    return CreateType(cast<PipeType>(Ty), Unit);
3539
3540
7.08k
  case Type::TemplateSpecialization:
3541
7.08k
    return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3542
3543
0
  case Type::Auto:
3544
0
  case Type::Attributed:
3545
0
  case Type::Adjusted:
3546
0
  case Type::Decayed:
3547
0
  case Type::DeducedTemplateSpecialization:
3548
0
  case Type::Elaborated:
3549
0
  case Type::Using:
3550
0
  case Type::Paren:
3551
0
  case Type::MacroQualified:
3552
0
  case Type::SubstTemplateTypeParm:
3553
0
  case Type::TypeOfExpr:
3554
0
  case Type::TypeOf:
3555
0
  case Type::Decltype:
3556
0
  case Type::UnaryTransform:
3557
0
    break;
3558
1.16M
  }
3559
3560
0
  llvm_unreachable("type should have been unwrapped!");
3561
0
}
3562
3563
llvm::DICompositeType *
3564
131k
CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) {
3565
131k
  QualType QTy(Ty, 0);
3566
3567
131k
  auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
3568
3569
  // We may have cached a forward decl when we could have created
3570
  // a non-forward decl. Go ahead and create a non-forward decl
3571
  // now.
3572
131k
  if (T && 
!T->isForwardDecl()2.42k
)
3573
0
    return T;
3574
3575
  // Otherwise create the type.
3576
131k
  llvm::DICompositeType *Res = CreateLimitedType(Ty);
3577
3578
  // Propagate members from the declaration to the definition
3579
  // CreateType(const RecordType*) will overwrite this with the members in the
3580
  // correct order if the full type is needed.
3581
131k
  DBuilder.replaceArrays(Res, T ? 
T->getElements()2.42k
:
llvm::DINodeArray()128k
);
3582
3583
  // And update the type cache.
3584
131k
  TypeCache[QTy.getAsOpaquePtr()].reset(Res);
3585
131k
  return Res;
3586
131k
}
3587
3588
// TODO: Currently used for context chains when limiting debug info.
3589
131k
llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
3590
131k
  RecordDecl *RD = Ty->getDecl();
3591
3592
  // Get overall information about the record type for the debug info.
3593
131k
  StringRef RDName = getClassName(RD);
3594
131k
  const SourceLocation Loc = RD->getLocation();
3595
131k
  llvm::DIFile *DefUnit = nullptr;
3596
131k
  unsigned Line = 0;
3597
131k
  if (Loc.isValid()) {
3598
130k
    DefUnit = getOrCreateFile(Loc);
3599
130k
    Line = getLineNumber(Loc);
3600
130k
  }
3601
3602
131k
  llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
3603
3604
  // If we ended up creating the type during the context chain construction,
3605
  // just return that.
3606
131k
  auto *T = cast_or_null<llvm::DICompositeType>(
3607
131k
      getTypeOrNull(CGM.getContext().getRecordType(RD)));
3608
131k
  if (T && 
(2.45k
!T->isForwardDecl()2.45k
||
!RD->getDefinition()2.43k
))
3609
28
    return T;
3610
3611
  // If this is just a forward or incomplete declaration, construct an
3612
  // appropriately marked node and just return it.
3613
131k
  const RecordDecl *D = RD->getDefinition();
3614
131k
  if (!D || 
!D->isCompleteDefinition()118k
)
3615
12.8k
    return getOrCreateRecordFwdDecl(Ty, RDContext);
3616
3617
118k
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
3618
118k
  auto Align = getDeclAlignIfRequired(D, CGM.getContext());
3619
3620
118k
  SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3621
3622
  // Explicitly record the calling convention and export symbols for C++
3623
  // records.
3624
118k
  auto Flags = llvm::DINode::FlagZero;
3625
118k
  if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3626
102k
    if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3627
10.3k
      Flags |= llvm::DINode::FlagTypePassByReference;
3628
91.7k
    else
3629
91.7k
      Flags |= llvm::DINode::FlagTypePassByValue;
3630
3631
    // Record if a C++ record is non-trivial type.
3632
102k
    if (!CXXRD->isTrivial())
3633
22.1k
      Flags |= llvm::DINode::FlagNonTrivial;
3634
3635
    // Record exports it symbols to the containing structure.
3636
102k
    if (CXXRD->isAnonymousStructOrUnion())
3637
634
        Flags |= llvm::DINode::FlagExportSymbols;
3638
3639
102k
    Flags |= getAccessFlag(CXXRD->getAccess(),
3640
102k
                           dyn_cast<CXXRecordDecl>(CXXRD->getDeclContext()));
3641
102k
  }
3642
3643
118k
  llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
3644
118k
  llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
3645
118k
      getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
3646
118k
      Flags, Identifier, Annotations);
3647
3648
  // Elements of composite types usually have back to the type, creating
3649
  // uniquing cycles.  Distinct nodes are more efficient.
3650
118k
  switch (RealDecl->getTag()) {
3651
0
  default:
3652
0
    llvm_unreachable("invalid composite type tag");
3653
3654
0
  case llvm::dwarf::DW_TAG_array_type:
3655
0
  case llvm::dwarf::DW_TAG_enumeration_type:
3656
    // Array elements and most enumeration elements don't have back references,
3657
    // so they don't tend to be involved in uniquing cycles and there is some
3658
    // chance of merging them when linking together two modules.  Only make
3659
    // them distinct if they are ODR-uniqued.
3660
0
    if (Identifier.empty())
3661
0
      break;
3662
0
    LLVM_FALLTHROUGH;
3663
3664
97.0k
  case llvm::dwarf::DW_TAG_structure_type:
3665
100k
  case llvm::dwarf::DW_TAG_union_type:
3666
118k
  case llvm::dwarf::DW_TAG_class_type:
3667
    // Immediately resolve to a distinct node.
3668
118k
    RealDecl =
3669
118k
        llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3670
118k
    break;
3671
118k
  }
3672
3673
118k
  RegionMap[Ty->getDecl()].reset(RealDecl);
3674
118k
  TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
3675
3676
118k
  if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3677
58.0k
    DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
3678
58.0k
                           CollectCXXTemplateParams(TSpecial, DefUnit));
3679
118k
  return RealDecl;
3680
118k
}
3681
3682
void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
3683
102k
                                        llvm::DICompositeType *RealDecl) {
3684
  // A class's primary base or the class itself contains the vtable.
3685
102k
  llvm::DICompositeType *ContainingType = nullptr;
3686
102k
  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3687
102k
  if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
3688
    // Seek non-virtual primary base root.
3689
2.69k
    while (true) {
3690
2.69k
      const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3691
2.69k
      const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3692
2.69k
      if (PBT && 
!BRL.isPrimaryBaseVirtual()1.23k
)
3693
1.23k
        PBase = PBT;
3694
1.46k
      else
3695
1.46k
        break;
3696
2.69k
    }
3697
1.46k
    ContainingType = cast<llvm::DICompositeType>(
3698
1.46k
        getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3699
1.46k
                        getOrCreateFile(RD->getLocation())));
3700
100k
  } else if (RD->isDynamicClass())
3701
674
    ContainingType = RealDecl;
3702
3703
102k
  DBuilder.replaceVTableHolder(RealDecl, ContainingType);
3704
102k
}
3705
3706
llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
3707
5.11k
                                            StringRef Name, uint64_t *Offset) {
3708
5.11k
  llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
3709
5.11k
  uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
3710
5.11k
  auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3711
5.11k
  llvm::DIType *Ty =
3712
5.11k
      DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3713
5.11k
                                *Offset, llvm::DINode::FlagZero, FieldTy);
3714
5.11k
  *Offset += FieldSize;
3715
5.11k
  return Ty;
3716
5.11k
}
3717
3718
void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
3719
                                           StringRef &Name,
3720
                                           StringRef &LinkageName,
3721
                                           llvm::DIScope *&FDContext,
3722
                                           llvm::DINodeArray &TParamsArray,
3723
350k
                                           llvm::DINode::DIFlags &Flags) {
3724
350k
  const auto *FD = cast<FunctionDecl>(GD.getCanonicalDecl().getDecl());
3725
350k
  Name = getFunctionName(FD);
3726
  // Use mangled name as linkage name for C/C++ functions.
3727
350k
  if (FD->getType()->getAs<FunctionProtoType>())
3728
349k
    LinkageName = CGM.getMangledName(GD);
3729
350k
  if (FD->hasPrototype())
3730
349k
    Flags |= llvm::DINode::FlagPrototyped;
3731
  // No need to replicate the linkage name if it isn't different from the
3732
  // subprogram name, no need to have it at all unless coverage is enabled or
3733
  // debug is set to more than just line tables or extra debug info is needed.
3734
350k
  if (LinkageName == Name || 
(136k
!CGM.getCodeGenOpts().EmitGcovArcs136k
&&
3735
136k
                              
!CGM.getCodeGenOpts().EmitGcovNotes136k
&&
3736
136k
                              
!CGM.getCodeGenOpts().DebugInfoForProfiling136k
&&
3737
136k
                              
!CGM.getCodeGenOpts().PseudoProbeForProfiling136k
&&
3738
136k
                              
DebugKind <= codegenoptions::DebugLineTablesOnly136k
))
3739
214k
    LinkageName = StringRef();
3740
3741
  // Emit the function scope in line tables only mode (if CodeView) to
3742
  // differentiate between function names.
3743
350k
  if (CGM.getCodeGenOpts().hasReducedDebugInfo() ||
3744
350k
      
(791
DebugKind == codegenoptions::DebugLineTablesOnly791
&&
3745
350k
       
CGM.getCodeGenOpts().EmitCodeView524
)) {
3746
350k
    if (const NamespaceDecl *NSDecl =
3747
350k
            dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
3748
21.8k
      FDContext = getOrCreateNamespace(NSDecl);
3749
328k
    else if (const RecordDecl *RDecl =
3750
328k
                 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
3751
70.0k
      llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3752
70.0k
      FDContext = getContextDescriptor(RDecl, Mod ? 
Mod2.73k
:
TheCU67.3k
);
3753
70.0k
    }
3754
350k
  }
3755
350k
  if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
3756
    // Check if it is a noreturn-marked function
3757
350k
    if (FD->isNoReturn())
3758
2.77k
      Flags |= llvm::DINode::FlagNoReturn;
3759
    // Collect template parameters.
3760
350k
    TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3761
350k
  }
3762
350k
}
3763
3764
void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
3765
                                      unsigned &LineNo, QualType &T,
3766
                                      StringRef &Name, StringRef &LinkageName,
3767
                                      llvm::MDTuple *&TemplateParameters,
3768
4.85k
                                      llvm::DIScope *&VDContext) {
3769
4.85k
  Unit = getOrCreateFile(VD->getLocation());
3770
4.85k
  LineNo = getLineNumber(VD->getLocation());
3771
3772
4.85k
  setLocation(VD->getLocation());
3773
3774
4.85k
  T = VD->getType();
3775
4.85k
  if (T->isIncompleteArrayType()) {
3776
    // CodeGen turns int[] into int[1] so we'll do the same here.
3777
0
    llvm::APInt ConstVal(32, 1);
3778
0
    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3779
3780
0
    T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
3781
0
                                              ArrayType::Normal, 0);
3782
0
  }
3783
3784
4.85k
  Name = VD->getName();
3785
4.85k
  if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3786
4.85k
      
!isa<ObjCMethodDecl>(VD->getDeclContext())4.67k
)
3787
4.67k
    LinkageName = CGM.getMangledName(VD);
3788
4.85k
  if (LinkageName == Name)
3789
3.37k
    LinkageName = StringRef();
3790
3791
4.85k
  if (isa<VarTemplateSpecializationDecl>(VD)) {
3792
16
    llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
3793
16
    TemplateParameters = parameterNodes.get();
3794
4.84k
  } else {
3795
4.84k
    TemplateParameters = nullptr;
3796
4.84k
  }
3797
3798
  // Since we emit declarations (DW_AT_members) for static members, place the
3799
  // definition of those static members in the namespace they were declared in
3800
  // in the source code (the lexical decl context).
3801
  // FIXME: Generalize this for even non-member global variables where the
3802
  // declaration and definition may have different lexical decl contexts, once
3803
  // we have support for emitting declarations of (non-member) global variables.
3804
4.85k
  const DeclContext *DC = VD->isStaticDataMember() ? 
VD->getLexicalDeclContext()100
3805
4.85k
                                                   : 
VD->getDeclContext()4.75k
;
3806
  // When a record type contains an in-line initialization of a static data
3807
  // member, and the record type is marked as __declspec(dllexport), an implicit
3808
  // definition of the member will be created in the record context.  DWARF
3809
  // doesn't seem to have a nice way to describe this in a form that consumers
3810
  // are likely to understand, so fake the "normal" situation of a definition
3811
  // outside the class by putting it in the global scope.
3812
4.85k
  if (DC->isRecord())
3813
1
    DC = CGM.getContext().getTranslationUnitDecl();
3814
3815
4.85k
  llvm::DIScope *Mod = getParentModuleOrNull(VD);
3816
4.85k
  VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? 
Mod28
:
TheCU4.82k
);
3817
4.85k
}
3818
3819
llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3820
133k
                                                          bool Stub) {
3821
133k
  llvm::DINodeArray TParamsArray;
3822
133k
  StringRef Name, LinkageName;
3823
133k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3824
133k
  llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3825
133k
  SourceLocation Loc = GD.getDecl()->getLocation();
3826
133k
  llvm::DIFile *Unit = getOrCreateFile(Loc);
3827
133k
  llvm::DIScope *DContext = Unit;
3828
133k
  unsigned Line = getLineNumber(Loc);
3829
133k
  collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3830
133k
                           Flags);
3831
133k
  auto *FD = cast<FunctionDecl>(GD.getDecl());
3832
3833
  // Build function type.
3834
133k
  SmallVector<QualType, 16> ArgTypes;
3835
133k
  for (const ParmVarDecl *Parm : FD->parameters())
3836
225k
    ArgTypes.push_back(Parm->getType());
3837
3838
133k
  CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3839
133k
  QualType FnType = CGM.getContext().getFunctionType(
3840
133k
      FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
3841
133k
  if (!FD->isExternallyVisible())
3842
0
    SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3843
133k
  if (CGM.getLangOpts().Optimize)
3844
0
    SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3845
3846
133k
  if (Stub) {
3847
3
    Flags |= getCallSiteRelatedAttrs();
3848
3
    SPFlags |= llvm::DISubprogram::SPFlagDefinition;
3849
3
    return DBuilder.createFunction(
3850
3
        DContext, Name, LinkageName, Unit, Line,
3851
3
        getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3852
3
        TParamsArray.get(), getFunctionDeclaration(FD));
3853
3
  }
3854
3855
133k
  llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
3856
133k
      DContext, Name, LinkageName, Unit, Line,
3857
133k
      getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3858
133k
      TParamsArray.get(), getFunctionDeclaration(FD));
3859
133k
  const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
3860
133k
  FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3861
133k
                                 std::make_tuple(CanonDecl),
3862
133k
                                 std::make_tuple(SP));
3863
133k
  return SP;
3864
133k
}
3865
3866
133k
llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
3867
133k
  return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3868
133k
}
3869
3870
3
llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
3871
3
  return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3872
3
}
3873
3874
llvm::DIGlobalVariable *
3875
4
CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3876
4
  QualType T;
3877
4
  StringRef Name, LinkageName;
3878
4
  SourceLocation Loc = VD->getLocation();
3879
4
  llvm::DIFile *Unit = getOrCreateFile(Loc);
3880
4
  llvm::DIScope *DContext = Unit;
3881
4
  unsigned Line = getLineNumber(Loc);
3882
4
  llvm::MDTuple *TemplateParameters = nullptr;
3883
3884
4
  collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
3885
4
                      DContext);
3886
4
  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3887
4
  auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3888
4
      DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
3889
4
      !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
3890
4
  FwdDeclReplaceMap.emplace_back(
3891
4
      std::piecewise_construct,
3892
4
      std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3893
4
      std::make_tuple(static_cast<llvm::Metadata *>(GV)));
3894
4
  return GV;
3895
4
}
3896
3897
188k
llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
3898
  // We only need a declaration (not a definition) of the type - so use whatever
3899
  // we would otherwise do to get a type for a pointee. (forward declarations in
3900
  // limited debug info, full definitions (if the type definition is available)
3901
  // in unlimited debug info)
3902
188k
  if (const auto *TD = dyn_cast<TypeDecl>(D))
3903
26.1k
    return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
3904
26.1k
                           getOrCreateFile(TD->getLocation()));
3905
162k
  auto I = DeclCache.find(D->getCanonicalDecl());
3906
3907
162k
  if (I != DeclCache.end()) {
3908
118
    auto N = I->second;
3909
118
    if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3910
79
      return GVE->getVariable();
3911
39
    return dyn_cast_or_null<llvm::DINode>(N);
3912
118
  }
3913
3914
  // No definition for now. Emit a forward definition that might be
3915
  // merged with a potential upcoming definition.
3916
162k
  if (const auto *FD = dyn_cast<FunctionDecl>(D))
3917
133k
    return getFunctionForwardDeclaration(FD);
3918
28.8k
  else if (const auto *VD = dyn_cast<VarDecl>(D))
3919
4
    return getGlobalVariableForwardDeclaration(VD);
3920
3921
28.8k
  return nullptr;
3922
162k
}
3923
3924
364k
llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
3925
364k
  if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3926
978
    return nullptr;
3927
3928
363k
  const auto *FD = dyn_cast<FunctionDecl>(D);
3929
363k
  if (!FD)
3930
13.1k
    return nullptr;
3931
3932
  // Setup context.
3933
350k
  auto *S = getDeclContextDescriptor(D);
3934
3935
350k
  auto MI = SPCache.find(FD->getCanonicalDecl());
3936
350k
  if (MI == SPCache.end()) {
3937
292k
    if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
3938
12.6k
      return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
3939
12.6k
                                     cast<llvm::DICompositeType>(S));
3940
12.6k
    }
3941
292k
  }
3942
337k
  if (MI != SPCache.end()) {
3943
57.4k
    auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3944
57.4k
    if (SP && !SP->isDefinition())
3945
57.4k
      return SP;
3946
57.4k
  }
3947
3948
285k
  
for (auto NextFD : FD->redecls())280k
{
3949
285k
    auto MI = SPCache.find(NextFD->getCanonicalDecl());
3950
285k
    if (MI != SPCache.end()) {
3951
0
      auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3952
0
      if (SP && !SP->isDefinition())
3953
0
        return SP;
3954
0
    }
3955
285k
  }
3956
280k
  return nullptr;
3957
280k
}
3958
3959
llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
3960
    const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
3961
1.32k
    llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
3962
1.32k
  if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3963
4
    return nullptr;
3964
3965
1.32k
  const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
3966
1.32k
  if (!OMD)
3967
0
    return nullptr;
3968
3969
1.32k
  if (CGM.getCodeGenOpts().DwarfVersion < 5 && 
!OMD->isDirectMethod()1.31k
)
3970
1.29k
    return nullptr;
3971
3972
31
  if (OMD->isDirectMethod())
3973
23
    SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
3974
3975
  // Starting with DWARF V5 method declarations are emitted as children of
3976
  // the interface type.
3977
31
  auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
3978
31
  if (!ID)
3979
31
    ID = OMD->getClassInterface();
3980
31
  if (!ID)
3981
0
    return nullptr;
3982
31
  QualType QTy(ID->getTypeForDecl(), 0);
3983
31
  auto It = TypeCache.find(QTy.getAsOpaquePtr());
3984
31
  if (It == TypeCache.end())
3985
0
    return nullptr;
3986
31
  auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
3987
31
  llvm::DISubprogram *FD = DBuilder.createFunction(
3988
31
      InterfaceType, getObjCMethodName(OMD), StringRef(),
3989
31
      InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
3990
31
  DBuilder.finalizeSubprogram(FD);
3991
31
  ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
3992
31
  return FD;
3993
31
}
3994
3995
// getOrCreateFunctionType - Construct type. If it is a c++ method, include
3996
// implicit parameter "this".
3997
llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
3998
                                                             QualType FnType,
3999
366k
                                                             llvm::DIFile *F) {
4000
  // In CodeView, we emit the function types in line tables only because the
4001
  // only way to distinguish between functions is by display name and type.
4002
366k
  if (!D || 
(365k
DebugKind <= codegenoptions::DebugLineTablesOnly365k
&&
4003
365k
             
!CGM.getCodeGenOpts().EmitCodeView982
))
4004
    // Create fake but valid subroutine type. Otherwise -verify would fail, and
4005
    // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
4006
1.68k
    return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
4007
4008
364k
  if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
4009
70.0k
    return getOrCreateMethodType(Method, F, false);
4010
4011
294k
  const auto *FTy = FnType->getAs<FunctionType>();
4012
294k
  CallingConv CC = FTy ? FTy->getCallConv() : 
CallingConv::CC_C0
;
4013
4014
294k
  if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
4015
    // Add "self" and "_cmd"
4016
13.4k
    SmallVector<llvm::Metadata *, 16> Elts;
4017
4018
    // First element is always return type. For 'void' functions it is NULL.
4019
13.4k
    QualType ResultTy = OMethod->getReturnType();
4020
4021
    // Replace the instancetype keyword with the actual type.
4022
13.4k
    if (ResultTy == CGM.getContext().getObjCInstanceType())
4023
25
      ResultTy = CGM.getContext().getPointerType(
4024
25
          QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
4025
4026
13.4k
    Elts.push_back(getOrCreateType(ResultTy, F));
4027
    // "self" pointer is always first argument.
4028
13.4k
    QualType SelfDeclTy;
4029
13.4k
    if (auto *SelfDecl = OMethod->getSelfDecl())
4030
13.4k
      SelfDeclTy = SelfDecl->getType();
4031
0
    else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4032
0
      if (FPT->getNumParams() > 1)
4033
0
        SelfDeclTy = FPT->getParamType(0);
4034
13.4k
    if (!SelfDeclTy.isNull())
4035
13.4k
      Elts.push_back(
4036
13.4k
          CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
4037
    // "_cmd" pointer is always second argument.
4038
13.4k
    Elts.push_back(DBuilder.createArtificialType(
4039
13.4k
        getOrCreateType(CGM.getContext().getObjCSelType(), F)));
4040
    // Get rest of the arguments.
4041
13.4k
    for (const auto *PI : OMethod->parameters())
4042
18.1k
      Elts.push_back(getOrCreateType(PI->getType(), F));
4043
    // Variadic methods need a special marker at the end of the type list.
4044
13.4k
    if (OMethod->isVariadic())
4045
74
      Elts.push_back(DBuilder.createUnspecifiedParameter());
4046
4047
13.4k
    llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
4048
13.4k
    return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4049
13.4k
                                         getDwarfCC(CC));
4050
13.4k
  }
4051
4052
  // Handle variadic function types; they need an additional
4053
  // unspecified parameter.
4054
281k
  if (const auto *FD = dyn_cast<FunctionDecl>(D))
4055
280k
    if (FD->isVariadic()) {
4056
6.91k
      SmallVector<llvm::Metadata *, 16> EltTys;
4057
6.91k
      EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
4058
6.91k
      if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4059
6.91k
        for (QualType ParamType : FPT->param_types())
4060
13.3k
          EltTys.push_back(getOrCreateType(ParamType, F));
4061
6.91k
      EltTys.push_back(DBuilder.createUnspecifiedParameter());
4062
6.91k
      llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
4063
6.91k
      return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4064
6.91k
                                           getDwarfCC(CC));
4065
6.91k
    }
4066
4067
274k
  TypeLoc TL;
4068
274k
  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4069
273k
    if (const TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4070
273k
      TL = TSI->getTypeLoc();
4071
273k
  }
4072
274k
  return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F, TL));
4073
281k
}
4074
4075
QualType
4076
CGDebugInfo::getFunctionType(const FunctionDecl *FD, QualType RetTy,
4077
236k
                             const SmallVectorImpl<const VarDecl *> &Args) {
4078
236k
  CallingConv CC = CallingConv::CC_C;
4079
236k
  if (FD)
4080
233k
    if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
4081
233k
      CC = SrcFnTy->getCallConv();
4082
236k
  SmallVector<QualType, 16> ArgTypes;
4083
236k
  for (const VarDecl *VD : Args)
4084
337k
    ArgTypes.push_back(VD->getType());
4085
236k
  return CGM.getContext().getFunctionType(RetTy, ArgTypes,
4086
236k
                                          FunctionProtoType::ExtProtoInfo(CC));
4087
236k
}
4088
4089
void CGDebugInfo::emitFunctionStart(GlobalDecl GD, SourceLocation Loc,
4090
                                    SourceLocation ScopeLoc, QualType FnType,
4091
103k
                                    llvm::Function *Fn, bool CurFuncIsThunk) {
4092
103k
  StringRef Name;
4093
103k
  StringRef LinkageName;
4094
4095
103k
  FnBeginRegionCount.push_back(LexicalBlockStack.size());
4096
4097
103k
  const Decl *D = GD.getDecl();
4098
103k
  bool HasDecl = (D != nullptr);
4099
4100
103k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4101
103k
  llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4102
103k
  llvm::DIFile *Unit = getOrCreateFile(Loc);
4103
103k
  llvm::DIScope *FDContext = Unit;
4104
103k
  llvm::DINodeArray TParamsArray;
4105
103k
  if (!HasDecl) {
4106
    // Use llvm function name.
4107
730
    LinkageName = Fn->getName();
4108
102k
  } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4109
    // If there is a subprogram for this function available then use it.
4110
100k
    auto FI = SPCache.find(FD->getCanonicalDecl());
4111
100k
    if (FI != SPCache.end()) {
4112
55.4k
      auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4113
55.4k
      if (SP && SP->isDefinition()) {
4114
0
        LexicalBlockStack.emplace_back(SP);
4115
0
        RegionMap[D].reset(SP);
4116
0
        return;
4117
0
      }
4118
55.4k
    }
4119
100k
    collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4120
100k
                             TParamsArray, Flags);
4121
100k
  } else 
if (const auto *2.54k
OMD2.54k
= dyn_cast<ObjCMethodDecl>(D)) {
4122
1.32k
    Name = getObjCMethodName(OMD);
4123
1.32k
    Flags |= llvm::DINode::FlagPrototyped;
4124
1.32k
  } else 
if (1.21k
isa<VarDecl>(D)1.21k
&&
4125
1.21k
             
GD.getDynamicInitKind() != DynamicInitKind::NoStub527
) {
4126
    // This is a global initializer or atexit destructor for a global variable.
4127
527
    Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
4128
527
                                     Fn);
4129
689
  } else {
4130
689
    Name = Fn->getName();
4131
4132
689
    if (isa<BlockDecl>(D))
4133
173
      LinkageName = Name;
4134
4135
689
    Flags |= llvm::DINode::FlagPrototyped;
4136
689
  }
4137
103k
  if (Name.startswith("\01"))
4138
0
    Name = Name.substr(1);
4139
4140
103k
  if (!HasDecl || 
D->isImplicit()102k
||
D->hasAttr<ArtificialAttr>()99.6k
||
4141
103k
      
(99.6k
isa<VarDecl>(D)99.6k
&&
GD.getDynamicInitKind() != DynamicInitKind::NoStub526
)) {
4142
4.55k
    Flags |= llvm::DINode::FlagArtificial;
4143
    // Artificial functions should not silently reuse CurLoc.
4144
4.55k
    CurLoc = SourceLocation();
4145
4.55k
  }
4146
4147
103k
  if (CurFuncIsThunk)
4148
102
    Flags |= llvm::DINode::FlagThunk;
4149
4150
103k
  if (Fn->hasLocalLinkage())
4151
7.08k
    SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4152
103k
  if (CGM.getLangOpts().Optimize)
4153
748
    SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4154
4155
103k
  llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
4156
103k
  llvm::DISubprogram::DISPFlags SPFlagsForDef =
4157
103k
      SPFlags | llvm::DISubprogram::SPFlagDefinition;
4158
4159
103k
  const unsigned LineNo = getLineNumber(Loc.isValid() ? 
Loc102k
:
CurLoc1.01k
);
4160
103k
  unsigned ScopeLine = getLineNumber(ScopeLoc);
4161
103k
  llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
4162
103k
  llvm::DISubprogram *Decl = nullptr;
4163
103k
  llvm::DINodeArray Annotations = nullptr;
4164
103k
  if (D) {
4165
102k
    Decl = isa<ObjCMethodDecl>(D)
4166
102k
               ? 
getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)1.32k
4167
102k
               : 
getFunctionDeclaration(D)101k
;
4168
102k
    Annotations = CollectBTFDeclTagAnnotations(D);
4169
102k
  }
4170
4171
  // FIXME: The function declaration we're constructing here is mostly reusing
4172
  // declarations from CXXMethodDecl and not constructing new ones for arbitrary
4173
  // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
4174
  // all subprograms instead of the actual context since subprogram definitions
4175
  // are emitted as CU level entities by the backend.
4176
103k
  llvm::DISubprogram *SP = DBuilder.createFunction(
4177
103k
      FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
4178
103k
      FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl, nullptr,
4179
103k
      Annotations);
4180
103k
  Fn->setSubprogram(SP);
4181
  // We might get here with a VarDecl in the case we're generating
4182
  // code for the initialization of globals. Do not record these decls
4183
  // as they will overwrite the actual VarDecl Decl in the cache.
4184
103k
  if (HasDecl && 
isa<FunctionDecl>(D)102k
)
4185
100k
    DeclCache[D->getCanonicalDecl()].reset(SP);
4186
4187
  // Push the function onto the lexical block stack.
4188
103k
  LexicalBlockStack.emplace_back(SP);
4189
4190
103k
  if (HasDecl)
4191
102k
    RegionMap[D].reset(SP);
4192
103k
}
4193
4194
void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
4195
128k
                                   QualType FnType, llvm::Function *Fn) {
4196
128k
  StringRef Name;
4197
128k
  StringRef LinkageName;
4198
4199
128k
  const Decl *D = GD.getDecl();
4200
128k
  if (!D)
4201
0
    return;
4202
4203
128k
  llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
4204
0
    return GetName(D, true);
4205
0
  });
4206
4207
128k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4208
128k
  llvm::DIFile *Unit = getOrCreateFile(Loc);
4209
128k
  bool IsDeclForCallSite = Fn ? 
true72
:
false128k
;
4210
128k
  llvm::DIScope *FDContext =
4211
128k
      IsDeclForCallSite ? 
Unit72
:
getDeclContextDescriptor(D)128k
;
4212
128k
  llvm::DINodeArray TParamsArray;
4213
128k
  if (isa<FunctionDecl>(D)) {
4214
    // If there is a DISubprogram for this function available then use it.
4215
116k
    collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4216
116k
                             TParamsArray, Flags);
4217
116k
  } else 
if (const auto *12.1k
OMD12.1k
= dyn_cast<ObjCMethodDecl>(D)) {
4218
12.1k
    Name = getObjCMethodName(OMD);
4219
12.1k
    Flags |= llvm::DINode::FlagPrototyped;
4220
12.1k
  } else {
4221
0
    llvm_unreachable("not a function or ObjC method");
4222
0
  }
4223
128k
  if (!Name.empty() && Name[0] == '\01')
4224
0
    Name = Name.substr(1);
4225
4226
128k
  if (D->isImplicit()) {
4227
0
    Flags |= llvm::DINode::FlagArtificial;
4228
    // Artificial functions without a location should not silently reuse CurLoc.
4229
0
    if (Loc.isInvalid())
4230
0
      CurLoc = SourceLocation();
4231
0
  }
4232
128k
  unsigned LineNo = getLineNumber(Loc);
4233
128k
  unsigned ScopeLine = 0;
4234
128k
  llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4235
128k
  if (CGM.getLangOpts().Optimize)
4236
24.9k
    SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4237
4238
128k
  llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
4239
128k
  llvm::DISubprogram *SP = DBuilder.createFunction(
4240
128k
      FDContext, Name, LinkageName, Unit, LineNo,
4241
128k
      getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
4242
128k
      TParamsArray.get(), getFunctionDeclaration(D), nullptr, Annotations);
4243
4244
128k
  if (IsDeclForCallSite)
4245
72
    Fn->setSubprogram(SP);
4246
4247
128k
  DBuilder.finalizeSubprogram(SP);
4248
128k
}
4249
4250
void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
4251
                                          QualType CalleeType,
4252
132k
                                          const FunctionDecl *CalleeDecl) {
4253
132k
  if (!CallOrInvoke)
4254
0
    return;
4255
132k
  auto *Func = CallOrInvoke->getCalledFunction();
4256
132k
  if (!Func)
4257
22
    return;
4258
132k
  if (Func->getSubprogram())
4259
16.4k
    return;
4260
4261
  // Do not emit a declaration subprogram for a builtin, a function with nodebug
4262
  // attribute, or if call site info isn't required. Also, elide declarations
4263
  // for functions with reserved names, as call site-related features aren't
4264
  // interesting in this case (& also, the compiler may emit calls to these
4265
  // functions without debug locations, which makes the verifier complain).
4266
116k
  if (CalleeDecl->getBuiltinID() != 0 || 
CalleeDecl->hasAttr<NoDebugAttr>()115k
||
4267
116k
      
getCallSiteRelatedAttrs() == llvm::DINode::FlagZero115k
)
4268
116k
    return;
4269
93
  if (CalleeDecl->isReserved(CGM.getLangOpts()) !=
4270
93
      ReservedIdentifierStatus::NotReserved)
4271
2
    return;
4272
4273
  // If there is no DISubprogram attached to the function being called,
4274
  // create the one describing the function in order to have complete
4275
  // call site debug info.
4276
91
  if (!CalleeDecl->isStatic() && 
!CalleeDecl->isInlined()70
)
4277
70
    EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
4278
91
}
4279
4280
3
void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
4281
3
  const auto *FD = cast<FunctionDecl>(GD.getDecl());
4282
  // If there is a subprogram for this function available then use it.
4283
3
  auto FI = SPCache.find(FD->getCanonicalDecl());
4284
3
  llvm::DISubprogram *SP = nullptr;
4285
3
  if (FI != SPCache.end())
4286
1
    SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4287
3
  if (!SP || 
!SP->isDefinition()1
)
4288
3
    SP = getFunctionStub(GD);
4289
3
  FnBeginRegionCount.push_back(LexicalBlockStack.size());
4290
3
  LexicalBlockStack.emplace_back(SP);
4291
3
  setInlinedAt(Builder.getCurrentDebugLocation());
4292
3
  EmitLocation(Builder, FD->getLocation());
4293
3
}
4294
4295
3
void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
4296
3
  assert(CurInlinedAt && "unbalanced inline scope stack");
4297
0
  EmitFunctionEnd(Builder, nullptr);
4298
3
  setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
4299
3
}
4300
4301
4.75M
void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
4302
  // Update our current location
4303
4.75M
  setLocation(Loc);
4304
4305
4.75M
  if (CurLoc.isInvalid() || 
CurLoc.isMacroID()4.74M
||
LexicalBlockStack.empty()4.74M
)
4306
2.72k
    return;
4307
4308
4.74M
  llvm::MDNode *Scope = LexicalBlockStack.back();
4309
4.74M
  Builder.SetCurrentDebugLocation(
4310
4.74M
      llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(CurLoc),
4311
4.74M
                            getColumnNumber(CurLoc), Scope, CurInlinedAt));
4312
4.74M
}
4313
4314
206k
void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
4315
206k
  llvm::MDNode *Back = nullptr;
4316
206k
  if (!LexicalBlockStack.empty())
4317
206k
    Back = LexicalBlockStack.back().get();
4318
206k
  LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
4319
206k
      cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
4320
206k
      getColumnNumber(CurLoc)));
4321
206k
}
4322
4323
void CGDebugInfo::AppendAddressSpaceXDeref(
4324
282k
    unsigned AddressSpace, SmallVectorImpl<uint64_t> &Expr) const {
4325
282k
  Optional<unsigned> DWARFAddressSpace =
4326
282k
      CGM.getTarget().getDWARFAddressSpace(AddressSpace);
4327
282k
  if (!DWARFAddressSpace)
4328
282k
    return;
4329
4330
31
  Expr.push_back(llvm::dwarf::DW_OP_constu);
4331
31
  Expr.push_back(DWARFAddressSpace.getValue());
4332
31
  Expr.push_back(llvm::dwarf::DW_OP_swap);
4333
31
  Expr.push_back(llvm::dwarf::DW_OP_xderef);
4334
31
}
4335
4336
void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
4337
207k
                                        SourceLocation Loc) {
4338
  // Set our current location.
4339
207k
  setLocation(Loc);
4340
4341
  // Emit a line table change for the current location inside the new scope.
4342
207k
  Builder.SetCurrentDebugLocation(llvm::DILocation::get(
4343
207k
      CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc),
4344
207k
      LexicalBlockStack.back(), CurInlinedAt));
4345
4346
207k
  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
4347
957
    return;
4348
4349
  // Create a new lexical block and push it on the stack.
4350
206k
  CreateLexicalBlock(Loc);
4351
206k
}
4352
4353
void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
4354
207k
                                      SourceLocation Loc) {
4355
207k
  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4356
4357
  // Provide an entry in the line table for the end of the block.
4358
0
  EmitLocation(Builder, Loc);
4359
4360
207k
  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
4361
957
    return;
4362
4363
206k
  LexicalBlockStack.pop_back();
4364
206k
}
4365
4366
103k
void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
4367
103k
  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4368
0
  unsigned RCount = FnBeginRegionCount.back();
4369
103k
  assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
4370
4371
  // Pop all regions for this function.
4372
207k
  while (LexicalBlockStack.size() != RCount) {
4373
    // Provide an entry in the line table for the end of the block.
4374
103k
    EmitLocation(Builder, CurLoc);
4375
103k
    LexicalBlockStack.pop_back();
4376
103k
  }
4377
103k
  FnBeginRegionCount.pop_back();
4378
4379
103k
  if (Fn && 
Fn->getSubprogram()103k
)
4380
103k
    DBuilder.finalizeSubprogram(Fn->getSubprogram());
4381
103k
}
4382
4383
CGDebugInfo::BlockByRefType
4384
CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
4385
41
                                          uint64_t *XOffset) {
4386
41
  SmallVector<llvm::Metadata *, 5> EltTys;
4387
41
  QualType FType;
4388
41
  uint64_t FieldSize, FieldOffset;
4389
41
  uint32_t FieldAlign;
4390
4391
41
  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4392
41
  QualType Type = VD->getType();
4393
4394
41
  FieldOffset = 0;
4395
41
  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4396
41
  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
4397
41
  EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
4398
41
  FType = CGM.getContext().IntTy;
4399
41
  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
4400
41
  EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
4401
4402
41
  bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
4403
41
  if (HasCopyAndDispose) {
4404
3
    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4405
3
    EltTys.push_back(
4406
3
        CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
4407
3
    EltTys.push_back(
4408
3
        CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
4409
3
  }
4410
41
  bool HasByrefExtendedLayout;
4411
41
  Qualifiers::ObjCLifetime Lifetime;
4412
41
  if (CGM.getContext().getByrefLifetime(Type, Lifetime,
4413
41
                                        HasByrefExtendedLayout) &&
4414
41
      
HasByrefExtendedLayout12
) {
4415
6
    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4416
6
    EltTys.push_back(
4417
6
        CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
4418
6
  }
4419
4420
41
  CharUnits Align = CGM.getContext().getDeclAlign(VD);
4421
41
  if (Align > CGM.getContext().toCharUnitsFromBits(
4422
41
                  CGM.getTarget().getPointerAlign(0))) {
4423
0
    CharUnits FieldOffsetInBytes =
4424
0
        CGM.getContext().toCharUnitsFromBits(FieldOffset);
4425
0
    CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
4426
0
    CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
4427
4428
0
    if (NumPaddingBytes.isPositive()) {
4429
0
      llvm::APInt pad(32, NumPaddingBytes.getQuantity());
4430
0
      FType = CGM.getContext().getConstantArrayType(
4431
0
          CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0);
4432
0
      EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
4433
0
    }
4434
0
  }
4435
4436
41
  FType = Type;
4437
41
  llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
4438
41
  FieldSize = CGM.getContext().getTypeSize(FType);
4439
41
  FieldAlign = CGM.getContext().toBits(Align);
4440
4441
41
  *XOffset = FieldOffset;
4442
41
  llvm::DIType *FieldTy = DBuilder.createMemberType(
4443
41
      Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
4444
41
      llvm::DINode::FlagZero, WrappedTy);
4445
41
  EltTys.push_back(FieldTy);
4446
41
  FieldOffset += FieldSize;
4447
4448
41
  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4449
41
  return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
4450
41
                                    llvm::DINode::FlagZero, nullptr, Elements),
4451
41
          WrappedTy};
4452
41
}
4453
4454
llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
4455
                                                llvm::Value *Storage,
4456
                                                llvm::Optional<unsigned> ArgNo,
4457
                                                CGBuilderTy &Builder,
4458
277k
                                                const bool UsePointerValue) {
4459
277k
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4460
0
  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4461
277k
  if (VD->hasAttr<NoDebugAttr>())
4462
2
    return nullptr;
4463
4464
277k
  bool Unwritten =
4465
277k
      VD->isImplicit() || 
(207k
isa<Decl>(VD->getDeclContext())207k
&&
4466
207k
                           cast<Decl>(VD->getDeclContext())->isImplicit());
4467
277k
  llvm::DIFile *Unit = nullptr;
4468
277k
  if (!Unwritten)
4469
207k
    Unit = getOrCreateFile(VD->getLocation());
4470
277k
  llvm::DIType *Ty;
4471
277k
  uint64_t XOffset = 0;
4472
277k
  if (VD->hasAttr<BlocksAttr>())
4473
15
    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4474
277k
  else {
4475
277k
    TypeLoc TL;
4476
277k
    if (const TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4477
208k
      TL = TSI->getTypeLoc();
4478
277k
    Ty = getOrCreateType(VD->getType(), Unit, TL);
4479
277k
  }
4480
4481
  // If there is no debug info for this type then do not emit debug info
4482
  // for this variable.
4483
277k
  if (!Ty)
4484
0
    return nullptr;
4485
4486
  // Get location information.
4487
277k
  unsigned Line = 0;
4488
277k
  unsigned Column = 0;
4489
277k
  if (!Unwritten) {
4490
207k
    Line = getLineNumber(VD->getLocation());
4491
207k
    Column = getColumnNumber(VD->getLocation());
4492
207k
  }
4493
277k
  SmallVector<uint64_t, 13> Expr;
4494
277k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4495
277k
  if (VD->isImplicit())
4496
70.2k
    Flags |= llvm::DINode::FlagArtificial;
4497
4498
277k
  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4499
4500
277k
  unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
4501
277k
  AppendAddressSpaceXDeref(AddressSpace, Expr);
4502
4503
  // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4504
  // object pointer flag.
4505
277k
  if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4506
68.7k
    if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
4507
68.7k
        
IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf3.96k
)
4508
66.0k
      Flags |= llvm::DINode::FlagObjectPointer;
4509
68.7k
  }
4510
4511
  // Note: Older versions of clang used to emit byval references with an extra
4512
  // DW_OP_deref, because they referenced the IR arg directly instead of
4513
  // referencing an alloca. Newer versions of LLVM don't treat allocas
4514
  // differently from other function arguments when used in a dbg.declare.
4515
277k
  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4516
277k
  StringRef Name = VD->getName();
4517
277k
  if (!Name.empty()) {
4518
    // __block vars are stored on the heap if they are captured by a block that
4519
    // can escape the local scope.
4520
267k
    if (VD->isEscapingByref()) {
4521
      // Here, we need an offset *into* the alloca.
4522
11
      CharUnits offset = CharUnits::fromQuantity(32);
4523
11
      Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4524
      // offset of __forwarding field
4525
11
      offset = CGM.getContext().toCharUnitsFromBits(
4526
11
          CGM.getTarget().getPointerWidth(0));
4527
11
      Expr.push_back(offset.getQuantity());
4528
11
      Expr.push_back(llvm::dwarf::DW_OP_deref);
4529
11
      Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4530
      // offset of x field
4531
11
      offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4532
11
      Expr.push_back(offset.getQuantity());
4533
11
    }
4534
267k
  } else 
if (const auto *10.5k
RT10.5k
= dyn_cast<RecordType>(VD->getType())) {
4535
    // If VD is an anonymous union then Storage represents value for
4536
    // all union fields.
4537
1.86k
    const RecordDecl *RD = RT->getDecl();
4538
1.86k
    if (RD->isUnion() && 
RD->isAnonymousStructOrUnion()4
) {
4539
      // GDB has trouble finding local variables in anonymous unions, so we emit
4540
      // artificial local variables for each of the members.
4541
      //
4542
      // FIXME: Remove this code as soon as GDB supports this.
4543
      // The debug info verifier in LLVM operates based on the assumption that a
4544
      // variable has the same size as its storage and we had to disable the
4545
      // check for artificial variables.
4546
8
      for (const auto *Field : RD->fields()) {
4547
8
        llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4548
8
        StringRef FieldName = Field->getName();
4549
4550
        // Ignore unnamed fields. Do not ignore unnamed records.
4551
8
        if (FieldName.empty() && 
!isa<RecordType>(Field->getType())0
)
4552
0
          continue;
4553
4554
        // Use VarDecl's Tag, Scope and Line number.
4555
8
        auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
4556
8
        auto *D = DBuilder.createAutoVariable(
4557
8
            Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
4558
8
            Flags | llvm::DINode::FlagArtificial, FieldAlign);
4559
4560
        // Insert an llvm.dbg.declare into the current block.
4561
8
        DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4562
8
                               llvm::DILocation::get(CGM.getLLVMContext(), Line,
4563
8
                                                     Column, Scope,
4564
8
                                                     CurInlinedAt),
4565
8
                               Builder.GetInsertBlock());
4566
8
      }
4567
4
    }
4568
1.86k
  }
4569
4570
  // Clang stores the sret pointer provided by the caller in a static alloca.
4571
  // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4572
  // the address of the variable.
4573
277k
  if (UsePointerValue) {
4574
166
    assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
4575
166
           "Debug info already contains DW_OP_deref.");
4576
0
    Expr.push_back(llvm::dwarf::DW_OP_deref);
4577
166
  }
4578
4579
  // Create the descriptor for the variable.
4580
0
  llvm::DILocalVariable *D = nullptr;
4581
277k
  if (ArgNo) {
4582
172k
    llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD);
4583
172k
    D = DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line, Ty,
4584
172k
                                         CGM.getLangOpts().Optimize, Flags,
4585
172k
                                         Annotations);
4586
172k
  } else {
4587
    // For normal local variable, we will try to find out whether 'VD' is the
4588
    // copy parameter of coroutine.
4589
    // If yes, we are going to use DIVariable of the origin parameter instead
4590
    // of creating the new one.
4591
    // If no, it might be a normal alloc, we just create a new one for it.
4592
4593
    // Check whether the VD is move parameters.
4594
105k
    auto RemapCoroArgToLocalVar = [&]() -> llvm::DILocalVariable * {
4595
      // The scope of parameter and move-parameter should be distinct
4596
      // DISubprogram.
4597
105k
      if (!isa<llvm::DISubprogram>(Scope) || 
!Scope->isDistinct()35.8k
)
4598
69.2k
        return nullptr;
4599
4600
35.8k
      auto Iter = llvm::find_if(CoroutineParameterMappings, [&](auto &Pair) {
4601
18
        Stmt *StmtPtr = const_cast<Stmt *>(Pair.second);
4602
18
        if (DeclStmt *DeclStmtPtr = dyn_cast<DeclStmt>(StmtPtr)) {
4603
18
          DeclGroupRef DeclGroup = DeclStmtPtr->getDeclGroup();
4604
18
          Decl *Decl = DeclGroup.getSingleDecl();
4605
18
          if (VD == dyn_cast_or_null<VarDecl>(Decl))
4606
6
            return true;
4607
18
        }
4608
12
        return false;
4609
18
      });
4610
4611
35.8k
      if (Iter != CoroutineParameterMappings.end()) {
4612
6
        ParmVarDecl *PD = const_cast<ParmVarDecl *>(Iter->first);
4613
12
        auto Iter2 = llvm::find_if(ParamDbgMappings, [&](auto &DbgPair) {
4614
12
          return DbgPair.first == PD && 
DbgPair.second->getScope() == Scope6
;
4615
12
        });
4616
6
        if (Iter2 != ParamDbgMappings.end())
4617
6
          return const_cast<llvm::DILocalVariable *>(Iter2->second);
4618
6
      }
4619
35.8k
      return nullptr;
4620
35.8k
    };
4621
4622
    // If we couldn't find a move param DIVariable, create a new one.
4623
105k
    D = RemapCoroArgToLocalVar();
4624
    // Or we will create a new DIVariable for this Decl if D dose not exists.
4625
105k
    if (!D)
4626
105k
      D = DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4627
105k
                                      CGM.getLangOpts().Optimize, Flags, Align);
4628
105k
  }
4629
  // Insert an llvm.dbg.declare into the current block.
4630
277k
  DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4631
277k
                         llvm::DILocation::get(CGM.getLLVMContext(), Line,
4632
277k
                                               Column, Scope, CurInlinedAt),
4633
277k
                         Builder.GetInsertBlock());
4634
4635
277k
  return D;
4636
277k
}
4637
4638
llvm::DILocalVariable *
4639
CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
4640
                                       CGBuilderTy &Builder,
4641
105k
                                       const bool UsePointerValue) {
4642
105k
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4643
0
  return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue);
4644
105k
}
4645
4646
19
void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {
4647
19
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4648
0
  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4649
4650
19
  if (D->hasAttr<NoDebugAttr>())
4651
0
    return;
4652
4653
19
  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4654
19
  llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4655
4656
  // Get location information.
4657
19
  unsigned Line = getLineNumber(D->getLocation());
4658
19
  unsigned Column = getColumnNumber(D->getLocation());
4659
4660
19
  StringRef Name = D->getName();
4661
4662
  // Create the descriptor for the label.
4663
19
  auto *L =
4664
19
      DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
4665
4666
  // Insert an llvm.dbg.label into the current block.
4667
19
  DBuilder.insertLabel(L,
4668
19
                       llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
4669
19
                                             Scope, CurInlinedAt),
4670
19
                       Builder.GetInsertBlock());
4671
19
}
4672
4673
llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
4674
13.4k
                                          llvm::DIType *Ty) {
4675
13.4k
  llvm::DIType *CachedTy = getTypeOrNull(QualTy);
4676
13.4k
  if (CachedTy)
4677
13.4k
    Ty = CachedTy;
4678
13.4k
  return DBuilder.createObjectPointerType(Ty);
4679
13.4k
}
4680
4681
void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
4682
    const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
4683
1.15k
    const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
4684
1.15k
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4685
0
  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4686
4687
1.15k
  if (Builder.GetInsertBlock() == nullptr)
4688
0
    return;
4689
1.15k
  if (VD->hasAttr<NoDebugAttr>())
4690
1
    return;
4691
4692
1.15k
  bool isByRef = VD->hasAttr<BlocksAttr>();
4693
4694
1.15k
  uint64_t XOffset = 0;
4695
1.15k
  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4696
1.15k
  llvm::DIType *Ty;
4697
1.15k
  if (isByRef)
4698
13
    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4699
1.14k
  else
4700
1.14k
    Ty = getOrCreateType(VD->getType(), Unit);
4701
4702
  // Self is passed along as an implicit non-arg variable in a
4703
  // block. Mark it as the object pointer.
4704
1.15k
  if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
4705
9
    if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4706
9
      Ty = CreateSelfType(VD->getType(), Ty);
4707
4708
  // Get location information.
4709
1.15k
  const unsigned Line =
4710
1.15k
      getLineNumber(VD->getLocation().isValid() ? 
VD->getLocation()1.14k
:
CurLoc9
);
4711
1.15k
  unsigned Column = getColumnNumber(VD->getLocation());
4712
4713
1.15k
  const llvm::DataLayout &target = CGM.getDataLayout();
4714
4715
1.15k
  CharUnits offset = CharUnits::fromQuantity(
4716
1.15k
      target.getStructLayout(blockInfo.StructureType)
4717
1.15k
          ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
4718
4719
1.15k
  SmallVector<uint64_t, 9> addr;
4720
1.15k
  addr.push_back(llvm::dwarf::DW_OP_deref);
4721
1.15k
  addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4722
1.15k
  addr.push_back(offset.getQuantity());
4723
1.15k
  if (isByRef) {
4724
13
    addr.push_back(llvm::dwarf::DW_OP_deref);
4725
13
    addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4726
    // offset of __forwarding field
4727
13
    offset =
4728
13
        CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
4729
13
    addr.push_back(offset.getQuantity());
4730
13
    addr.push_back(llvm::dwarf::DW_OP_deref);
4731
13
    addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4732
    // offset of x field
4733
13
    offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4734
13
    addr.push_back(offset.getQuantity());
4735
13
  }
4736
4737
  // Create the descriptor for the variable.
4738
1.15k
  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4739
1.15k
  auto *D = DBuilder.createAutoVariable(
4740
1.15k
      cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
4741
1.15k
      Line, Ty, false, llvm::DINode::FlagZero, Align);
4742
4743
  // Insert an llvm.dbg.declare into the current block.
4744
1.15k
  auto DL = llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
4745
1.15k
                                  LexicalBlockStack.back(), CurInlinedAt);
4746
1.15k
  auto *Expr = DBuilder.createExpression(addr);
4747
1.15k
  if (InsertPoint)
4748
1.15k
    DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
4749
1
  else
4750
1
    DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
4751
1.15k
}
4752
4753
llvm::DILocalVariable *
4754
CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
4755
172k
                                      unsigned ArgNo, CGBuilderTy &Builder) {
4756
172k
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4757
0
  return EmitDeclare(VD, AI, ArgNo, Builder);
4758
172k
}
4759
4760
namespace {
4761
struct BlockLayoutChunk {
4762
  uint64_t OffsetInBits;
4763
  const BlockDecl::Capture *Capture;
4764
};
4765
4.40k
bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
4766
4.40k
  return l.OffsetInBits < r.OffsetInBits;
4767
4.40k
}
4768
} // namespace
4769
4770
void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
4771
    const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
4772
    const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
4773
169
    SmallVectorImpl<llvm::Metadata *> &Fields) {
4774
  // Blocks in OpenCL have unique constraints which make the standard fields
4775
  // redundant while requiring size and align fields for enqueue_kernel. See
4776
  // initializeForBlockHeader in CGBlocks.cpp
4777
169
  if (CGM.getLangOpts().OpenCL) {
4778
7
    Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
4779
7
                                     BlockLayout.getElementOffsetInBits(0),
4780
7
                                     Unit, Unit));
4781
7
    Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
4782
7
                                     BlockLayout.getElementOffsetInBits(1),
4783
7
                                     Unit, Unit));
4784
162
  } else {
4785
162
    Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
4786
162
                                     BlockLayout.getElementOffsetInBits(0),
4787
162
                                     Unit, Unit));
4788
162
    Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
4789
162
                                     BlockLayout.getElementOffsetInBits(1),
4790
162
                                     Unit, Unit));
4791
162
    Fields.push_back(
4792
162
        createFieldType("__reserved", Context.IntTy, Loc, AS_public,
4793
162
                        BlockLayout.getElementOffsetInBits(2), Unit, Unit));
4794
162
    auto *FnTy = Block.getBlockExpr()->getFunctionType();
4795
162
    auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
4796
162
    Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
4797
162
                                     BlockLayout.getElementOffsetInBits(3),
4798
162
                                     Unit, Unit));
4799
162
    Fields.push_back(createFieldType(
4800
162
        "__descriptor",
4801
162
        Context.getPointerType(Block.NeedsCopyDispose
4802
162
                                   ? 
Context.getBlockDescriptorExtendedType()98
4803
162
                                   : 
Context.getBlockDescriptorType()64
),
4804
162
        Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
4805
162
  }
4806
169
}
4807
4808
void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
4809
                                                       StringRef Name,
4810
                                                       unsigned ArgNo,
4811
                                                       llvm::AllocaInst *Alloca,
4812
169
                                                       CGBuilderTy &Builder) {
4813
169
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4814
0
  ASTContext &C = CGM.getContext();
4815
169
  const BlockDecl *blockDecl = block.getBlockDecl();
4816
4817
  // Collect some general information about the block's location.
4818
169
  SourceLocation loc = blockDecl->getCaretLocation();
4819
169
  llvm::DIFile *tunit = getOrCreateFile(loc);
4820
169
  unsigned line = getLineNumber(loc);
4821
169
  unsigned column = getColumnNumber(loc);
4822
4823
  // Build the debug-info type for the block literal.
4824
169
  getDeclContextDescriptor(blockDecl);
4825
4826
169
  const llvm::StructLayout *blockLayout =
4827
169
      CGM.getDataLayout().getStructLayout(block.StructureType);
4828
4829
169
  SmallVector<llvm::Metadata *, 16> fields;
4830
169
  collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
4831
169
                                             fields);
4832
4833
  // We want to sort the captures by offset, not because DWARF
4834
  // requires this, but because we're paranoid about debuggers.
4835
169
  SmallVector<BlockLayoutChunk, 8> chunks;
4836
4837
  // 'this' capture.
4838
169
  if (blockDecl->capturesCXXThis()) {
4839
1
    BlockLayoutChunk chunk;
4840
1
    chunk.OffsetInBits =
4841
1
        blockLayout->getElementOffsetInBits(block.CXXThisIndex);
4842
1
    chunk.Capture = nullptr;
4843
1
    chunks.push_back(chunk);
4844
1
  }
4845
4846
  // Variable captures.
4847
1.15k
  for (const auto &capture : blockDecl->captures()) {
4848
1.15k
    const VarDecl *variable = capture.getVariable();
4849
1.15k
    const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
4850
4851
    // Ignore constant captures.
4852
1.15k
    if (captureInfo.isConstant())
4853
0
      continue;
4854
4855
1.15k
    BlockLayoutChunk chunk;
4856
1.15k
    chunk.OffsetInBits =
4857
1.15k
        blockLayout->getElementOffsetInBits(captureInfo.getIndex());
4858
1.15k
    chunk.Capture = &capture;
4859
1.15k
    chunks.push_back(chunk);
4860
1.15k
  }
4861
4862
  // Sort by offset.
4863
169
  llvm::array_pod_sort(chunks.begin(), chunks.end());
4864
4865
1.15k
  for (const BlockLayoutChunk &Chunk : chunks) {
4866
1.15k
    uint64_t offsetInBits = Chunk.OffsetInBits;
4867
1.15k
    const BlockDecl::Capture *capture = Chunk.Capture;
4868
4869
    // If we have a null capture, this must be the C++ 'this' capture.
4870
1.15k
    if (!capture) {
4871
1
      QualType type;
4872
1
      if (auto *Method =
4873
1
              cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
4874
0
        type = Method->getThisType();
4875
1
      else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
4876
1
        type = QualType(RDecl->getTypeForDecl(), 0);
4877
0
      else
4878
0
        llvm_unreachable("unexpected block declcontext");
4879
4880
1
      fields.push_back(createFieldType("this", type, loc, AS_public,
4881
1
                                       offsetInBits, tunit, tunit));
4882
1
      continue;
4883
1
    }
4884
4885
1.15k
    const VarDecl *variable = capture->getVariable();
4886
1.15k
    StringRef name = variable->getName();
4887
4888
1.15k
    llvm::DIType *fieldType;
4889
1.15k
    if (capture->isByRef()) {
4890
13
      TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
4891
13
      auto Align = PtrInfo.isAlignRequired() ? 
PtrInfo.Align0
: 0;
4892
      // FIXME: This recomputes the layout of the BlockByRefWrapper.
4893
13
      uint64_t xoffset;
4894
13
      fieldType =
4895
13
          EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
4896
13
      fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
4897
13
      fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
4898
13
                                            PtrInfo.Width, Align, offsetInBits,
4899
13
                                            llvm::DINode::FlagZero, fieldType);
4900
1.14k
    } else {
4901
1.14k
      auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
4902
1.14k
      fieldType = createFieldType(name, variable->getType(), loc, AS_public,
4903
1.14k
                                  offsetInBits, Align, tunit, tunit);
4904
1.14k
    }
4905
1.15k
    fields.push_back(fieldType);
4906
1.15k
  }
4907
4908
169
  SmallString<36> typeName;
4909
169
  llvm::raw_svector_ostream(typeName)
4910
169
      << "__block_literal_" << CGM.getUniqueBlockCount();
4911
4912
169
  llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
4913
4914
169
  llvm::DIType *type =
4915
169
      DBuilder.createStructType(tunit, typeName.str(), tunit, line,
4916
169
                                CGM.getContext().toBits(block.BlockSize), 0,
4917
169
                                llvm::DINode::FlagZero, nullptr, fieldsArray);
4918
169
  type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
4919
4920
  // Get overall information about the block.
4921
169
  llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
4922
169
  auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
4923
4924
  // Create the descriptor for the parameter.
4925
169
  auto *debugVar = DBuilder.createParameterVariable(
4926
169
      scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
4927
4928
  // Insert an llvm.dbg.declare into the current block.
4929
169
  DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
4930
169
                         llvm::DILocation::get(CGM.getLLVMContext(), line,
4931
169
                                               column, scope, CurInlinedAt),
4932
169
                         Builder.GetInsertBlock());
4933
169
}
4934
4935
llvm::DIDerivedType *
4936
4.92k
CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
4937
4.92k
  if (!D || 
!D->isStaticDataMember()4.92k
)
4938
4.82k
    return nullptr;
4939
4940
100
  auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
4941
100
  if (MI != StaticDataMemberCache.end()) {
4942
25
    assert(MI->second && "Static data member declaration should still exist");
4943
0
    return MI->second;
4944
25
  }
4945
4946
  // If the member wasn't found in the cache, lazily construct and add it to the
4947
  // type (used when a limited form of the type is emitted).
4948
75
  auto DC = D->getDeclContext();
4949
75
  auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
4950
75
  return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
4951
100
}
4952
4953
llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
4954
    const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
4955
5
    StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
4956
5
  llvm::DIGlobalVariableExpression *GVE = nullptr;
4957
4958
9
  for (const auto *Field : RD->fields()) {
4959
9
    llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4960
9
    StringRef FieldName = Field->getName();
4961
4962
    // Ignore unnamed fields, but recurse into anonymous records.
4963
9
    if (FieldName.empty()) {
4964
2
      if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
4965
2
        GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
4966
2
                                     Var, DContext);
4967
2
      continue;
4968
2
    }
4969
    // Use VarDecl's Tag, Scope and Line number.
4970
7
    GVE = DBuilder.createGlobalVariableExpression(
4971
7
        DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
4972
7
        Var->hasLocalLinkage());
4973
7
    Var->addDebugInfo(GVE);
4974
7
  }
4975
5
  return GVE;
4976
5
}
4977
4978
namespace {
4979
struct ReconstitutableType : public RecursiveASTVisitor<ReconstitutableType> {
4980
  bool Reconstitutable = true;
4981
3
  bool VisitVectorType(VectorType *FT) {
4982
3
    Reconstitutable = false;
4983
3
    return false;
4984
3
  }
4985
93
  bool VisitAtomicType(AtomicType *FT) {
4986
93
    Reconstitutable = false;
4987
93
    return false;
4988
93
  }
4989
493
  bool TraverseEnumType(EnumType *ET) {
4990
    // Unnamed enums can't be reconstituted due to a lack of column info we
4991
    // produce in the DWARF, so we can't get Clang's full name back.
4992
493
    if (const auto *ED = dyn_cast<EnumDecl>(ET->getDecl())) {
4993
493
      if (!ED->getIdentifier()) {
4994
101
        Reconstitutable = false;
4995
101
        return false;
4996
101
      }
4997
493
    }
4998
392
    return true;
4999
493
  }
5000
5.83k
  bool VisitFunctionProtoType(FunctionProtoType *FT) {
5001
    // noexcept is not encoded in DWARF, so the reversi
5002
5.83k
    Reconstitutable &= !isNoexceptExceptionSpec(FT->getExceptionSpecType());
5003
5.83k
    return Reconstitutable;
5004
5.83k
  }
5005
97.1k
  bool TraverseRecordType(RecordType *RT) {
5006
    // Unnamed classes/lambdas can't be reconstituted due to a lack of column
5007
    // info we produce in the DWARF, so we can't get Clang's full name back.
5008
    // But so long as it's not one of those, it doesn't matter if some sub-type
5009
    // of the record (a template parameter) can't be reconstituted - because the
5010
    // un-reconstitutable type itself will carry its own name.
5011
97.1k
    const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5012
97.1k
    if (!RD)
5013
0
      return true;
5014
97.1k
    if (RD->isLambda() || 
!RD->getIdentifier()95.3k
) {
5015
1.97k
      Reconstitutable = false;
5016
1.97k
      return false;
5017
1.97k
    }
5018
95.1k
    return true;
5019
97.1k
  }
5020
};
5021
} // anonymous namespace
5022
5023
// Test whether a type name could be rebuilt from emitted debug info.
5024
163k
static bool IsReconstitutableType(QualType QT) {
5025
163k
  ReconstitutableType T;
5026
163k
  T.TraverseType(QT);
5027
163k
  return T.Reconstitutable;
5028
163k
}
5029
5030
780k
std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const {
5031
780k
  std::string Name;
5032
780k
  llvm::raw_string_ostream OS(Name);
5033
780k
  const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5034
780k
  if (!ND)
5035
0
    return Name;
5036
780k
  codegenoptions::DebugTemplateNamesKind TemplateNamesKind =
5037
780k
      CGM.getCodeGenOpts().getDebugSimpleTemplateNames();
5038
780k
  Optional<TemplateArgs> Args;
5039
5040
780k
  bool IsOperatorOverload = false; // isa<CXXConversionDecl>(ND);
5041
780k
  if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
5042
71.3k
    Args = GetTemplateArgs(RD);
5043
709k
  } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
5044
709k
    Args = GetTemplateArgs(FD);
5045
709k
    auto NameKind = ND->getDeclName().getNameKind();
5046
709k
    IsOperatorOverload |=
5047
709k
        NameKind == DeclarationName::CXXOperatorName ||
5048
709k
        
NameKind == DeclarationName::CXXConversionFunctionName656k
;
5049
709k
  } else 
if (auto *0
VD0
= dyn_cast<VarDecl>(ND)) {
5050
0
    Args = GetTemplateArgs(VD);
5051
0
  }
5052
780k
  std::function<bool(ArrayRef<TemplateArgument>)> HasReconstitutableArgs =
5053
780k
      [&](ArrayRef<TemplateArgument> Args) {
5054
216k
        return llvm::all_of(Args, [&](const TemplateArgument &TA) {
5055
216k
          switch (TA.getKind()) {
5056
345
          case TemplateArgument::Template:
5057
            // Easy to reconstitute - the value of the parameter in the debug
5058
            // info is the string name of the template. (so the template name
5059
            // itself won't benefit from any name rebuilding, but that's a
5060
            // representational limitation - maybe DWARF could be
5061
            // changed/improved to use some more structural representation)
5062
345
            return true;
5063
24
          case TemplateArgument::Declaration:
5064
            // Reference and pointer non-type template parameters point to
5065
            // variables, functions, etc and their value is, at best (for
5066
            // variables) represented as an address - not a reference to the
5067
            // DWARF describing the variable/function/etc. This makes it hard,
5068
            // possibly impossible to rebuild the original name - looking up the
5069
            // address in the executable file's symbol table would be needed.
5070
24
            return false;
5071
451
          case TemplateArgument::NullPtr:
5072
            // These could be rebuilt, but figured they're close enough to the
5073
            // declaration case, and not worth rebuilding.
5074
451
            return false;
5075
17.1k
          case TemplateArgument::Pack:
5076
            // A pack is invalid if any of the elements of the pack are invalid.
5077
17.1k
            return HasReconstitutableArgs(TA.getPackAsArray());
5078
35.2k
          case TemplateArgument::Integral:
5079
            // Larger integers get encoded as DWARF blocks which are a bit
5080
            // harder to parse back into a large integer, etc - so punting on
5081
            // this for now. Re-parsing the integers back into APInt is probably
5082
            // feasible some day.
5083
35.2k
            return TA.getAsIntegral().getBitWidth() <= 64;
5084
163k
          case TemplateArgument::Type:
5085
163k
            return IsReconstitutableType(TA.getAsType());
5086
0
          default:
5087
0
            llvm_unreachable("Other, unresolved, template arguments should "
5088
216k
                             "not be seen here");
5089
216k
          }
5090
216k
        });
5091
130k
      };
5092
  // A conversion operator presents complications/ambiguity if there's a
5093
  // conversion to class template that is itself a template, eg:
5094
  // template<typename T>
5095
  // operator ns::t1<T, int>();
5096
  // This should be named, eg: "operator ns::t1<float, int><float>"
5097
  // (ignoring clang bug that means this is currently "operator t1<float>")
5098
  // but if the arguments were stripped, the consumer couldn't differentiate
5099
  // whether the template argument list for the conversion type was the
5100
  // function's argument list (& no reconstitution was needed) or not.
5101
  // This could be handled if reconstitutable names had a separate attribute
5102
  // annotating them as such - this would remove the ambiguity.
5103
  //
5104
  // Alternatively the template argument list could be parsed enough to check
5105
  // whether there's one list or two, then compare that with the DWARF
5106
  // description of the return type and the template argument lists to determine
5107
  // how many lists there should be and if one is missing it could be assumed(?)
5108
  // to be the function's template argument list  & then be rebuilt.
5109
  //
51