Coverage Report

Created: 2021-01-23 06:44

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