Coverage Report

Created: 2020-02-25 14:32

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