Coverage Report

Created: 2017-10-03 07:32

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/clang/lib/CodeGen/CGDebugInfo.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2
//
3
//                     The LLVM Compiler Infrastructure
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
// This coordinates the debug information generation while generating code.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "CGDebugInfo.h"
15
#include "CGBlocks.h"
16
#include "CGCXXABI.h"
17
#include "CGObjCRuntime.h"
18
#include "CGRecordLayout.h"
19
#include "CodeGenFunction.h"
20
#include "CodeGenModule.h"
21
#include "ConstantEmitter.h"
22
#include "clang/AST/ASTContext.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/FileManager.h"
29
#include "clang/Basic/SourceManager.h"
30
#include "clang/Basic/Version.h"
31
#include "clang/Frontend/CodeGenOptions.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/Module.h"
45
#include "llvm/Support/FileSystem.h"
46
#include "llvm/Support/MD5.h"
47
#include "llvm/Support/Path.h"
48
using namespace clang;
49
using namespace clang::CodeGen;
50
51
2.84k
static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
52
2.84k
  auto TI = Ctx.getTypeInfo(Ty);
53
2.84k
  return TI.AlignIsRequired ? 
TI.Align0
:
02.84k
;
54
2.84k
}
55
56
996
static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
57
996
  return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
58
996
}
59
60
5.33k
static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
61
5.33k
  return D->hasAttr<AlignedAttr>() ? 
D->getMaxAlignment()0
:
05.33k
;
62
5.33k
}
63
64
CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
65
    : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
66
      DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
67
1.32k
      DBuilder(CGM.getModule()) {
68
1.32k
  for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
69
4
    DebugPrefixMap[KV.first] = KV.second;
70
1.32k
  CreateCompileUnit();
71
1.32k
}
72
73
1.32k
CGDebugInfo::~CGDebugInfo() {
74
1.32k
  assert(LexicalBlockStack.empty() &&
75
1.32k
         "Region stack mismatch, stack not empty!");
76
1.32k
}
77
78
ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
79
                                       SourceLocation TemporaryLocation)
80
509k
    : CGF(&CGF) {
81
509k
  init(TemporaryLocation);
82
509k
}
83
84
ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
85
                                       bool DefaultToEmpty,
86
                                       SourceLocation TemporaryLocation)
87
436k
    : CGF(&CGF) {
88
436k
  init(TemporaryLocation, DefaultToEmpty);
89
436k
}
90
91
void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
92
14.1M
                              bool DefaultToEmpty) {
93
14.1M
  auto *DI = CGF->getDebugInfo();
94
14.1M
  if (
!DI14.1M
) {
95
13.2M
    CGF = nullptr;
96
13.2M
    return;
97
13.2M
  }
98
885k
99
885k
  OriginalLocation = CGF->Builder.getCurrentDebugLocation();
100
885k
101
885k
  if (
OriginalLocation && 885k
!DI->CGM.getExpressionLocationsEnabled()885k
)
102
261
    return;
103
885k
104
885k
  
if (885k
TemporaryLocation.isValid()885k
) {
105
877k
    DI->EmitLocation(CGF->Builder, TemporaryLocation);
106
877k
    return;
107
877k
  }
108
7.97k
109
7.97k
  
if (7.97k
DefaultToEmpty7.97k
) {
110
5.80k
    CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
111
5.80k
    return;
112
5.80k
  }
113
2.17k
114
2.17k
  // Construct a location that has a valid scope, but no line info.
115
7.97k
  assert(!DI->LexicalBlockStack.empty());
116
2.17k
  CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
117
2.17k
      0, 0, DI->LexicalBlockStack.back(), DI->getInlinedAt()));
118
2.17k
}
119
120
ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
121
13.2M
    : CGF(&CGF) {
122
13.2M
  init(E->getExprLoc());
123
13.2M
}
124
125
ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
126
185k
    : CGF(&CGF) {
127
185k
  if (
!CGF.getDebugInfo()185k
) {
128
163k
    this->CGF = nullptr;
129
163k
    return;
130
163k
  }
131
22.4k
  OriginalLocation = CGF.Builder.getCurrentDebugLocation();
132
22.4k
  if (Loc)
133
6.14k
    CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
134
185k
}
135
136
14.3M
ApplyDebugLocation::~ApplyDebugLocation() {
137
14.3M
  // Query CGF so the location isn't overwritten when location updates are
138
14.3M
  // temporarily disabled (for C++ default function arguments)
139
14.3M
  if (CGF)
140
908k
    CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
141
14.3M
}
142
143
ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF,
144
                                                   GlobalDecl InlinedFn)
145
44
    : CGF(&CGF) {
146
44
  if (
!CGF.getDebugInfo()44
) {
147
41
    this->CGF = nullptr;
148
41
    return;
149
41
  }
150
3
  auto &DI = *CGF.getDebugInfo();
151
3
  SavedLocation = DI.getLocation();
152
3
  assert((DI.getInlinedAt() ==
153
3
          CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
154
3
         "CGDebugInfo and IRBuilder are out of sync");
155
3
156
3
  DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
157
3
}
158
159
44
ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
160
44
  if (!CGF)
161
41
    return;
162
3
  auto &DI = *CGF->getDebugInfo();
163
3
  DI.EmitInlineFunctionEnd(CGF->Builder);
164
3
  DI.EmitLocation(CGF->Builder, SavedLocation);
165
3
}
166
167
1.14M
void CGDebugInfo::setLocation(SourceLocation Loc) {
168
1.14M
  // If the new location isn't valid return.
169
1.14M
  if (Loc.isInvalid())
170
573
    return;
171
1.14M
172
1.14M
  CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
173
1.14M
174
1.14M
  // If we've changed files in the middle of a lexical scope go ahead
175
1.14M
  // and create a new lexical scope with file node if it's different
176
1.14M
  // from the one in the scope.
177
1.14M
  if (LexicalBlockStack.empty())
178
411
    return;
179
1.14M
180
1.14M
  SourceManager &SM = CGM.getContext().getSourceManager();
181
1.14M
  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
182
1.14M
  PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
183
1.14M
184
1.14M
  if (
PCLoc.isInvalid() || 1.14M
Scope->getFilename() == PCLoc.getFilename()1.14M
)
185
1.14M
    return;
186
361
187
361
  
if (auto *361
LBF361
= dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
188
216
    LexicalBlockStack.pop_back();
189
216
    LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
190
216
        LBF->getScope(), getOrCreateFile(CurLoc)));
191
361
  } else 
if (145
isa<llvm::DILexicalBlock>(Scope) ||
192
145
             
isa<llvm::DISubprogram>(Scope)145
) {
193
145
    LexicalBlockStack.pop_back();
194
145
    LexicalBlockStack.emplace_back(
195
145
        DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
196
145
  }
197
1.14M
}
198
199
2.90k
llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
200
2.90k
  llvm::DIScope *Mod = getParentModuleOrNull(D);
201
2.90k
  return getContextDescriptor(cast<Decl>(D->getDeclContext()),
202
2.90k
                              Mod ? 
Mod334
:
TheCU2.56k
);
203
2.90k
}
204
205
llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
206
4.01k
                                                 llvm::DIScope *Default) {
207
4.01k
  if (!Context)
208
0
    return Default;
209
4.01k
210
4.01k
  auto I = RegionMap.find(Context);
211
4.01k
  if (
I != RegionMap.end()4.01k
) {
212
1.10k
    llvm::Metadata *V = I->second;
213
1.10k
    return dyn_cast_or_null<llvm::DIScope>(V);
214
1.10k
  }
215
2.90k
216
2.90k
  // Check namespace.
217
2.90k
  
if (const auto *2.90k
NSDecl2.90k
= dyn_cast<NamespaceDecl>(Context))
218
297
    return getOrCreateNamespace(NSDecl);
219
2.60k
220
2.60k
  
if (const auto *2.60k
RDecl2.60k
= dyn_cast<RecordDecl>(Context))
221
410
    
if (410
!RDecl->isDependentType()410
)
222
410
      return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
223
410
                             getOrCreateMainFile());
224
2.19k
  return Default;
225
2.19k
}
226
227
2.14k
PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
228
2.14k
  PrintingPolicy PP = CGM.getContext().getPrintingPolicy();
229
2.14k
230
2.14k
  // If we're emitting codeview, it's important to try to match MSVC's naming so
231
2.14k
  // that visualizers written for MSVC will trigger for our class names. In
232
2.14k
  // particular, we can't have spaces between arguments of standard templates
233
2.14k
  // like basic_string and vector.
234
2.14k
  if (CGM.getCodeGenOpts().EmitCodeView)
235
22
    PP.MSVCFormatting = true;
236
2.14k
237
2.14k
  return PP;
238
2.14k
}
239
240
22.9k
StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
241
22.9k
  assert(FD && "Invalid FunctionDecl!");
242
22.9k
  IdentifierInfo *FII = FD->getIdentifier();
243
22.9k
  FunctionTemplateSpecializationInfo *Info =
244
22.9k
      FD->getTemplateSpecializationInfo();
245
22.9k
246
22.9k
  // Emit the unqualified name in normal operation. LLVM and the debugger can
247
22.9k
  // compute the fully qualified name from the scope chain. If we're only
248
22.9k
  // emitting line table info, there won't be any scope chains, so emit the
249
22.9k
  // fully qualified name here so that stack traces are more accurate.
250
22.9k
  // FIXME: Do this when emitting DWARF as well as when emitting CodeView after
251
22.9k
  // evaluating the size impact.
252
22.9k
  bool UseQualifiedName = DebugKind == codegenoptions::DebugLineTablesOnly &&
253
20.7k
                          CGM.getCodeGenOpts().EmitCodeView;
254
22.9k
255
22.9k
  if (
!Info && 22.9k
FII21.2k
&&
!UseQualifiedName15.8k
)
256
15.8k
    return FII->getName();
257
7.09k
258
7.09k
  SmallString<128> NS;
259
7.09k
  llvm::raw_svector_ostream OS(NS);
260
7.09k
  if (!UseQualifiedName)
261
7.07k
    FD->printName(OS);
262
7.09k
  else
263
18
    FD->printQualifiedName(OS, getPrintingPolicy());
264
7.09k
265
7.09k
  // Add any template specialization args.
266
7.09k
  if (
Info7.09k
) {
267
1.76k
    const TemplateArgumentList *TArgs = Info->TemplateArguments;
268
1.76k
    TemplateSpecializationType::PrintTemplateArgumentList(OS, TArgs->asArray(),
269
1.76k
                                                          getPrintingPolicy());
270
1.76k
  }
271
22.9k
272
22.9k
  // Copy this name on the side and use its reference.
273
22.9k
  return internString(OS.str());
274
22.9k
}
275
276
130
StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
277
130
  SmallString<256> MethodName;
278
130
  llvm::raw_svector_ostream OS(MethodName);
279
130
  OS << (OMD->isInstanceMethod() ? 
'-'114
:
'+'16
) << '[';
280
130
  const DeclContext *DC = OMD->getDeclContext();
281
130
  if (const auto *
OID130
= dyn_cast<ObjCImplementationDecl>(DC)) {
282
53
    OS << OID->getName();
283
130
  } else 
if (const auto *77
OID77
= dyn_cast<ObjCInterfaceDecl>(DC)) {
284
64
    OS << OID->getName();
285
77
  } else 
if (const auto *13
OC13
= dyn_cast<ObjCCategoryDecl>(DC)) {
286
8
    if (
OC->IsClassExtension()8
) {
287
5
      OS << OC->getClassInterface()->getName();
288
8
    } else {
289
3
      OS << OC->getIdentifier()->getNameStart() << '('
290
3
         << OC->getIdentifier()->getNameStart() << ')';
291
3
    }
292
13
  } else 
if (const auto *5
OCD5
= dyn_cast<ObjCCategoryImplDecl>(DC)) {
293
1
    OS << OCD->getClassInterface()->getName() << '('
294
1
       << OCD->getName() << ')';
295
5
  } else 
if (4
isa<ObjCProtocolDecl>(DC)4
) {
296
4
    // We can extract the type of the class from the self pointer.
297
4
    if (ImplicitParamDecl *
SelfDecl4
= OMD->getSelfDecl()) {
298
4
      QualType ClassTy =
299
4
          cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
300
4
      ClassTy.print(OS, PrintingPolicy(LangOptions()));
301
4
    }
302
77
  }
303
130
  OS << ' ' << OMD->getSelector().getAsString() << ']';
304
130
305
130
  return internString(OS.str());
306
130
}
307
308
7
StringRef CGDebugInfo::getSelectorName(Selector S) {
309
7
  return internString(S.getAsString());
310
7
}
311
312
1.13k
StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
313
1.13k
  if (
isa<ClassTemplateSpecializationDecl>(RD)1.13k
) {
314
363
    SmallString<128> Name;
315
363
    llvm::raw_svector_ostream OS(Name);
316
363
    RD->getNameForDiagnostic(OS, getPrintingPolicy(),
317
363
                             /*Qualified*/ false);
318
363
319
363
    // Copy this name on the side and use its reference.
320
363
    return internString(Name);
321
363
  }
322
771
323
771
  // quick optimization to avoid having to intern strings that are already
324
771
  // stored reliably elsewhere
325
771
  
if (const IdentifierInfo *771
II771
= RD->getIdentifier())
326
663
    return II->getName();
327
108
328
108
  // The CodeView printer in LLVM wants to see the names of unnamed types: it is
329
108
  // used to reconstruct the fully qualified type names.
330
108
  
if (108
CGM.getCodeGenOpts().EmitCodeView108
) {
331
3
    if (const TypedefNameDecl *
D3
= RD->getTypedefNameForAnonDecl()) {
332
1
      assert(RD->getDeclContext() == D->getDeclContext() &&
333
1
             "Typedef should not be in another decl context!");
334
1
      assert(D->getDeclName().getAsIdentifierInfo() &&
335
1
             "Typedef was not named!");
336
1
      return D->getDeclName().getAsIdentifierInfo()->getName();
337
1
    }
338
2
339
2
    
if (2
CGM.getLangOpts().CPlusPlus2
) {
340
2
      StringRef Name;
341
2
342
2
      ASTContext &Context = CGM.getContext();
343
2
      if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
344
2
        // Anonymous types without a name for linkage purposes have their
345
2
        // declarator mangled in if they have one.
346
1
        Name = DD->getName();
347
1
      else 
if (const TypedefNameDecl *1
TND1
=
348
1
                   Context.getTypedefNameForUnnamedTagDecl(RD))
349
1
        // Anonymous types without a name for linkage purposes have their
350
1
        // associate typedef mangled in if they have one.
351
1
        Name = TND->getName();
352
2
353
2
      if (
!Name.empty()2
) {
354
2
        SmallString<256> UnnamedType("<unnamed-type-");
355
2
        UnnamedType += Name;
356
2
        UnnamedType += '>';
357
2
        return internString(UnnamedType);
358
2
      }
359
105
    }
360
3
  }
361
105
362
105
  return StringRef();
363
105
}
364
365
llvm::DIFile::ChecksumKind
366
4.13k
CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
367
4.13k
  Checksum.clear();
368
4.13k
369
4.13k
  if (!CGM.getCodeGenOpts().EmitCodeView)
370
4.10k
    return llvm::DIFile::CSK_None;
371
30
372
30
  SourceManager &SM = CGM.getContext().getSourceManager();
373
30
  bool Invalid;
374
30
  llvm::MemoryBuffer *MemBuffer = SM.getBuffer(FID, &Invalid);
375
30
  if (Invalid)
376
0
    return llvm::DIFile::CSK_None;
377
30
378
30
  llvm::MD5 Hash;
379
30
  llvm::MD5::MD5Result Result;
380
30
381
30
  Hash.update(MemBuffer->getBuffer());
382
30
  Hash.final(Result);
383
30
384
30
  Hash.stringifyResult(Result, Checksum);
385
30
  return llvm::DIFile::CSK_MD5;
386
30
}
387
388
30.7k
llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
389
30.7k
  if (!Loc.isValid())
390
30.7k
    // If Location is not valid then use main input file.
391
372
    return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
392
372
                               remapDIPath(TheCU->getDirectory()),
393
372
                               TheCU->getFile()->getChecksumKind(),
394
372
                               TheCU->getFile()->getChecksum());
395
30.3k
396
30.3k
  SourceManager &SM = CGM.getContext().getSourceManager();
397
30.3k
  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
398
30.3k
399
30.3k
  if (
PLoc.isInvalid() || 30.3k
StringRef(PLoc.getFilename()).empty()30.3k
)
400
30.3k
    // If the location is not valid then use main input file.
401
8
    return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
402
8
                               remapDIPath(TheCU->getDirectory()),
403
8
                               TheCU->getFile()->getChecksumKind(),
404
8
                               TheCU->getFile()->getChecksum());
405
30.3k
406
30.3k
  // Cache the results.
407
30.3k
  const char *fname = PLoc.getFilename();
408
30.3k
  auto it = DIFileCache.find(fname);
409
30.3k
410
30.3k
  if (
it != DIFileCache.end()30.3k
) {
411
27.4k
    // Verify that the information still exists.
412
27.4k
    if (llvm::Metadata *V = it->second)
413
27.4k
      return cast<llvm::DIFile>(V);
414
2.88k
  }
415
2.88k
416
2.88k
  SmallString<32> Checksum;
417
2.88k
  llvm::DIFile::ChecksumKind CSKind =
418
2.88k
      computeChecksum(SM.getFileID(Loc), Checksum);
419
2.88k
420
2.88k
  llvm::DIFile *F = DBuilder.createFile(remapDIPath(PLoc.getFilename()),
421
2.88k
                                        remapDIPath(getCurrentDirname()),
422
2.88k
                                        CSKind, Checksum);
423
2.88k
424
2.88k
  DIFileCache[fname].reset(F);
425
2.88k
  return F;
426
2.88k
}
427
428
614
llvm::DIFile *CGDebugInfo::getOrCreateMainFile() {
429
614
  return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
430
614
                             remapDIPath(TheCU->getDirectory()),
431
614
                             TheCU->getFile()->getChecksumKind(),
432
614
                             TheCU->getFile()->getChecksum());
433
614
}
434
435
11.6k
std::string CGDebugInfo::remapDIPath(StringRef Path) const {
436
11.6k
  for (const auto &Entry : DebugPrefixMap)
437
100
    
if (100
Path.startswith(Entry.first)100
)
438
15
      return (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
439
11.6k
  return Path.str();
440
11.6k
}
441
442
1.21M
unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
443
1.21M
  if (
Loc.isInvalid() && 1.21M
CurLoc.isInvalid()478
)
444
244
    return 0;
445
1.21M
  SourceManager &SM = CGM.getContext().getSourceManager();
446
1.21M
  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? 
Loc1.21M
:
CurLoc234
);
447
1.21M
  return PLoc.isValid() ? 
PLoc.getLine()1.21M
:
00
;
448
1.21M
}
449
450
1.16M
unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
451
1.16M
  // We may not want column information at all.
452
1.16M
  if (
!Force && 1.16M
!CGM.getCodeGenOpts().DebugColumnInfo1.16M
)
453
39.2k
    return 0;
454
1.12M
455
1.12M
  // If the location is invalid then use the current column.
456
1.12M
  
if (1.12M
Loc.isInvalid() && 1.12M
CurLoc.isInvalid()1
)
457
0
    return 0;
458
1.12M
  SourceManager &SM = CGM.getContext().getSourceManager();
459
1.12M
  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? 
Loc1.12M
:
CurLoc1
);
460
1.12M
  return PLoc.isValid() ? 
PLoc.getColumn()1.12M
:
00
;
461
1.16M
}
462
463
4.21k
StringRef CGDebugInfo::getCurrentDirname() {
464
4.21k
  if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
465
3.30k
    return CGM.getCodeGenOpts().DebugCompilationDir;
466
907
467
907
  
if (907
!CWDName.empty()907
)
468
456
    return CWDName;
469
451
  SmallString<256> CWD;
470
451
  llvm::sys::fs::current_path(CWD);
471
451
  return CWDName = internString(CWD);
472
451
}
473
474
1.32k
void CGDebugInfo::CreateCompileUnit() {
475
1.32k
  SmallString<32> Checksum;
476
1.32k
  llvm::DIFile::ChecksumKind CSKind = llvm::DIFile::CSK_None;
477
1.32k
478
1.32k
  // Should we be asking the SourceManager for the main file name, instead of
479
1.32k
  // accepting it as an argument? This just causes the main file name to
480
1.32k
  // mismatch with source locations and create extra lexical scopes or
481
1.32k
  // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
482
1.32k
  // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
483
1.32k
  // because that's what the SourceManager says)
484
1.32k
485
1.32k
  // Get absolute path name.
486
1.32k
  SourceManager &SM = CGM.getContext().getSourceManager();
487
1.32k
  std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
488
1.32k
  if (MainFileName.empty())
489
424
    MainFileName = "<stdin>";
490
1.32k
491
1.32k
  // The main file name provided via the "-main-file-name" option contains just
492
1.32k
  // the file name itself with no path information. This file name may have had
493
1.32k
  // a relative path, so we look into the actual file entry for the main
494
1.32k
  // file to determine the real absolute path for the file.
495
1.32k
  std::string MainFileDir;
496
1.32k
  if (const FileEntry *
MainFile1.32k
= SM.getFileEntryForID(SM.getMainFileID())) {
497
1.24k
    MainFileDir = remapDIPath(MainFile->getDir()->getName());
498
1.24k
    if (
MainFileDir != "."1.24k
) {
499
1.23k
      llvm::SmallString<1024> MainFileDirSS(MainFileDir);
500
1.23k
      llvm::sys::path::append(MainFileDirSS, MainFileName);
501
1.23k
      MainFileName = MainFileDirSS.str();
502
1.23k
    }
503
1.24k
    // If the main file name provided is identical to the input file name, and
504
1.24k
    // if the input file is a preprocessed source, use the module name for
505
1.24k
    // debug info. The module name comes from the name specified in the first
506
1.24k
    // linemarker if the input is a preprocessed source.
507
1.24k
    if (MainFile->getName() == MainFileName &&
508
894
        FrontendOptions::getInputKindForExtension(
509
894
            MainFile->getName().rsplit('.').second)
510
894
            .isPreprocessed())
511
0
      MainFileName = CGM.getModule().getName().str();
512
1.24k
513
1.24k
    CSKind = computeChecksum(SM.getMainFileID(), Checksum);
514
1.24k
  }
515
1.32k
516
1.32k
  llvm::dwarf::SourceLanguage LangTag;
517
1.32k
  const LangOptions &LO = CGM.getLangOpts();
518
1.32k
  if (
LO.CPlusPlus1.32k
) {
519
1.07k
    if (LO.ObjC1)
520
26
      LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
521
1.07k
    else
522
1.05k
      LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
523
1.32k
  } else 
if (251
LO.ObjC1251
) {
524
76
    LangTag = llvm::dwarf::DW_LANG_ObjC;
525
251
  } else 
if (175
LO.RenderScript175
) {
526
1
    LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
527
175
  } else 
if (174
LO.C99174
) {
528
174
    LangTag = llvm::dwarf::DW_LANG_C99;
529
174
  } else {
530
0
    LangTag = llvm::dwarf::DW_LANG_C89;
531
0
  }
532
1.32k
533
1.32k
  std::string Producer = getClangFullVersion();
534
1.32k
535
1.32k
  // Figure out which version of the ObjC runtime we have.
536
1.32k
  unsigned RuntimeVers = 0;
537
1.32k
  if (LO.ObjC1)
538
102
    
RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 102
296
:
16
;
539
1.32k
540
1.32k
  llvm::DICompileUnit::DebugEmissionKind EmissionKind;
541
1.32k
  switch (DebugKind) {
542
29
  case codegenoptions::NoDebugInfo:
543
29
  case codegenoptions::LocTrackingOnly:
544
29
    EmissionKind = llvm::DICompileUnit::NoDebug;
545
29
    break;
546
839
  case codegenoptions::DebugLineTablesOnly:
547
839
    EmissionKind = llvm::DICompileUnit::LineTablesOnly;
548
839
    break;
549
460
  case codegenoptions::LimitedDebugInfo:
550
460
  case codegenoptions::FullDebugInfo:
551
460
    EmissionKind = llvm::DICompileUnit::FullDebug;
552
460
    break;
553
1.32k
  }
554
1.32k
555
1.32k
  // Create new compile unit.
556
1.32k
  // FIXME - Eliminate TheCU.
557
1.32k
  auto &CGOpts = CGM.getCodeGenOpts();
558
1.32k
  TheCU = DBuilder.createCompileUnit(
559
1.32k
      LangTag,
560
1.32k
      DBuilder.createFile(remapDIPath(MainFileName),
561
1.32k
                          remapDIPath(getCurrentDirname()), CSKind, Checksum),
562
1.32k
      Producer, LO.Optimize || 
CGOpts.PrepareForLTO505
||
CGOpts.EmitSummaryIndex500
,
563
1.32k
      CGOpts.DwarfDebugFlags, RuntimeVers,
564
1.32k
      CGOpts.EnableSplitDwarf ? 
""1
:
CGOpts.SplitDwarfFile1.32k
, EmissionKind,
565
1.32k
      0 /* DWOid */, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
566
1.32k
      CGOpts.GnuPubnames);
567
1.32k
}
568
569
1.37k
llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
570
1.37k
  llvm::dwarf::TypeKind Encoding;
571
1.37k
  StringRef BTName;
572
1.37k
  switch (BT->getKind()) {
573
1.37k
#define BUILTIN_TYPE(Id, SingletonId)
574
0
#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
575
1.37k
#include 
"clang/AST/BuiltinTypes.def"1.37k
576
0
  case BuiltinType::Dependent:
577
0
    llvm_unreachable("Unexpected builtin type");
578
1
  case BuiltinType::NullPtr:
579
1
    return DBuilder.createNullPtrType();
580
720
  case BuiltinType::Void:
581
720
    return nullptr;
582
12
  case BuiltinType::ObjCClass:
583
12
    if (!ClassTy)
584
9
      ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
585
9
                                           "objc_class", TheCU,
586
9
                                           getOrCreateMainFile(), 0);
587
12
    return ClassTy;
588
21
  case BuiltinType::ObjCId: {
589
21
    // typedef struct objc_class *Class;
590
21
    // typedef struct objc_object {
591
21
    //  Class isa;
592
21
    // } *id;
593
21
594
21
    if (ObjTy)
595
0
      return ObjTy;
596
21
597
21
    
if (21
!ClassTy21
)
598
15
      ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
599
15
                                           "objc_class", TheCU,
600
15
                                           getOrCreateMainFile(), 0);
601
21
602
21
    unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
603
21
604
21
    auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
605
21
606
21
    ObjTy = DBuilder.createStructType(
607
21
        TheCU, "objc_object", getOrCreateMainFile(), 0, 0, 0,
608
21
        llvm::DINode::FlagZero, nullptr, llvm::DINodeArray());
609
21
610
21
    DBuilder.replaceArrays(
611
21
        ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
612
21
                   ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0,
613
21
                   llvm::DINode::FlagZero, ISATy)));
614
21
    return ObjTy;
615
21
  }
616
47
  case BuiltinType::ObjCSel: {
617
47
    if (!SelTy)
618
47
      SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
619
47
                                         "objc_selector", TheCU,
620
47
                                         getOrCreateMainFile(), 0);
621
47
    return SelTy;
622
21
  }
623
21
624
21
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
625
0
  case BuiltinType::Id: \
626
0
    return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
627
0
                                    SingletonId);
628
47
#include 
"clang/Basic/OpenCLImageTypes.def"47
629
0
  case BuiltinType::OCLSampler:
630
0
    return getOrCreateStructPtrType("opencl_sampler_t",
631
0
                                    OCLSamplerDITy);
632
0
  case BuiltinType::OCLEvent:
633
0
    return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
634
0
  case BuiltinType::OCLClkEvent:
635
0
    return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
636
0
  case BuiltinType::OCLQueue:
637
0
    return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
638
0
  case BuiltinType::OCLReserveID:
639
0
    return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
640
21
641
12
  case BuiltinType::UChar:
642
12
  case BuiltinType::Char_U:
643
12
    Encoding = llvm::dwarf::DW_ATE_unsigned_char;
644
12
    break;
645
71
  case BuiltinType::Char_S:
646
71
  case BuiltinType::SChar:
647
71
    Encoding = llvm::dwarf::DW_ATE_signed_char;
648
71
    break;
649
1
  case BuiltinType::Char16:
650
1
  case BuiltinType::Char32:
651
1
    Encoding = llvm::dwarf::DW_ATE_UTF;
652
1
    break;
653
73
  case BuiltinType::UShort:
654
73
  case BuiltinType::UInt:
655
73
  case BuiltinType::UInt128:
656
73
  case BuiltinType::ULong:
657
73
  case BuiltinType::WChar_U:
658
73
  case BuiltinType::ULongLong:
659
73
    Encoding = llvm::dwarf::DW_ATE_unsigned;
660
73
    break;
661
340
  case BuiltinType::Short:
662
340
  case BuiltinType::Int:
663
340
  case BuiltinType::Int128:
664
340
  case BuiltinType::Long:
665
340
  case BuiltinType::WChar_S:
666
340
  case BuiltinType::LongLong:
667
340
    Encoding = llvm::dwarf::DW_ATE_signed;
668
340
    break;
669
22
  case BuiltinType::Bool:
670
22
    Encoding = llvm::dwarf::DW_ATE_boolean;
671
22
    break;
672
57
  case BuiltinType::Half:
673
57
  case BuiltinType::Float:
674
57
  case BuiltinType::LongDouble:
675
57
  case BuiltinType::Float16:
676
57
  case BuiltinType::Float128:
677
57
  case BuiltinType::Double:
678
57
    // FIXME: For targets where long double and __float128 have the same size,
679
57
    // they are currently indistinguishable in the debugger without some
680
57
    // special treatment. However, there is currently no consensus on encoding
681
57
    // and this should be updated once a DWARF encoding exists for distinct
682
57
    // floating point types of the same size.
683
57
    Encoding = llvm::dwarf::DW_ATE_float;
684
57
    break;
685
576
  }
686
576
687
576
  switch (BT->getKind()) {
688
13
  case BuiltinType::Long:
689
13
    BTName = "long int";
690
13
    break;
691
8
  case BuiltinType::LongLong:
692
8
    BTName = "long long int";
693
8
    break;
694
33
  case BuiltinType::ULong:
695
33
    BTName = "long unsigned int";
696
33
    break;
697
8
  case BuiltinType::ULongLong:
698
8
    BTName = "long long unsigned int";
699
8
    break;
700
514
  default:
701
514
    BTName = BT->getName(CGM.getLangOpts());
702
514
    break;
703
576
  }
704
576
  // Bit size and offset of the type.
705
576
  uint64_t Size = CGM.getContext().getTypeSize(BT);
706
576
  return DBuilder.createBasicType(BTName, Size, Encoding);
707
576
}
708
709
2
llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
710
2
  // Bit size and offset of the type.
711
2
  llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
712
2
  if (Ty->isComplexIntegerType())
713
0
    Encoding = llvm::dwarf::DW_ATE_lo_user;
714
2
715
2
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
716
2
  return DBuilder.createBasicType("complex", Size, Encoding);
717
2
}
718
719
llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
720
312
                                               llvm::DIFile *Unit) {
721
312
  QualifierCollector Qc;
722
312
  const Type *T = Qc.strip(Ty);
723
312
724
312
  // Ignore these qualifiers for now.
725
312
  Qc.removeObjCGCAttr();
726
312
  Qc.removeAddressSpace();
727
312
  Qc.removeObjCLifetime();
728
312
729
312
  // We will create one Derived type for one qualifier and recurse to handle any
730
312
  // additional ones.
731
312
  llvm::dwarf::Tag Tag;
732
312
  if (
Qc.hasConst()312
) {
733
178
    Tag = llvm::dwarf::DW_TAG_const_type;
734
178
    Qc.removeConst();
735
312
  } else 
if (134
Qc.hasVolatile()134
) {
736
2
    Tag = llvm::dwarf::DW_TAG_volatile_type;
737
2
    Qc.removeVolatile();
738
134
  } else 
if (132
Qc.hasRestrict()132
) {
739
31
    Tag = llvm::dwarf::DW_TAG_restrict_type;
740
31
    Qc.removeRestrict();
741
132
  } else {
742
101
    assert(Qc.empty() && "Unknown type qualifier for debug info");
743
101
    return getOrCreateType(QualType(T, 0), Unit);
744
101
  }
745
211
746
211
  auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
747
211
748
211
  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
749
211
  // CVR derived types.
750
211
  return DBuilder.createQualifiedType(Tag, FromTy);
751
211
}
752
753
llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
754
141
                                      llvm::DIFile *Unit) {
755
141
756
141
  // The frontend treats 'id' as a typedef to an ObjCObjectType,
757
141
  // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
758
141
  // debug info, we want to emit 'id' in both cases.
759
141
  if (Ty->isObjCQualifiedIdType())
760
1
    return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
761
140
762
140
  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
763
140
                               Ty->getPointeeType(), Unit);
764
140
}
765
766
llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
767
834
                                      llvm::DIFile *Unit) {
768
834
  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
769
834
                               Ty->getPointeeType(), Unit);
770
834
}
771
772
/// \return whether a C++ mangling exists for the type defined by TD.
773
1.22k
static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
774
1.22k
  switch (TheCU->getSourceLanguage()) {
775
899
  case llvm::dwarf::DW_LANG_C_plus_plus:
776
899
    return true;
777
114
  case llvm::dwarf::DW_LANG_ObjC_plus_plus:
778
16
    return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
779
212
  default:
780
212
    return false;
781
0
  }
782
0
}
783
784
/// In C++ mode, types have linkage, so we can rely on the ODR and
785
/// on their mangled names, if they're external.
786
static SmallString<256> getUniqueTagTypeName(const TagType *Ty,
787
                                             CodeGenModule &CGM,
788
1.22k
                                             llvm::DICompileUnit *TheCU) {
789
1.22k
  SmallString<256> FullName;
790
1.22k
  const TagDecl *TD = Ty->getDecl();
791
1.22k
792
1.22k
  if (
!hasCXXMangling(TD, TheCU) || 1.22k
!TD->isExternallyVisible()1.01k
)
793
318
    return FullName;
794
907
795
907
  // TODO: This is using the RTTI name. Is there a better way to get
796
907
  // a unique string for a type?
797
907
  llvm::raw_svector_ostream Out(FullName);
798
907
  CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
799
907
  return FullName;
800
907
}
801
802
/// \return the approproate DWARF tag for a composite type.
803
1.08k
static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
804
1.08k
   llvm::dwarf::Tag Tag;
805
1.08k
  if (
RD->isStruct() || 1.08k
RD->isInterface()351
)
806
735
    Tag = llvm::dwarf::DW_TAG_structure_type;
807
351
  else 
if (351
RD->isUnion()351
)
808
44
    Tag = llvm::dwarf::DW_TAG_union_type;
809
307
  else {
810
307
    // FIXME: This could be a struct type giving a default visibility different
811
307
    // than C++ class type, but needs llvm metadata changes first.
812
307
    assert(RD->isClass());
813
307
    Tag = llvm::dwarf::DW_TAG_class_type;
814
307
  }
815
1.08k
  return Tag;
816
1.08k
}
817
818
llvm::DICompositeType *
819
CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
820
290
                                      llvm::DIScope *Ctx) {
821
290
  const RecordDecl *RD = Ty->getDecl();
822
290
  if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
823
3
    return cast<llvm::DICompositeType>(T);
824
287
  llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
825
287
  unsigned Line = getLineNumber(RD->getLocation());
826
287
  StringRef RDName = getClassName(RD);
827
287
828
287
  uint64_t Size = 0;
829
287
  uint32_t Align = 0;
830
287
831
287
  // Create the type.
832
287
  SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
833
287
  llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
834
287
      getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
835
287
      llvm::DINode::FlagFwdDecl, FullName);
836
287
  if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
837
1
    
if (auto *1
TSpecial1
= dyn_cast<ClassTemplateSpecializationDecl>(RD))
838
1
      DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
839
1
                             CollectCXXTemplateParams(TSpecial, DefUnit));
840
290
  ReplaceMap.emplace_back(
841
290
      std::piecewise_construct, std::make_tuple(Ty),
842
290
      std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
843
290
  return RetTy;
844
290
}
845
846
llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
847
                                                 const Type *Ty,
848
                                                 QualType PointeeTy,
849
1.09k
                                                 llvm::DIFile *Unit) {
850
1.09k
  // Bit size, align and offset of the type.
851
1.09k
  // Size is always the size of a pointer. We can't use getTypeSize here
852
1.09k
  // because that does not return the correct value for references.
853
1.09k
  unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
854
1.09k
  uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
855
1.09k
  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
856
1.09k
  Optional<unsigned> DWARFAddressSpace =
857
1.09k
      CGM.getTarget().getDWARFAddressSpace(AddressSpace);
858
1.09k
859
1.09k
  if (Tag == llvm::dwarf::DW_TAG_reference_type ||
860
983
      Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
861
124
    return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
862
124
                                        Size, Align, DWARFAddressSpace);
863
1.09k
  else
864
974
    return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
865
974
                                      Align, DWARFAddressSpace);
866
0
}
867
868
llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
869
0
                                                    llvm::DIType *&Cache) {
870
0
  if (Cache)
871
0
    return Cache;
872
0
  Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
873
0
                                     TheCU, getOrCreateMainFile(), 0);
874
0
  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
875
0
  Cache = DBuilder.createPointerType(Cache, Size);
876
0
  return Cache;
877
0
}
878
879
llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
880
19
                                      llvm::DIFile *Unit) {
881
19
  SmallVector<llvm::Metadata *, 8> EltTys;
882
19
  QualType FType;
883
19
  uint64_t FieldSize, FieldOffset;
884
19
  uint32_t FieldAlign;
885
19
  llvm::DINodeArray Elements;
886
19
887
19
  FieldOffset = 0;
888
19
  FType = CGM.getContext().UnsignedLongTy;
889
19
  EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
890
19
  EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
891
19
892
19
  Elements = DBuilder.getOrCreateArray(EltTys);
893
19
  EltTys.clear();
894
19
895
19
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
896
19
  unsigned LineNo = 0;
897
19
898
19
  auto *EltTy =
899
19
      DBuilder.createStructType(Unit, "__block_descriptor", nullptr, LineNo,
900
19
                                FieldOffset, 0, Flags, nullptr, Elements);
901
19
902
19
  // Bit size, align and offset of the type.
903
19
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
904
19
905
19
  auto *DescTy = DBuilder.createPointerType(EltTy, Size);
906
19
907
19
  FieldOffset = 0;
908
19
  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
909
19
  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
910
19
  FType = CGM.getContext().IntTy;
911
19
  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
912
19
  EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
913
19
  FType = CGM.getContext().getPointerType(Ty->getPointeeType());
914
19
  EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
915
19
916
19
  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
917
19
  FieldSize = CGM.getContext().getTypeSize(Ty);
918
19
  FieldAlign = CGM.getContext().getTypeAlign(Ty);
919
19
  EltTys.push_back(DBuilder.createMemberType(
920
19
      Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign, FieldOffset,
921
19
      llvm::DINode::FlagZero, DescTy));
922
19
923
19
  FieldOffset += FieldSize;
924
19
  Elements = DBuilder.getOrCreateArray(EltTys);
925
19
926
19
  // The __block_literal_generic structs are marked with a special
927
19
  // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
928
19
  // the debugger needs to know about. To allow type uniquing, emit
929
19
  // them without a name or a location.
930
19
  EltTy =
931
19
      DBuilder.createStructType(Unit, "", nullptr, LineNo,
932
19
                                FieldOffset, 0, Flags, nullptr, Elements);
933
19
934
19
  return DBuilder.createPointerType(EltTy, Size);
935
19
}
936
937
llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
938
3
                                      llvm::DIFile *Unit) {
939
3
  assert(Ty->isTypeAlias());
940
3
  llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
941
3
942
3
  SmallString<128> NS;
943
3
  llvm::raw_svector_ostream OS(NS);
944
3
  Ty->getTemplateName().print(OS, getPrintingPolicy(),
945
3
                              /*qualified*/ false);
946
3
947
3
  TemplateSpecializationType::PrintTemplateArgumentList(
948
3
      OS, Ty->template_arguments(), getPrintingPolicy());
949
3
950
3
  auto *AliasDecl = cast<TypeAliasTemplateDecl>(
951
3
      Ty->getTemplateName().getAsTemplateDecl())->getTemplatedDecl();
952
3
953
3
  SourceLocation Loc = AliasDecl->getLocation();
954
3
  return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
955
3
                                getLineNumber(Loc),
956
3
                                getDeclContextDescriptor(AliasDecl));
957
3
}
958
959
llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
960
299
                                      llvm::DIFile *Unit) {
961
299
  // We don't set size information, but do specify where the typedef was
962
299
  // declared.
963
299
  SourceLocation Loc = Ty->getDecl()->getLocation();
964
299
965
299
  // Typedefs are derived from some other type.
966
299
  return DBuilder.createTypedef(
967
299
      getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
968
299
      Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
969
299
      getDeclContextDescriptor(Ty->getDecl()));
970
299
}
971
972
2.51k
static unsigned getDwarfCC(CallingConv CC) {
973
2.51k
  switch (CC) {
974
2.43k
  case CC_C:
975
2.43k
    // Avoid emitting DW_AT_calling_convention if the C convention was used.
976
2.43k
    return 0;
977
2.51k
978
1
  case CC_X86StdCall:
979
1
    return llvm::dwarf::DW_CC_BORLAND_stdcall;
980
1
  case CC_X86FastCall:
981
1
    return llvm::dwarf::DW_CC_BORLAND_msfastcall;
982
70
  case CC_X86ThisCall:
983
70
    return llvm::dwarf::DW_CC_BORLAND_thiscall;
984
1
  case CC_X86VectorCall:
985
1
    return llvm::dwarf::DW_CC_LLVM_vectorcall;
986
0
  case CC_X86Pascal:
987
0
    return llvm::dwarf::DW_CC_BORLAND_pascal;
988
2.51k
989
2.51k
  // FIXME: Create new DW_CC_ codes for these calling conventions.
990
6
  case CC_Win64:
991
6
  case CC_X86_64SysV:
992
6
  case CC_AAPCS:
993
6
  case CC_AAPCS_VFP:
994
6
  case CC_IntelOclBicc:
995
6
  case CC_SpirFunction:
996
6
  case CC_OpenCLKernel:
997
6
  case CC_Swift:
998
6
  case CC_PreserveMost:
999
6
  case CC_PreserveAll:
1000
6
  case CC_X86RegCall:
1001
6
    return 0;
1002
0
  }
1003
0
  return 0;
1004
0
}
1005
1006
llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1007
893
                                      llvm::DIFile *Unit) {
1008
893
  SmallVector<llvm::Metadata *, 16> EltTys;
1009
893
1010
893
  // Add the result type at least.
1011
893
  EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
1012
893
1013
893
  // Set up remainder of arguments if there is a prototype.
1014
893
  // otherwise emit it as a variadic function.
1015
893
  if (isa<FunctionNoProtoType>(Ty))
1016
3
    EltTys.push_back(DBuilder.createUnspecifiedParameter());
1017
890
  else 
if (const auto *890
FPT890
= dyn_cast<FunctionProtoType>(Ty)) {
1018
890
    for (const QualType &ParamType : FPT->param_types())
1019
1.05k
      EltTys.push_back(getOrCreateType(ParamType, Unit));
1020
890
    if (FPT->isVariadic())
1021
5
      EltTys.push_back(DBuilder.createUnspecifiedParameter());
1022
890
  }
1023
893
1024
893
  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1025
893
  return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
1026
893
                                       getDwarfCC(Ty->getCallConv()));
1027
893
}
1028
1029
/// Convert an AccessSpecifier into the corresponding DINode flag.
1030
/// As an optimization, return 0 if the access specifier equals the
1031
/// default for the containing type.
1032
static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1033
1.78k
                                           const RecordDecl *RD) {
1034
1.78k
  AccessSpecifier Default = clang::AS_none;
1035
1.78k
  if (
RD && 1.78k
RD->isClass()1.61k
)
1036
693
    Default = clang::AS_private;
1037
1.08k
  else 
if (1.08k
RD && 1.08k
(RD->isStruct() || 926
RD->isUnion()54
))
1038
926
    Default = clang::AS_public;
1039
1.78k
1040
1.78k
  if (Access == Default)
1041
1.07k
    return llvm::DINode::FlagZero;
1042
708
1043
708
  switch (Access) {
1044
2
  case clang::AS_private:
1045
2
    return llvm::DINode::FlagPrivate;
1046
23
  case clang::AS_protected:
1047
23
    return llvm::DINode::FlagProtected;
1048
679
  case clang::AS_public:
1049
679
    return llvm::DINode::FlagPublic;
1050
4
  case clang::AS_none:
1051
4
    return llvm::DINode::FlagZero;
1052
0
  }
1053
0
  
llvm_unreachable0
("unexpected access enumerator");
1054
0
}
1055
1056
llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1057
                                              llvm::DIScope *RecordTy,
1058
14
                                              const RecordDecl *RD) {
1059
14
  StringRef Name = BitFieldDecl->getName();
1060
14
  QualType Ty = BitFieldDecl->getType();
1061
14
  SourceLocation Loc = BitFieldDecl->getLocation();
1062
14
  llvm::DIFile *VUnit = getOrCreateFile(Loc);
1063
14
  llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1064
14
1065
14
  // Get the location for the field.
1066
14
  llvm::DIFile *File = getOrCreateFile(Loc);
1067
14
  unsigned Line = getLineNumber(Loc);
1068
14
1069
14
  const CGBitFieldInfo &BitFieldInfo =
1070
14
      CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1071
14
  uint64_t SizeInBits = BitFieldInfo.Size;
1072
14
  assert(SizeInBits > 0 && "found named 0-width bitfield");
1073
14
  uint64_t StorageOffsetInBits =
1074
14
      CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1075
14
  uint64_t Offset = BitFieldInfo.Offset;
1076
14
  // The bit offsets for big endian machines are reversed for big
1077
14
  // endian target, compensate for that as the DIDerivedType requires
1078
14
  // un-reversed offsets.
1079
14
  if (CGM.getDataLayout().isBigEndian())
1080
2
    Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1081
14
  uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1082
14
  llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1083
14
  return DBuilder.createBitFieldMemberType(
1084
14
      RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1085
14
      Flags, DebugType);
1086
14
}
1087
1088
llvm::DIType *
1089
CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
1090
                             AccessSpecifier AS, uint64_t offsetInBits,
1091
                             uint32_t AlignInBits, llvm::DIFile *tunit,
1092
665
                             llvm::DIScope *scope, const RecordDecl *RD) {
1093
665
  llvm::DIType *debugType = getOrCreateType(type, tunit);
1094
665
1095
665
  // Get the location for the field.
1096
665
  llvm::DIFile *file = getOrCreateFile(loc);
1097
665
  unsigned line = getLineNumber(loc);
1098
665
1099
665
  uint64_t SizeInBits = 0;
1100
665
  auto Align = AlignInBits;
1101
665
  if (
!type->isIncompleteArrayType()665
) {
1102
662
    TypeInfo TI = CGM.getContext().getTypeInfo(type);
1103
662
    SizeInBits = TI.Width;
1104
662
    if (!Align)
1105
662
      Align = getTypeAlignIfRequired(type, CGM.getContext());
1106
662
  }
1107
665
1108
665
  llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1109
665
  return DBuilder.createMemberType(scope, name, file, line, SizeInBits,
1110
665
                                   Align, offsetInBits, flags, debugType);
1111
665
}
1112
1113
void CGDebugInfo::CollectRecordLambdaFields(
1114
    const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1115
11
    llvm::DIType *RecordTy) {
1116
11
  // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1117
11
  // has the name and the location of the variable so we should iterate over
1118
11
  // both concurrently.
1119
11
  const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1120
11
  RecordDecl::field_iterator Field = CXXDecl->field_begin();
1121
11
  unsigned fieldno = 0;
1122
11
  for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
1123
11
                                             E = CXXDecl->captures_end();
1124
21
       
I != E21
;
++I, ++Field, ++fieldno10
) {
1125
10
    const LambdaCapture &C = *I;
1126
10
    if (
C.capturesVariable()10
) {
1127
9
      SourceLocation Loc = C.getLocation();
1128
9
      assert(!Field->isBitField() && "lambdas don't have bitfield members!");
1129
9
      VarDecl *V = C.getCapturedVar();
1130
9
      StringRef VName = V->getName();
1131
9
      llvm::DIFile *VUnit = getOrCreateFile(Loc);
1132
9
      auto Align = getDeclAlignIfRequired(V, CGM.getContext());
1133
9
      llvm::DIType *FieldType = createFieldType(
1134
9
          VName, Field->getType(), Loc, Field->getAccess(),
1135
9
          layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
1136
9
      elements.push_back(FieldType);
1137
10
    } else 
if (1
C.capturesThis()1
) {
1138
1
      // TODO: Need to handle 'this' in some way by probably renaming the
1139
1
      // this of the lambda class and having a field member of 'this' or
1140
1
      // by using AT_object_pointer for the function and having that be
1141
1
      // used as 'this' for semantic references.
1142
1
      FieldDecl *f = *Field;
1143
1
      llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1144
1
      QualType type = f->getType();
1145
1
      llvm::DIType *fieldType = createFieldType(
1146
1
          "this", type, f->getLocation(), f->getAccess(),
1147
1
          layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1148
1
1149
1
      elements.push_back(fieldType);
1150
1
    }
1151
10
  }
1152
11
}
1153
1154
llvm::DIDerivedType *
1155
CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1156
87
                                     const RecordDecl *RD) {
1157
87
  // Create the descriptor for the static variable, with or without
1158
87
  // constant initializers.
1159
87
  Var = Var->getCanonicalDecl();
1160
87
  llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1161
87
  llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1162
87
1163
87
  unsigned LineNumber = getLineNumber(Var->getLocation());
1164
87
  StringRef VName = Var->getName();
1165
87
  llvm::Constant *C = nullptr;
1166
87
  if (
Var->getInit()87
) {
1167
28
    const APValue *Value = Var->evaluateValue();
1168
28
    if (
Value28
) {
1169
28
      if (Value->isInt())
1170
25
        C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1171
28
      if (Value->isFloat())
1172
3
        C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1173
28
    }
1174
28
  }
1175
87
1176
87
  llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
1177
87
  auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
1178
87
  llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1179
87
      RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
1180
87
  StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1181
87
  return GV;
1182
87
}
1183
1184
void CGDebugInfo::CollectRecordNormalField(
1185
    const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1186
    SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1187
522
    const RecordDecl *RD) {
1188
522
  StringRef name = field->getName();
1189
522
  QualType type = field->getType();
1190
522
1191
522
  // Ignore unnamed fields unless they're anonymous structs/unions.
1192
522
  if (
name.empty() && 522
!type->isRecordType()21
)
1193
14
    return;
1194
508
1195
508
  llvm::DIType *FieldType;
1196
508
  if (
field->isBitField()508
) {
1197
14
    FieldType = createBitFieldType(field, RecordTy, RD);
1198
508
  } else {
1199
494
    auto Align = getDeclAlignIfRequired(field, CGM.getContext());
1200
494
    FieldType =
1201
494
        createFieldType(name, type, field->getLocation(), field->getAccess(),
1202
494
                        OffsetInBits, Align, tunit, RecordTy, RD);
1203
494
  }
1204
522
1205
522
  elements.push_back(FieldType);
1206
522
}
1207
1208
void CGDebugInfo::CollectRecordNestedType(
1209
6
    const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1210
6
  QualType Ty = CGM.getContext().getTypeDeclType(TD);
1211
6
  // Injected class names are not considered nested records.
1212
6
  if (isa<InjectedClassNameType>(Ty))
1213
1
    return;
1214
5
  SourceLocation Loc = TD->getLocation();
1215
5
  llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1216
5
  elements.push_back(nestedType);
1217
5
}
1218
1219
void CGDebugInfo::CollectRecordFields(
1220
    const RecordDecl *record, llvm::DIFile *tunit,
1221
    SmallVectorImpl<llvm::Metadata *> &elements,
1222
804
    llvm::DICompositeType *RecordTy) {
1223
804
  const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1224
804
1225
804
  if (
CXXDecl && 804
CXXDecl->isLambda()678
)
1226
11
    CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1227
793
  else {
1228
793
    const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1229
793
1230
793
    // Debug info for nested types is included in the member list only for
1231
793
    // CodeView.
1232
793
    bool IncludeNestedTypes = CGM.getCodeGenOpts().EmitCodeView;
1233
793
1234
793
    // Field number for non-static fields.
1235
793
    unsigned fieldNo = 0;
1236
793
1237
793
    // Static and non-static members should appear in the same order as
1238
793
    // the corresponding declarations in the source program.
1239
793
    for (const auto *I : record->decls())
1240
3.35k
      
if (const auto *3.35k
V3.35k
= dyn_cast<VarDecl>(I)) {
1241
67
        if (V->hasAttr<NoDebugAttr>())
1242
2
          continue;
1243
65
        // Reuse the existing static member declaration if one exists
1244
65
        auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1245
65
        if (
MI != StaticDataMemberCache.end()65
) {
1246
0
          assert(MI->second &&
1247
0
                 "Static data member declaration should still exist");
1248
0
          elements.push_back(MI->second);
1249
65
        } else {
1250
65
          auto Field = CreateRecordStaticField(V, RecordTy, record);
1251
65
          elements.push_back(Field);
1252
65
        }
1253
3.35k
      } else 
if (const auto *3.28k
field3.28k
= dyn_cast<FieldDecl>(I)) {
1254
522
        CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1255
522
                                 elements, RecordTy, record);
1256
522
1257
522
        // Bump field number for next field.
1258
522
        ++fieldNo;
1259
3.28k
      } else 
if (2.76k
IncludeNestedTypes2.76k
) {
1260
155
        if (const auto *nestedType = dyn_cast<TypeDecl>(I))
1261
36
          
if (36
!nestedType->isImplicit() &&
1262
6
              nestedType->getDeclContext() == record)
1263
6
            CollectRecordNestedType(nestedType, elements);
1264
3.35k
      }
1265
793
  }
1266
804
}
1267
1268
llvm::DISubroutineType *
1269
CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1270
1.52k
                                   llvm::DIFile *Unit) {
1271
1.52k
  const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1272
1.52k
  if (Method->isStatic())
1273
56
    return cast_or_null<llvm::DISubroutineType>(
1274
56
        getOrCreateType(QualType(Func, 0), Unit));
1275
1.46k
  return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
1276
1.46k
                                       Func, Unit);
1277
1.46k
}
1278
1279
llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1280
1.48k
    QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
1281
1.48k
  // Add "this" pointer.
1282
1.48k
  llvm::DITypeRefArray Args(
1283
1.48k
      cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
1284
1.48k
          ->getTypeArray());
1285
1.48k
  assert(Args.size() && "Invalid number of arguments!");
1286
1.48k
1287
1.48k
  SmallVector<llvm::Metadata *, 16> Elts;
1288
1.48k
1289
1.48k
  // First element is always return type. For 'void' functions it is NULL.
1290
1.48k
  Elts.push_back(Args[0]);
1291
1.48k
1292
1.48k
  // "this" pointer is always first argument.
1293
1.48k
  const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1294
1.48k
  if (
isa<ClassTemplateSpecializationDecl>(RD)1.48k
) {
1295
425
    // Create pointer type directly in this case.
1296
425
    const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1297
425
    QualType PointeeTy = ThisPtrTy->getPointeeType();
1298
425
    unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1299
425
    uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1300
425
    auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
1301
425
    llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1302
425
    llvm::DIType *ThisPtrType =
1303
425
        DBuilder.createPointerType(PointeeType, Size, Align);
1304
425
    TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1305
425
    // TODO: This and the artificial type below are misleading, the
1306
425
    // types aren't artificial the argument is, but the current
1307
425
    // metadata doesn't represent that.
1308
425
    ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1309
425
    Elts.push_back(ThisPtrType);
1310
1.48k
  } else {
1311
1.06k
    llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1312
1.06k
    TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1313
1.06k
    ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1314
1.06k
    Elts.push_back(ThisPtrType);
1315
1.06k
  }
1316
1.48k
1317
1.48k
  // Copy rest of the arguments.
1318
1.77k
  for (unsigned i = 1, e = Args.size(); 
i != e1.77k
;
++i289
)
1319
289
    Elts.push_back(Args[i]);
1320
1.48k
1321
1.48k
  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1322
1.48k
1323
1.48k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1324
1.48k
  if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1325
2
    Flags |= llvm::DINode::FlagLValueReference;
1326
1.48k
  if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1327
2
    Flags |= llvm::DINode::FlagRValueReference;
1328
1.48k
1329
1.48k
  return DBuilder.createSubroutineType(EltTypeArray, Flags,
1330
1.48k
                                       getDwarfCC(Func->getCallConv()));
1331
1.48k
}
1332
1333
/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1334
/// inside a function.
1335
640
static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1336
640
  if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1337
2
    return isFunctionLocalClass(NRD);
1338
638
  
if (638
isa<FunctionDecl>(RD->getDeclContext())638
)
1339
9
    return true;
1340
629
  return false;
1341
629
}
1342
1343
llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1344
908
    const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1345
908
  bool IsCtorOrDtor =
1346
705
      isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1347
908
1348
908
  StringRef MethodName = getFunctionName(Method);
1349
908
  llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
1350
908
1351
908
  // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1352
908
  // make sense to give a single ctor/dtor a linkage name.
1353
908
  StringRef MethodLinkageName;
1354
908
  // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1355
908
  // property to use here. It may've been intended to model "is non-external
1356
908
  // type" but misses cases of non-function-local but non-external classes such
1357
908
  // as those in anonymous namespaces as well as the reverse - external types
1358
908
  // that are function local, such as those in (non-local) inline functions.
1359
908
  if (
!IsCtorOrDtor && 908
!isFunctionLocalClass(Method->getParent())638
)
1360
629
    MethodLinkageName = CGM.getMangledName(Method);
1361
908
1362
908
  // Get the location for the method.
1363
908
  llvm::DIFile *MethodDefUnit = nullptr;
1364
908
  unsigned MethodLine = 0;
1365
908
  if (
!Method->isImplicit()908
) {
1366
834
    MethodDefUnit = getOrCreateFile(Method->getLocation());
1367
834
    MethodLine = getLineNumber(Method->getLocation());
1368
834
  }
1369
908
1370
908
  // Collect virtual method info.
1371
908
  llvm::DIType *ContainingType = nullptr;
1372
908
  unsigned Virtuality = 0;
1373
908
  unsigned VIndex = 0;
1374
908
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1375
908
  int ThisAdjustment = 0;
1376
908
1377
908
  if (
Method->isVirtual()908
) {
1378
353
    if (Method->isPure())
1379
2
      Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1380
353
    else
1381
351
      Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1382
353
1383
353
    if (
CGM.getTarget().getCXXABI().isItaniumFamily()353
) {
1384
344
      // It doesn't make sense to give a virtual destructor a vtable index,
1385
344
      // since a single destructor has two entries in the vtable.
1386
344
      if (!isa<CXXDestructorDecl>(Method))
1387
317
        VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1388
353
    } else {
1389
9
      // Emit MS ABI vftable information.  There is only one entry for the
1390
9
      // deleting dtor.
1391
9
      const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1392
9
      GlobalDecl GD = DD ? 
GlobalDecl(DD, Dtor_Deleting)2
:
GlobalDecl(Method)7
;
1393
9
      MicrosoftVTableContext::MethodVFTableLocation ML =
1394
9
          CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1395
9
      VIndex = ML.Index;
1396
9
1397
9
      // CodeView only records the vftable offset in the class that introduces
1398
9
      // the virtual method. This is possible because, unlike Itanium, the MS
1399
9
      // C++ ABI does not include all virtual methods from non-primary bases in
1400
9
      // the vtable for the most derived class. For example, if C inherits from
1401
9
      // A and B, C's primary vftable will not include B's virtual methods.
1402
9
      if (Method->begin_overridden_methods() == Method->end_overridden_methods())
1403
9
        Flags |= llvm::DINode::FlagIntroducedVirtual;
1404
9
1405
9
      // The 'this' adjustment accounts for both the virtual and non-virtual
1406
9
      // portions of the adjustment. Presumably the debugger only uses it when
1407
9
      // it knows the dynamic type of an object.
1408
9
      ThisAdjustment = CGM.getCXXABI()
1409
9
                           .getVirtualFunctionPrologueThisAdjustment(GD)
1410
9
                           .getQuantity();
1411
9
    }
1412
353
    ContainingType = RecordTy;
1413
353
  }
1414
908
1415
908
  if (Method->isStatic())
1416
33
    Flags |= llvm::DINode::FlagStaticMember;
1417
908
  if (Method->isImplicit())
1418
74
    Flags |= llvm::DINode::FlagArtificial;
1419
908
  Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1420
908
  if (const auto *
CXXC908
= dyn_cast<CXXConstructorDecl>(Method)) {
1421
203
    if (CXXC->isExplicit())
1422
2
      Flags |= llvm::DINode::FlagExplicit;
1423
908
  } else 
if (const auto *705
CXXC705
= dyn_cast<CXXConversionDecl>(Method)) {
1424
3
    if (CXXC->isExplicit())
1425
0
      Flags |= llvm::DINode::FlagExplicit;
1426
705
  }
1427
908
  if (Method->hasPrototype())
1428
908
    Flags |= llvm::DINode::FlagPrototyped;
1429
908
  if (Method->getRefQualifier() == RQ_LValue)
1430
1
    Flags |= llvm::DINode::FlagLValueReference;
1431
908
  if (Method->getRefQualifier() == RQ_RValue)
1432
1
    Flags |= llvm::DINode::FlagRValueReference;
1433
908
1434
908
  llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1435
908
  llvm::DISubprogram *SP = DBuilder.createMethod(
1436
908
      RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1437
908
      MethodTy, /*isLocalToUnit=*/false, /*isDefinition=*/false, Virtuality,
1438
908
      VIndex, ThisAdjustment, ContainingType, Flags, CGM.getLangOpts().Optimize,
1439
908
      TParamsArray.get());
1440
908
1441
908
  SPCache[Method->getCanonicalDecl()].reset(SP);
1442
908
1443
908
  return SP;
1444
908
}
1445
1446
void CGDebugInfo::CollectCXXMemberFunctions(
1447
    const CXXRecordDecl *RD, llvm::DIFile *Unit,
1448
678
    SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1449
678
1450
678
  // Since we want more than just the individual member decls if we
1451
678
  // have templated functions iterate over every declaration to gather
1452
678
  // the functions.
1453
3.13k
  for (const auto *I : RD->decls()) {
1454
3.13k
    const auto *Method = dyn_cast<CXXMethodDecl>(I);
1455
3.13k
    // If the member is implicit, don't add it to the member list. This avoids
1456
3.13k
    // the member being added to type units by LLVM, while still allowing it
1457
3.13k
    // to be emitted into the type declaration/reference inside the compile
1458
3.13k
    // unit.
1459
3.13k
    // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
1460
3.13k
    // FIXME: Handle Using(Shadow?)Decls here to create
1461
3.13k
    // DW_TAG_imported_declarations inside the class for base decls brought into
1462
3.13k
    // derived classes. GDB doesn't seem to notice/leverage these when I tried
1463
3.13k
    // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1464
3.13k
    // referenced)
1465
3.13k
    if (
!Method || 3.13k
Method->isImplicit()1.77k
||
Method->hasAttr<NoDebugAttr>()687
)
1466
2.45k
      continue;
1467
686
1468
686
    
if (686
Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType()686
)
1469
1
      continue;
1470
685
1471
685
    // Reuse the existing member function declaration if it exists.
1472
685
    // It may be associated with the declaration of the type & should be
1473
685
    // reused as we're building the definition.
1474
685
    //
1475
685
    // This situation can arise in the vtable-based debug info reduction where
1476
685
    // implicit members are emitted in a non-vtable TU.
1477
685
    auto MI = SPCache.find(Method->getCanonicalDecl());
1478
685
    EltTys.push_back(MI == SPCache.end()
1479
662
                         ? CreateCXXMemberFunction(Method, Unit, RecordTy)
1480
23
                         : static_cast<llvm::Metadata *>(MI->second));
1481
3.13k
  }
1482
678
}
1483
1484
void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1485
                                  SmallVectorImpl<llvm::Metadata *> &EltTys,
1486
678
                                  llvm::DIType *RecordTy) {
1487
678
  llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
1488
678
  CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1489
678
                     llvm::DINode::FlagZero);
1490
678
1491
678
  // If we are generating CodeView debug info, we also need to emit records for
1492
678
  // indirect virtual base classes.
1493
678
  if (
CGM.getCodeGenOpts().EmitCodeView678
) {
1494
32
    CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1495
32
                       llvm::DINode::FlagIndirectVirtualBase);
1496
32
  }
1497
678
}
1498
1499
void CGDebugInfo::CollectCXXBasesAux(
1500
    const CXXRecordDecl *RD, llvm::DIFile *Unit,
1501
    SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
1502
    const CXXRecordDecl::base_class_const_range &Bases,
1503
    llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
1504
710
    llvm::DINode::DIFlags StartingFlags) {
1505
710
  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1506
109
  for (const auto &BI : Bases) {
1507
109
    const auto *Base =
1508
109
        cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
1509
109
    if (!SeenTypes.insert(Base).second)
1510
3
      continue;
1511
106
    auto *BaseTy = getOrCreateType(BI.getType(), Unit);
1512
106
    llvm::DINode::DIFlags BFlags = StartingFlags;
1513
106
    uint64_t BaseOffset;
1514
106
1515
106
    if (
BI.isVirtual()106
) {
1516
16
      if (
CGM.getTarget().getCXXABI().isItaniumFamily()16
) {
1517
11
        // virtual base offset offset is -ve. The code generator emits dwarf
1518
11
        // expression where it expects +ve number.
1519
11
        BaseOffset = 0 - CGM.getItaniumVTableContext()
1520
11
                             .getVirtualBaseOffsetOffset(RD, Base)
1521
11
                             .getQuantity();
1522
16
      } else {
1523
5
        // In the MS ABI, store the vbtable offset, which is analogous to the
1524
5
        // vbase offset offset in Itanium.
1525
5
        BaseOffset =
1526
5
            4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1527
5
      }
1528
16
      BFlags |= llvm::DINode::FlagVirtual;
1529
16
    } else
1530
90
      BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1531
109
    // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1532
109
    // BI->isVirtual() and bits when not.
1533
109
1534
109
    BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1535
109
    llvm::DIType *DTy =
1536
109
        DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset, BFlags);
1537
109
    EltTys.push_back(DTy);
1538
109
  }
1539
710
}
1540
1541
llvm::DINodeArray
1542
CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1543
                                   ArrayRef<TemplateArgument> TAList,
1544
594
                                   llvm::DIFile *Unit) {
1545
594
  SmallVector<llvm::Metadata *, 16> TemplateParams;
1546
1.31k
  for (unsigned i = 0, e = TAList.size(); 
i != e1.31k
;
++i721
) {
1547
721
    const TemplateArgument &TA = TAList[i];
1548
721
    StringRef Name;
1549
721
    if (TPList)
1550
714
      Name = TPList->getParam(i)->getName();
1551
721
    switch (TA.getKind()) {
1552
311
    case TemplateArgument::Type: {
1553
311
      llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
1554
311
      TemplateParams.push_back(
1555
311
          DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
1556
311
    } break;
1557
355
    case TemplateArgument::Integral: {
1558
355
      llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
1559
355
      TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1560
355
          TheCU, Name, TTy,
1561
355
          llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
1562
355
    } break;
1563
10
    case TemplateArgument::Declaration: {
1564
10
      const ValueDecl *D = TA.getAsDecl();
1565
10
      QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
1566
10
      llvm::DIType *TTy = getOrCreateType(T, Unit);
1567
10
      llvm::Constant *V = nullptr;
1568
10
      const CXXMethodDecl *MD;
1569
10
      // Variable pointer template parameters have a value that is the address
1570
10
      // of the variable.
1571
10
      if (const auto *VD = dyn_cast<VarDecl>(D))
1572
4
        V = CGM.GetAddrOfGlobalVar(VD);
1573
10
      // Member function pointers have special support for building them, though
1574
10
      // this is currently unsupported in LLVM CodeGen.
1575
6
      else 
if (6
(MD = dyn_cast<CXXMethodDecl>(D)) && 6
MD->isInstance()2
)
1576
1
        V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1577
5
      else 
if (const auto *5
FD5
= dyn_cast<FunctionDecl>(D))
1578
3
        V = CGM.GetAddrOfFunction(FD);
1579
5
      // Member data pointers have special handling too to compute the fixed
1580
5
      // offset within the object.
1581
2
      else 
if (const auto *2
MPT2
= dyn_cast<MemberPointerType>(T.getTypePtr())) {
1582
2
        // These five lines (& possibly the above member function pointer
1583
2
        // handling) might be able to be refactored to use similar code in
1584
2
        // CodeGenModule::getMemberPointerConstant
1585
2
        uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1586
2
        CharUnits chars =
1587
2
            CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1588
2
        V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1589
2
      }
1590
10
      TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1591
10
          TheCU, Name, TTy,
1592
10
          cast_or_null<llvm::Constant>(V->stripPointerCasts())));
1593
10
    } break;
1594
4
    case TemplateArgument::NullPtr: {
1595
4
      QualType T = TA.getNullPtrType();
1596
4
      llvm::DIType *TTy = getOrCreateType(T, Unit);
1597
4
      llvm::Constant *V = nullptr;
1598
4
      // Special case member data pointer null values since they're actually -1
1599
4
      // instead of zero.
1600
4
      if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
1601
4
        // But treat member function pointers as simple zero integers because
1602
4
        // it's easier than having a special case in LLVM's CodeGen. If LLVM
1603
4
        // CodeGen grows handling for values of non-null member function
1604
4
        // pointers then perhaps we could remove this special case and rely on
1605
4
        // EmitNullMemberPointer for member function pointers.
1606
2
        
if (2
MPT->isMemberDataPointer()2
)
1607
1
          V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1608
4
      if (!V)
1609
3
        V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1610
4
      TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1611
4
          TheCU, Name, TTy, V));
1612
4
    } break;
1613
31
    case TemplateArgument::Template:
1614
31
      TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
1615
31
          TheCU, Name, nullptr,
1616
31
          TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
1617
31
      break;
1618
6
    case TemplateArgument::Pack:
1619
6
      TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1620
6
          TheCU, Name, nullptr,
1621
6
          CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1622
6
      break;
1623
4
    case TemplateArgument::Expression: {
1624
4
      const Expr *E = TA.getAsExpr();
1625
4
      QualType T = E->getType();
1626
4
      if (E->isGLValue())
1627
2
        T = CGM.getContext().getLValueReferenceType(T);
1628
4
      llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
1629
4
      assert(V && "Expression in template argument isn't constant");
1630
4
      llvm::DIType *TTy = getOrCreateType(T, Unit);
1631
4
      TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1632
4
          TheCU, Name, TTy, V->stripPointerCasts()));
1633
4
    } break;
1634
721
    // And the following should never occur:
1635
0
    case TemplateArgument::TemplateExpansion:
1636
0
    case TemplateArgument::Null:
1637
0
      llvm_unreachable(
1638
721
          "These argument types shouldn't exist in concrete types");
1639
721
    }
1640
721
  }
1641
594
  return DBuilder.getOrCreateArray(TemplateParams);
1642
594
}
1643
1644
llvm::DINodeArray
1645
CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
1646
2.09k
                                           llvm::DIFile *Unit) {
1647
2.09k
  if (FD->getTemplatedKind() ==
1648
2.09k
      FunctionDecl::TK_FunctionTemplateSpecialization) {
1649
304
    const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1650
304
                                             ->getTemplate()
1651
304
                                             ->getTemplateParameters();
1652
304
    return CollectTemplateParams(
1653
304
        TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1654
304
  }
1655
1.79k
  return llvm::DINodeArray();
1656
1.79k
}
1657
1658
llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1659
284
    const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
1660
284
  // Always get the full list of parameters, not just the ones from
1661
284
  // the specialization.
1662
284
  TemplateParameterList *TPList =
1663
284
      TSpecial->getSpecializedTemplate()->getTemplateParameters();
1664
284
  const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
1665
284
  return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1666
284
}
1667
1668
43
llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
1669
43
  if (VTablePtrType)
1670
17
    return VTablePtrType;
1671
26
1672
26
  ASTContext &Context = CGM.getContext();
1673
26
1674
26
  /* Function type */
1675
26
  llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
1676
26
  llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
1677
26
  llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
1678
26
  unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1679
26
  unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
1680
26
  Optional<unsigned> DWARFAddressSpace =
1681
26
      CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
1682
26
1683
26
  llvm::DIType *vtbl_ptr_type =
1684
26
      DBuilder.createPointerType(SubTy, Size, 0, DWARFAddressSpace,
1685
26
                                 "__vtbl_ptr_type");
1686
26
  VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1687
26
  return VTablePtrType;
1688
26
}
1689
1690
49
StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1691
49
  // Copy the gdb compatible name on the side and use its reference.
1692
49
  return internString("_vptr$", RD->getNameAsString());
1693
49
}
1694
1695
void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1696
                                    SmallVectorImpl<llvm::Metadata *> &EltTys,
1697
678
                                    llvm::DICompositeType *RecordTy) {
1698
678
  // If this class is not dynamic then there is not any vtable info to collect.
1699
678
  if (!RD->isDynamicClass())
1700
608
    return;
1701
70
1702
70
  // Don't emit any vtable shape or vptr info if this class doesn't have an
1703
70
  // extendable vfptr. This can happen if the class doesn't have virtual
1704
70
  // methods, or in the MS ABI if those virtual methods only come from virtually
1705
70
  // inherited bases.
1706
70
  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1707
70
  if (!RL.hasExtendableVFPtr())
1708
3
    return;
1709
67
1710
67
  // CodeView needs to know how large the vtable of every dynamic class is, so
1711
67
  // emit a special named pointer type into the element list. The vptr type
1712
67
  // points to this type as well.
1713
67
  llvm::DIType *VPtrTy = nullptr;
1714
67
  bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
1715
9
                         CGM.getTarget().getCXXABI().isMicrosoft();
1716
67
  if (
NeedVTableShape67
) {
1717
9
    uint64_t PtrWidth =
1718
9
        CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1719
9
    const VTableLayout &VFTLayout =
1720
9
        CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
1721
9
    unsigned VSlotCount =
1722
9
        VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
1723
9
    unsigned VTableWidth = PtrWidth * VSlotCount;
1724
9
    unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
1725
9
    Optional<unsigned> DWARFAddressSpace =
1726
9
        CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
1727
9
1728
9
    // Create a very wide void* type and insert it directly in the element list.
1729
9
    llvm::DIType *VTableType =
1730
9
        DBuilder.createPointerType(nullptr, VTableWidth, 0, DWARFAddressSpace,
1731
9
                                   "__vtbl_ptr_type");
1732
9
    EltTys.push_back(VTableType);
1733
9
1734
9
    // The vptr is a pointer to this special vtable type.
1735
9
    VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
1736
9
  }
1737
67
1738
67
  // If there is a primary base then the artificial vptr member lives there.
1739
67
  if (RL.getPrimaryBase())
1740
18
    return;
1741
49
1742
49
  
if (49
!VPtrTy49
)
1743
43
    VPtrTy = getOrCreateVTablePtrType(Unit);
1744
678
1745
678
  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1746
678
  llvm::DIType *VPtrMember = DBuilder.createMemberType(
1747
678
      Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
1748
678
      llvm::DINode::FlagArtificial, VPtrTy);
1749
678
  EltTys.push_back(VPtrMember);
1750
678
}
1751
1752
llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
1753
0
                                                 SourceLocation Loc) {
1754
0
  assert(DebugKind >= codegenoptions::LimitedDebugInfo);
1755
0
  llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
1756
0
  return T;
1757
0
}
1758
1759
llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
1760
59
                                                    SourceLocation Loc) {
1761
59
  return getOrCreateStandaloneType(D, Loc);
1762
59
}
1763
1764
llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
1765
235
                                                     SourceLocation Loc) {
1766
235
  assert(DebugKind >= codegenoptions::LimitedDebugInfo);
1767
235
  assert(!D.isNull() && "null type");
1768
235
  llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
1769
235
  assert(T && "could not create debug info for type");
1770
235
1771
235
  RetainedTypes.push_back(D.getAsOpaquePtr());
1772
235
  return T;
1773
235
}
1774
1775
9.73k
void CGDebugInfo::completeType(const EnumDecl *ED) {
1776
9.73k
  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
1777
5.79k
    return;
1778
3.94k
  QualType Ty = CGM.getContext().getEnumType(ED);
1779
3.94k
  void *TyPtr = Ty.getAsOpaquePtr();
1780
3.94k
  auto I = TypeCache.find(TyPtr);
1781
3.94k
  if (
I == TypeCache.end() || 3.94k
!cast<llvm::DIType>(I->second)->isForwardDecl()3
)
1782
3.94k
    return;
1783
1
  llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
1784
1
  assert(!Res->isForwardDecl());
1785
1
  TypeCache[TyPtr].reset(Res);
1786
1
}
1787
1788
71.1k
void CGDebugInfo::completeType(const RecordDecl *RD) {
1789
71.1k
  if (DebugKind > codegenoptions::LimitedDebugInfo ||
1790
68.0k
      !CGM.getLangOpts().CPlusPlus)
1791
3.19k
    completeRequiredType(RD);
1792
71.1k
}
1793
1794
/// Return true if the class or any of its methods are marked dllimport.
1795
894
static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
1796
894
  if (RD->hasAttr<DLLImportAttr>())
1797
4
    return true;
1798
890
  for (const CXXMethodDecl *MD : RD->methods())
1799
5.57k
    
if (5.57k
MD->hasAttr<DLLImportAttr>()5.57k
)
1800
2
      return true;
1801
888
  return false;
1802
888
}
1803
1804
/// Does a type definition exist in an imported clang module?
1805
302
static bool isDefinedInClangModule(const RecordDecl *RD) {
1806
302
  // Only definitions that where imported from an AST file come from a module.
1807
302
  if (
!RD || 302
!RD->isFromASTFile()282
)
1808
180
    return false;
1809
122
  // Anonymous entities cannot be addressed. Treat them as not from module.
1810
122
  
if (122
!RD->isExternallyVisible() && 122
RD->getName().empty()24
)
1811
20
    return false;
1812
102
  
if (auto *102
CXXDecl102
= dyn_cast<CXXRecordDecl>(RD)) {
1813
84
    if (!CXXDecl->isCompleteDefinition())
1814
1
      return false;
1815
83
    auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
1816
83
    if (
TemplateKind != TSK_Undeclared83
) {
1817
55
      // This is a template, check the origin of the first member.
1818
55
      if (CXXDecl->field_begin() == CXXDecl->field_end())
1819
21
        return TemplateKind == TSK_ExplicitInstantiationDeclaration;
1820
34
      
if (34
!CXXDecl->field_begin()->isFromASTFile()34
)
1821
24
        return false;
1822
56
    }
1823
84
  }
1824
56
  return true;
1825
56
}
1826
1827
714
void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1828
714
  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1829
714
    
if (714
CXXRD->isDynamicClass() &&
1830
699
        CGM.getVTableLinkage(CXXRD) ==
1831
699
            llvm::GlobalValue::AvailableExternallyLinkage &&
1832
2
        !isClassOrMethodDLLImport(CXXRD))
1833
1
      return;
1834
713
1835
713
  
if (713
DebugTypeExtRefs && 713
isDefinedInClangModule(RD->getDefinition())5
)
1836
2
    return;
1837
711
1838
711
  completeClass(RD);
1839
711
}
1840
1841
711
void CGDebugInfo::completeClass(const RecordDecl *RD) {
1842
711
  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
1843
598
    return;
1844
113
  QualType Ty = CGM.getContext().getRecordType(RD);
1845
113
  void *TyPtr = Ty.getAsOpaquePtr();
1846
113
  auto I = TypeCache.find(TyPtr);
1847
113
  if (
I != TypeCache.end() && 113
!cast<llvm::DIType>(I->second)->isForwardDecl()108
)
1848
45
    return;
1849
68
  llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1850
68
  assert(!Res->isForwardDecl());
1851
68
  TypeCache[TyPtr].reset(Res);
1852
68
}
1853
1854
static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1855
22
                                        CXXRecordDecl::method_iterator End) {
1856
22
  for (CXXMethodDecl *MD : llvm::make_range(I, End))
1857
29
    
if (FunctionDecl *29
Tmpl29
= MD->getInstantiatedFromMemberFunction())
1858
15
      
if (15
!Tmpl->isImplicit() && 15
Tmpl->isThisDeclarationADefinition()15
&&
1859
5
          !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
1860
4
        return true;
1861
18
  return false;
1862
18
}
1863
1864
static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
1865
                                 bool DebugTypeExtRefs, const RecordDecl *RD,
1866
48.0k
                                 const LangOptions &LangOpts) {
1867
48.0k
  if (
DebugTypeExtRefs && 48.0k
isDefinedInClangModule(RD->getDefinition())297
)
1868
56
    return true;
1869
47.9k
1870
47.9k
  
if (auto *47.9k
ES47.9k
= RD->getASTContext().getExternalSource())
1871
294
    
if (294
ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always294
)
1872
5
      return true;
1873
47.9k
1874
47.9k
  
if (47.9k
DebugKind > codegenoptions::LimitedDebugInfo47.9k
)
1875
4.89k
    return false;
1876
43.0k
1877
43.0k
  
if (43.0k
!LangOpts.CPlusPlus43.0k
)
1878
301
    return false;
1879
42.7k
1880
42.7k
  
if (42.7k
!RD->isCompleteDefinitionRequired()42.7k
)
1881
117
    return true;
1882
42.6k
1883
42.6k
  const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1884
42.6k
1885
42.6k
  if (!CXXDecl)
1886
0
    return false;
1887
42.6k
1888
42.6k
  // Only emit complete debug info for a dynamic class when its vtable is
1889
42.6k
  // emitted.  However, Microsoft debuggers don't resolve type information
1890
42.6k
  // across DLL boundaries, so skip this optimization if the class or any of its
1891
42.6k
  // methods are marked dllimport. This isn't a complete solution, since objects
1892
42.6k
  // without any dllimport methods can be used in one DLL and constructed in
1893
42.6k
  // another, but it is the current behavior of LimitedDebugInfo.
1894
42.6k
  
if (42.6k
CXXDecl->hasDefinition() && 42.6k
CXXDecl->isDynamicClass()42.6k
&&
1895
892
      !isClassOrMethodDLLImport(CXXDecl))
1896
887
    return true;
1897
41.7k
1898
41.7k
  TemplateSpecializationKind Spec = TSK_Undeclared;
1899
41.7k
  if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1900
4.10k
    Spec = SD->getSpecializationKind();
1901
41.7k
1902
41.7k
  if (Spec == TSK_ExplicitInstantiationDeclaration &&
1903
22
      hasExplicitMemberDefinition(CXXDecl->method_begin(),
1904
22
                                  CXXDecl->method_end()))
1905
4
    return true;
1906
41.7k
1907
41.7k
  return false;
1908
41.7k
}
1909
1910
47.0k
void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
1911
47.0k
  if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
1912
822
    return;
1913
46.1k
1914
46.1k
  QualType Ty = CGM.getContext().getRecordType(RD);
1915
46.1k
  llvm::DIType *T = getTypeOrNull(Ty);
1916
46.1k
  if (
T && 46.1k
T->isForwardDecl()74
)
1917
12
    completeClassData(RD);
1918
47.0k
}
1919
1920
1.02k
llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
1921
1.02k
  RecordDecl *RD = Ty->getDecl();
1922
1.02k
  llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
1923
1.02k
  if (
T || 1.02k
shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
1924
1.02k
                                CGM.getLangOpts())) {
1925
247
    if (!T)
1926
247
      T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
1927
247
    return T;
1928
247
  }
1929
779
1930
779
  return CreateTypeDefinition(Ty);
1931
779
}
1932
1933
847
llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1934
847
  RecordDecl *RD = Ty->getDecl();
1935
847
1936
847
  // Get overall information about the record type for the debug info.
1937
847
  llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1938
847
1939
847
  // Records and classes and unions can all be recursive.  To handle them, we
1940
847
  // first generate a debug descriptor for the struct as a forward declaration.
1941
847
  // Then (if it is a definition) we go through and get debug info for all of
1942
847
  // its members.  Finally, we create a descriptor for the complete type (which
1943
847
  // may refer to the forward decl if the struct is recursive) and replace all
1944
847
  // uses of the forward declaration with the final definition.
1945
847
  llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
1946
847
1947
847
  const RecordDecl *D = RD->getDefinition();
1948
847
  if (
!D || 847
!D->isCompleteDefinition()805
)
1949
43
    return FwdDecl;
1950
804
1951
804
  
if (const auto *804
CXXDecl804
= dyn_cast<CXXRecordDecl>(RD))
1952
678
    CollectContainingType(CXXDecl, FwdDecl);
1953
804
1954
804
  // Push the struct on region stack.
1955
804
  LexicalBlockStack.emplace_back(&*FwdDecl);
1956
804
  RegionMap[Ty->getDecl()].reset(FwdDecl);
1957
804
1958
804
  // Convert all the elements.
1959
804
  SmallVector<llvm::Metadata *, 16> EltTys;
1960
804
  // what about nested types?
1961
804
1962
804
  // Note: The split of CXXDecl information here is intentional, the
1963
804
  // gdb tests will depend on a certain ordering at printout. The debug
1964
804
  // information offsets are still correct if we merge them all together
1965
804
  // though.
1966
804
  const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1967
804
  if (
CXXDecl804
) {
1968
678
    CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1969
678
    CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl);
1970
678
  }
1971
804
1972
804
  // Collect data fields (including static variables and any initializers).
1973
804
  CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1974
804
  if (CXXDecl)
1975
678
    CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1976
804
1977
804
  LexicalBlockStack.pop_back();
1978
804
  RegionMap.erase(Ty->getDecl());
1979
804
1980
804
  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
1981
804
  DBuilder.replaceArrays(FwdDecl, Elements);
1982
804
1983
804
  if (FwdDecl->isTemporary())
1984
0
    FwdDecl =
1985
0
        llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
1986
847
1987
847
  RegionMap[Ty->getDecl()].reset(FwdDecl);
1988
847
  return FwdDecl;
1989
847
}
1990
1991
llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1992
35
                                      llvm::DIFile *Unit) {
1993
35
  // Ignore protocols.
1994
35
  return getOrCreateType(Ty->getBaseType(), Unit);
1995
35
}
1996
1997
llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
1998
0
                                      llvm::DIFile *Unit) {
1999
0
  // Ignore protocols.
2000
0
  SourceLocation Loc = Ty->getDecl()->getLocation();
2001
0
2002
0
  // Use Typedefs to represent ObjCTypeParamType.
2003
0
  return DBuilder.createTypedef(
2004
0
      getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2005
0
      Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2006
0
      getDeclContextDescriptor(Ty->getDecl()));
2007
0
}
2008
2009
/// \return true if Getter has the default name for the property PD.
2010
static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2011
78
                                 const ObjCMethodDecl *Getter) {
2012
78
  assert(PD);
2013
78
  if (!Getter)
2014
0
    return true;
2015
78
2016
78
  assert(Getter->getDeclName().isObjCZeroArgSelector());
2017
78
  return PD->getName() ==
2018
78
         Getter->getDeclName().getObjCSelector().getNameForSlot(0);
2019
78
}
2020
2021
/// \return true if Setter has the default name for the property PD.
2022
static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2023
78
                                 const ObjCMethodDecl *Setter) {
2024
78
  assert(PD);
2025
78
  if (!Setter)
2026
12
    return true;
2027
66
2028
78
  assert(Setter->getDeclName().isObjCOneArgSelector());
2029
66
  return SelectorTable::constructSetterName(PD->getName()) ==
2030
66
         Setter->getDeclName().getObjCSelector().getNameForSlot(0);
2031
66
}
2032
2033
llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2034
144
                                      llvm::DIFile *Unit) {
2035
144
  ObjCInterfaceDecl *ID = Ty->getDecl();
2036
144
  if (!ID)
2037
0
    return nullptr;
2038
144
2039
144
  // Return a forward declaration if this type was imported from a clang module,
2040
144
  // and this is not the compile unit with the implementation of the type (which
2041
144
  // may contain hidden ivars).
2042
144
  
if (144
DebugTypeExtRefs && 144
ID->isFromASTFile()19
&&
ID->getDefinition()6
&&
2043
6
      !ID->getImplementation())
2044
3
    return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2045
3
                                      ID->getName(),
2046
3
                                      getDeclContextDescriptor(ID), Unit, 0);
2047
141
2048
141
  // Get overall information about the record type for the debug info.
2049
141
  llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2050
141
  unsigned Line = getLineNumber(ID->getLocation());
2051
141
  auto RuntimeLang =
2052
141
      static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2053
141
2054
141
  // If this is just a forward declaration return a special forward-declaration
2055
141
  // debug type since we won't be able to lay out the entire type.
2056
141
  ObjCInterfaceDecl *Def = ID->getDefinition();
2057
141
  if (
!Def || 141
!Def->getImplementation()125
) {
2058
85
    llvm::DIScope *Mod = getParentModuleOrNull(ID);
2059
85
    llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
2060
85
        llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? 
Mod13
:
TheCU72
,
2061
85
        DefUnit, Line, RuntimeLang);
2062
85
    ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
2063
85
    return FwdDecl;
2064
85
  }
2065
56
2066
56
  return CreateTypeDefinition(Ty, Unit);
2067
56
}
2068
2069
llvm::DIModule *
2070
CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
2071
406
                                  bool CreateSkeletonCU) {
2072
406
  // Use the Module pointer as the key into the cache. This is a
2073
406
  // nullptr if the "Module" is a PCH, which is safe because we don't
2074
406
  // support chained PCH debug info, so there can only be a single PCH.
2075
406
  const Module *M = Mod.getModuleOrNull();
2076
406
  auto ModRef = ModuleCache.find(M);
2077
406
  if (ModRef != ModuleCache.end())
2078
353
    return cast<llvm::DIModule>(ModRef->second);
2079
53
2080
53
  // Macro definitions that were defined with "-D" on the command line.
2081
53
  SmallString<128> ConfigMacros;
2082
53
  {
2083
53
    llvm::raw_svector_ostream OS(ConfigMacros);
2084
53
    const auto &PPOpts = CGM.getPreprocessorOpts();
2085
53
    unsigned I = 0;
2086
53
    // Translate the macro definitions back into a commmand line.
2087
16
    for (auto &M : PPOpts.Macros) {
2088
16
      if (++I > 1)
2089
3
        OS << " ";
2090
16
      const std::string &Macro = M.first;
2091
16
      bool Undef = M.second;
2092
16
      OS << "\"-" << (Undef ? 
'U'1
:
'D'15
);
2093
16
      for (char c : Macro)
2094
132
        switch (c) {
2095
0
        case '\\' : OS << "\\\\"; break;
2096
0
        case '"'  : OS << "\\\""; break;
2097
132
        default: OS << c;
2098
132
        }
2099
16
      OS << '\"';
2100
16
    }
2101
53
  }
2102
53
2103
53
  
bool IsRootModule = M ? 53
!M->Parent33
:
true20
;
2104
53
  if (
CreateSkeletonCU && 53
IsRootModule23
) {
2105
19
    // PCH files don't have a signature field in the control block,
2106
19
    // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2107
19
    // We use the lower 64 bits for debug info.
2108
19
    uint64_t Signature =
2109
19
        Mod.getSignature()
2110
10
            ? (uint64_t)Mod.getSignature()[1] << 32 | Mod.getSignature()[0]
2111
9
            : ~1ULL;
2112
19
    llvm::DIBuilder DIB(CGM.getModule());
2113
19
    DIB.createCompileUnit(TheCU->getSourceLanguage(),
2114
19
                          DIB.createFile(Mod.getModuleName(), Mod.getPath()),
2115
19
                          TheCU->getProducer(), true, StringRef(), 0,
2116
19
                          Mod.getASTFile(), llvm::DICompileUnit::FullDebug,
2117
19
                          Signature);
2118
19
    DIB.finalize();
2119
19
  }
2120
53
  llvm::DIModule *Parent =
2121
45
      IsRootModule ? nullptr
2122
8
                   : getOrCreateModuleRef(
2123
8
                         ExternalASTSource::ASTSourceDescriptor(*M->Parent),
2124
8
                         CreateSkeletonCU);
2125
53
  llvm::DIModule *DIMod =
2126
53
      DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2127
53
                            Mod.getPath(), CGM.getHeaderSearchOpts().Sysroot);
2128
53
  ModuleCache[M].reset(DIMod);
2129
53
  return DIMod;
2130
406
}
2131
2132
llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2133
126
                                                llvm::DIFile *Unit) {
2134
126
  ObjCInterfaceDecl *ID = Ty->getDecl();
2135
126
  llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2136
126
  unsigned Line = getLineNumber(ID->getLocation());
2137
126
  unsigned RuntimeLang = TheCU->getSourceLanguage();
2138
126
2139
126
  // Bit size, align and offset of the type.
2140
126
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
2141
126
  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2142
126
2143
126
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2144
126
  if (ID->getImplementation())
2145
59
    Flags |= llvm::DINode::FlagObjcClassComplete;
2146
126
2147
126
  llvm::DIScope *Mod = getParentModuleOrNull(ID);
2148
126
  llvm::DICompositeType *RealDecl = DBuilder.createStructType(
2149
126
      Mod ? 
Mod13
:
Unit113
, ID->getName(), DefUnit, Line, Size, Align, Flags,
2150
126
      nullptr, llvm::DINodeArray(), RuntimeLang);
2151
126
2152
126
  QualType QTy(Ty, 0);
2153
126
  TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
2154
126
2155
126
  // Push the struct on region stack.
2156
126
  LexicalBlockStack.emplace_back(RealDecl);
2157
126
  RegionMap[Ty->getDecl()].reset(RealDecl);
2158
126
2159
126
  // Convert all the elements.
2160
126
  SmallVector<llvm::Metadata *, 16> EltTys;
2161
126
2162
126
  ObjCInterfaceDecl *SClass = ID->getSuperClass();
2163
126
  if (
SClass126
) {
2164
35
    llvm::DIType *SClassTy =
2165
35
        getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
2166
35
    if (!SClassTy)
2167
0
      return nullptr;
2168
35
2169
35
    llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0,
2170
35
                                                      llvm::DINode::FlagZero);
2171
35
    EltTys.push_back(InhTag);
2172
35
  }
2173
126
2174
126
  // Create entries for all of the properties.
2175
126
  
auto AddProperty = [&](const ObjCPropertyDecl *PD) 126
{
2176
47
    SourceLocation Loc = PD->getLocation();
2177
47
    llvm::DIFile *PUnit = getOrCreateFile(Loc);
2178
47
    unsigned PLine = getLineNumber(Loc);
2179
47
    ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2180
47
    ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2181
47
    llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2182
47
        PD->getName(), PUnit, PLine,
2183
44
        hasDefaultGetterName(PD, Getter) ? ""
2184
3
                                         : getSelectorName(PD->getGetterName()),
2185
45
        hasDefaultSetterName(PD, Setter) ? ""
2186
2
                                         : getSelectorName(PD->getSetterName()),
2187
47
        PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
2188
47
    EltTys.push_back(PropertyNode);
2189
47
  };
2190
126
  {
2191
126
    llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
2192
126
    for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
2193
11
      
for (auto *PD : ClassExt->properties()) 11
{
2194
7
        PropertySet.insert(PD->getIdentifier());
2195
7
        AddProperty(PD);
2196
7
      }
2197
42
    for (const auto *PD : ID->properties()) {
2198
42
      // Don't emit duplicate metadata for properties that were already in a
2199
42
      // class extension.
2200
42
      if (!PropertySet.insert(PD->getIdentifier()).second)
2201
2
        continue;
2202
40
      AddProperty(PD);
2203
40
    }
2204
126
  }
2205
126
2206
126
  const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2207
126
  unsigned FieldNo = 0;
2208
223
  for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2209
126
       
Field = Field->getNextIvar(), ++FieldNo97
) {
2210
97
    llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2211
97
    if (!FieldTy)
2212
0
      return nullptr;
2213
97
2214
97
    StringRef FieldName = Field->getName();
2215
97
2216
97
    // Ignore unnamed fields.
2217
97
    if (FieldName.empty())
2218
2
      continue;
2219
95
2220
95
    // Get the location for the field.
2221
95
    llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
2222
95
    unsigned FieldLine = getLineNumber(Field->getLocation());
2223
95
    QualType FType = Field->getType();
2224
95
    uint64_t FieldSize = 0;
2225
95
    uint32_t FieldAlign = 0;
2226
95
2227
95
    if (
!FType->isIncompleteArrayType()95
) {
2228
95
2229
95
      // Bit size, align and offset of the type.
2230
95
      FieldSize = Field->isBitField()
2231
4
                      ? Field->getBitWidthValue(CGM.getContext())
2232
91
                      : CGM.getContext().getTypeSize(FType);
2233
95
      FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2234
95
    }
2235
95
2236
95
    uint64_t FieldOffset;
2237
95
    if (
CGM.getLangOpts().ObjCRuntime.isNonFragile()95
) {
2238
89
      // We don't know the runtime offset of an ivar if we're using the
2239
89
      // non-fragile ABI.  For bitfields, use the bit offset into the first
2240
89
      // byte of storage of the bitfield.  For other fields, use zero.
2241
89
      if (
Field->isBitField()89
) {
2242
4
        FieldOffset =
2243
4
            CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
2244
4
        FieldOffset %= CGM.getContext().getCharWidth();
2245
89
      } else {
2246
85
        FieldOffset = 0;
2247
85
      }
2248
95
    } else {
2249
6
      FieldOffset = RL.getFieldOffset(FieldNo);
2250
6
    }
2251
95
2252
95
    llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2253
95
    if (Field->getAccessControl() == ObjCIvarDecl::Protected)
2254
49
      Flags = llvm::DINode::FlagProtected;
2255
46
    else 
if (46
Field->getAccessControl() == ObjCIvarDecl::Private46
)
2256
35
      Flags = llvm::DINode::FlagPrivate;
2257
11
    else 
if (11
Field->getAccessControl() == ObjCIvarDecl::Public11
)
2258
11
      Flags = llvm::DINode::FlagPublic;
2259
95
2260
95
    llvm::MDNode *PropertyNode = nullptr;
2261
95
    if (ObjCImplementationDecl *
ImpD95
= ID->getImplementation()) {
2262
60
      if (ObjCPropertyImplDecl *PImpD =
2263
31
              ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
2264
31
        if (ObjCPropertyDecl *
PD31
= PImpD->getPropertyDecl()) {
2265
31
          SourceLocation Loc = PD->getLocation();
2266
31
          llvm::DIFile *PUnit = getOrCreateFile(Loc);
2267
31
          unsigned PLine = getLineNumber(Loc);
2268
31
          ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2269
31
          ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2270
31
          PropertyNode = DBuilder.createObjCProperty(
2271
31
              PD->getName(), PUnit, PLine,
2272
31
              hasDefaultGetterName(PD, Getter) ? 
""30
: getSelectorName(
2273
1
                                                          PD->getGetterName()),
2274
31
              hasDefaultSetterName(PD, Setter) ? 
""30
: getSelectorName(
2275
1
                                                          PD->getSetterName()),
2276
31
              PD->getPropertyAttributes(),
2277
31
              getOrCreateType(PD->getType(), PUnit));
2278
31
        }
2279
31
      }
2280
60
    }
2281
97
    FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2282
97
                                      FieldSize, FieldAlign, FieldOffset, Flags,
2283
97
                                      FieldTy, PropertyNode);
2284
97
    EltTys.push_back(FieldTy);
2285
97
  }
2286
126
2287
126
  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2288
126
  DBuilder.replaceArrays(RealDecl, Elements);
2289
126
2290
126
  LexicalBlockStack.pop_back();
2291
126
  return RealDecl;
2292
126
}
2293
2294
llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2295
15
                                      llvm::DIFile *Unit) {
2296
15
  llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2297
15
  int64_t Count = Ty->getNumElements();
2298
15
  if (Count == 0)
2299
15
    // If number of elements are not known then this is an unbounded array.
2300
15
    // Use Count == -1 to express such arrays.
2301
0
    Count = -1;
2302
15
2303
15
  llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count);
2304
15
  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
2305
15
2306
15
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
2307
15
  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2308
15
2309
15
  return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2310
15
}
2311
2312
196
llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
2313
196
  uint64_t Size;
2314
196
  uint32_t Align;
2315
196
2316
196
  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
2317
196
  if (const auto *
VAT196
= dyn_cast<VariableArrayType>(Ty)) {
2318
9
    Size = 0;
2319
9
    Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2320
9
                                   CGM.getContext());
2321
196
  } else 
if (187
Ty->isIncompleteArrayType()187
) {
2322
4
    Size = 0;
2323
4
    if (Ty->getElementType()->isIncompleteType())
2324
1
      Align = 0;
2325
4
    else
2326
3
      Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
2327
187
  } else 
if (183
Ty->isIncompleteType()183
) {
2328
2
    Size = 0;
2329
2
    Align = 0;
2330
183
  } else {
2331
181
    // Size and align of the whole array, not the element type.
2332
181
    Size = CGM.getContext().getTypeSize(Ty);
2333
181
    Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2334
181
  }
2335
196
2336
196
  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
2337
196
  // interior arrays, do we care?  Why aren't nested arrays represented the
2338
196
  // obvious/recursive way?
2339
196
  SmallVector<llvm::Metadata *, 8> Subscripts;
2340
196
  QualType EltTy(Ty, 0);
2341
400
  while (
(Ty = dyn_cast<ArrayType>(EltTy))400
) {
2342
204
    // If the number of elements is known, then count is that number. Otherwise,
2343
204
    // it's -1. This allows us to represent a subrange with an array of 0
2344
204
    // elements, like this:
2345
204
    //
2346
204
    //   struct foo {
2347
204
    //     int x[0];
2348
204
    //   };
2349
204
    int64_t Count = -1; // Count == -1 is an unbounded array.
2350
204
    if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
2351
190
      Count = CAT->getSize().getZExtValue();
2352
14
    else 
if (const auto *14
VAT14
= dyn_cast<VariableArrayType>(Ty)) {
2353
10
      if (Expr *
Size10
= VAT->getSizeExpr()) {
2354
9
        llvm::APSInt V;
2355
9
        if (Size->EvaluateAsInt(V, CGM.getContext()))
2356
1
          Count = V.getExtValue();
2357
9
      }
2358
14
    }
2359
204
2360
204
    // FIXME: Verify this is right for VLAs.
2361
204
    Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
2362
204
    EltTy = Ty->getElementType();
2363
204
  }
2364
196
2365
196
  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2366
196
2367
196
  return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2368
196
                                  SubscriptArray);
2369
196
}
2370
2371
llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2372
115
                                      llvm::DIFile *Unit) {
2373
115
  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2374
115
                               Ty->getPointeeType(), Unit);
2375
115
}
2376
2377
llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2378
9
                                      llvm::DIFile *Unit) {
2379
9
  return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2380
9
                               Ty->getPointeeType(), Unit);
2381
9
}
2382
2383
llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2384
34
                                      llvm::DIFile *U) {
2385
34
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2386
34
  uint64_t Size = 0;
2387
34
2388
34
  if (
!Ty->isIncompleteType()34
) {
2389
31
    Size = CGM.getContext().getTypeSize(Ty);
2390
31
2391
31
    // Set the MS inheritance model. There is no flag for the unspecified model.
2392
31
    if (
CGM.getTarget().getCXXABI().isMicrosoft()31
) {
2393
12
      switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
2394
6
      case MSInheritanceAttr::Keyword_single_inheritance:
2395
6
        Flags |= llvm::DINode::FlagSingleInheritance;
2396
6
        break;
2397
2
      case MSInheritanceAttr::Keyword_multiple_inheritance:
2398
2
        Flags |= llvm::DINode::FlagMultipleInheritance;
2399
2
        break;
2400
2
      case MSInheritanceAttr::Keyword_virtual_inheritance:
2401
2
        Flags |= llvm::DINode::FlagVirtualInheritance;
2402
2
        break;
2403
2
      case MSInheritanceAttr::Keyword_unspecified_inheritance:
2404
2
        break;
2405
34
      }
2406
34
    }
2407
31
  }
2408
34
2409
34
  llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
2410
34
  if (Ty->isMemberDataPointerType())
2411
14
    return DBuilder.createMemberPointerType(
2412
14
        getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
2413
14
        Flags);
2414
20
2415
20
  const FunctionProtoType *FPT =
2416
20
      Ty->getPointeeType()->getAs<FunctionProtoType>();
2417
20
  return DBuilder.createMemberPointerType(
2418
20
      getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType(
2419
20
                                        Ty->getClass(), FPT->getTypeQuals())),
2420
20
                                    FPT, U),
2421
20
      ClassType, Size, /*Align=*/0, Flags);
2422
20
}
2423
2424
1
llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
2425
1
  auto *FromTy = getOrCreateType(Ty->getValueType(), U);
2426
1
  return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
2427
1
}
2428
2429
llvm::DIType* CGDebugInfo::CreateType(const PipeType *Ty,
2430
0
                                     llvm::DIFile *U) {
2431
0
  return getOrCreateType(Ty->getElementType(), U);
2432
0
}
2433
2434
82
llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
2435
82
  const EnumDecl *ED = Ty->getDecl();
2436
82
2437
82
  uint64_t Size = 0;
2438
82
  uint32_t Align = 0;
2439
82
  if (
!ED->getTypeForDecl()->isIncompleteType()82
) {
2440
80
    Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2441
80
    Align = getDeclAlignIfRequired(ED, CGM.getContext());
2442
80
  }
2443
82
2444
82
  SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2445
82
2446
82
  bool isImportedFromModule =
2447
82
      DebugTypeExtRefs && 
ED->isFromASTFile()39
&&
ED->getDefinition()18
;
2448
82
2449
82
  // If this is just a forward declaration, construct an appropriately
2450
82
  // marked node and just return it.
2451
82
  if (
isImportedFromModule || 82
!ED->getDefinition()64
) {
2452
26
    // Note that it is possible for enums to be created as part of
2453
26
    // their own declcontext. In this case a FwdDecl will be created
2454
26
    // twice. This doesn't cause a problem because both FwdDecls are
2455
26
    // entered into the ReplaceMap: finalize() will replace the first
2456
26
    // FwdDecl with the second and then replace the second with
2457
26
    // complete type.
2458
26
    llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
2459
26
    llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2460
26
    llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
2461
26
        llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
2462
26
2463
26
    unsigned Line = getLineNumber(ED->getLocation());
2464
26
    StringRef EDName = ED->getName();
2465
26
    llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
2466
26
        llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
2467
26
        0, Size, Align, llvm::DINode::FlagFwdDecl, FullName);
2468
26
2469
26
    ReplaceMap.emplace_back(
2470
26
        std::piecewise_construct, std::make_tuple(Ty),
2471
26
        std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
2472
26
    return RetTy;
2473
26
  }
2474
56
2475
56
  return CreateTypeDefinition(Ty);
2476
56
}
2477
2478
57
llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
2479
57
  const EnumDecl *ED = Ty->getDecl();
2480
57
  uint64_t Size = 0;
2481
57
  uint32_t Align = 0;
2482
57
  if (
!ED->getTypeForDecl()->isIncompleteType()57
) {
2483
57
    Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2484
57
    Align = getDeclAlignIfRequired(ED, CGM.getContext());
2485
57
  }
2486
57
2487
57
  SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2488
57
2489
57
  // Create elements for each enumerator.
2490
57
  SmallVector<llvm::Metadata *, 16> Enumerators;
2491
57
  ED = ED->getDefinition();
2492
66
  for (const auto *Enum : ED->enumerators()) {
2493
66
    Enumerators.push_back(DBuilder.createEnumerator(
2494
66
        Enum->getName(), Enum->getInitVal().getSExtValue()));
2495
66
  }
2496
57
2497
57
  // Return a CompositeType for the enum itself.
2498
57
  llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
2499
57
2500
57
  llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2501
57
  unsigned Line = getLineNumber(ED->getLocation());
2502
57
  llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
2503
57
  llvm::DIType *ClassTy =
2504
57
      ED->isFixed() ? 
getOrCreateType(ED->getIntegerType(), DefUnit)14
:
nullptr43
;
2505
57
  return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
2506
57
                                        Line, Size, Align, EltArray, ClassTy,
2507
57
                                        FullName);
2508
57
}
2509
2510
llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
2511
                                        unsigned MType, SourceLocation LineLoc,
2512
1.07k
                                        StringRef Name, StringRef Value) {
2513
1.07k
  unsigned Line = LineLoc.isInvalid() ? 
01.03k
:
getLineNumber(LineLoc)36
;
2514
1.07k
  return DBuilder.createMacro(Parent, Line, MType, Name, Value);
2515
1.07k
}
2516
2517
llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
2518
                                                    SourceLocation LineLoc,
2519
16
                                                    SourceLocation FileLoc) {
2520
16
  llvm::DIFile *FName = getOrCreateFile(FileLoc);
2521
16
  unsigned Line = LineLoc.isInvalid() ? 
08
:
getLineNumber(LineLoc)8
;
2522
16
  return DBuilder.createTempMacroFile(Parent, Line, FName);
2523
16
}
2524
2525
79.0k
static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
2526
79.0k
  Qualifiers Quals;
2527
79.8k
  do {
2528
79.8k
    Qualifiers InnerQuals = T.getLocalQualifiers();
2529
79.8k
    // Qualifiers::operator+() doesn't like it if you add a Qualifier
2530
79.8k
    // that is already there.
2531
79.8k
    Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
2532
79.8k
    Quals += InnerQuals;
2533
79.8k
    QualType LastT = T;
2534
79.8k
    switch (T->getTypeClass()) {
2535
79.0k
    default:
2536
79.0k
      return C.getQualifiedType(T.getTypePtr(), Quals);
2537
194
    case Type::TemplateSpecialization: {
2538
194
      const auto *Spec = cast<TemplateSpecializationType>(T);
2539
194
      if (Spec->isTypeAlias())
2540
6
        return C.getQualifiedType(T.getTypePtr(), Quals);
2541
188
      T = Spec->desugar();
2542
188
      break;
2543
188
    }
2544
4
    case Type::TypeOfExpr:
2545
4
      T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2546
4
      break;
2547
0
    case Type::TypeOf:
2548
0
      T = cast<TypeOfType>(T)->getUnderlyingType();
2549
0
      break;
2550
5
    case Type::Decltype:
2551
5
      T = cast<DecltypeType>(T)->getUnderlyingType();
2552
5
      break;
2553
0
    case Type::UnaryTransform:
2554
0
      T = cast<UnaryTransformType>(T)->getUnderlyingType();
2555
0
      break;
2556
8
    case Type::Attributed:
2557
8
      T = cast<AttributedType>(T)->getEquivalentType();
2558
8
      break;
2559
340
    case Type::Elaborated:
2560
340
      T = cast<ElaboratedType>(T)->getNamedType();
2561
340
      break;
2562
30
    case Type::Paren:
2563
30
      T = cast<ParenType>(T)->getInnerType();
2564
30
      break;
2565
152
    case Type::SubstTemplateTypeParm:
2566
152
      T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
2567
152
      break;
2568
36
    case Type::Auto:
2569
36
    case Type::DeducedTemplateSpecialization: {
2570
36
      QualType DT = cast<DeducedType>(T)->getDeducedType();
2571
36
      assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
2572
36
      T = DT;
2573
36
      break;
2574
36
    }
2575
43
    case Type::Adjusted:
2576
43
    case Type::Decayed:
2577
43
      // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2578
43
      T = cast<AdjustedType>(T)->getAdjustedType();
2579
43
      break;
2580
806
    }
2581
806
2582
79.8k
    assert(T != LastT && "Type unwrapping failed to unwrap!");
2583
806
    (void)LastT;
2584
79.0k
  } while (true);
2585
79.0k
}
2586
2587
64.1k
llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
2588
64.1k
2589
64.1k
  // Unwrap the type as needed for debug information.
2590
64.1k
  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2591
64.1k
2592
64.1k
  auto it = TypeCache.find(Ty.getAsOpaquePtr());
2593
64.1k
  if (
it != TypeCache.end()64.1k
) {
2594
10.1k
    // Verify that the debug info still exists.
2595
10.1k
    if (llvm::Metadata *V = it->second)
2596
9.64k
      return cast<llvm::DIType>(V);
2597
54.5k
  }
2598
54.5k
2599
54.5k
  return nullptr;
2600
54.5k
}
2601
2602
void CGDebugInfo::completeTemplateDefinition(
2603
4
    const ClassTemplateSpecializationDecl &SD) {
2604
4
  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2605
2
    return;
2606
2
  completeUnusedClass(SD);
2607
2
}
2608
2609
6
void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
2610
6
  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2611
0
    return;
2612
6
2613
6
  completeClassData(&D);
2614
6
  // In case this type has no member function definitions being emitted, ensure
2615
6
  // it is retained
2616
6
  RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
2617
6
}
2618
2619
14.8k
llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
2620
14.8k
  if (Ty.isNull())
2621
0
    return nullptr;
2622
14.8k
2623
14.8k
  // Unwrap the type as needed for debug information.
2624
14.8k
  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2625
14.8k
2626
14.8k
  if (auto *T = getTypeOrNull(Ty))
2627
9.30k
    return T;
2628
5.53k
2629
5.53k
  llvm::DIType *Res = CreateTypeNode(Ty, Unit);
2630
5.53k
  void* TyPtr = Ty.getAsOpaquePtr();
2631
5.53k
2632
5.53k
  // And update the type cache.
2633
5.53k
  TypeCache[TyPtr].reset(Res);
2634
5.53k
2635
5.53k
  return Res;
2636
5.53k
}
2637
2638
4.22k
llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
2639
4.22k
  // A forward declaration inside a module header does not belong to the module.
2640
4.22k
  if (
isa<RecordDecl>(D) && 4.22k
!cast<RecordDecl>(D)->getDefinition()1.71k
)
2641
107
    return nullptr;
2642
4.11k
  
if (4.11k
DebugTypeExtRefs && 4.11k
D->isFromASTFile()481
) {
2643
177
    // Record a reference to an imported clang module or precompiled header.
2644
177
    auto *Reader = CGM.getContext().getExternalSource();
2645
177
    auto Idx = D->getOwningModuleID();
2646
177
    auto Info = Reader->getSourceDescriptor(Idx);
2647
177
    if (Info)
2648
177
      return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
2649
3.94k
  } else 
if (3.94k
ClangModuleMap3.94k
) {
2650
215
    // We are building a clang module or a precompiled header.
2651
215
    //
2652
215
    // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
2653
215
    // and it wouldn't be necessary to specify the parent scope
2654
215
    // because the type is already unique by definition (it would look
2655
215
    // like the output of -fno-standalone-debug). On the other hand,
2656
215
    // the parent scope helps a consumer to quickly locate the object
2657
215
    // file where the type's definition is located, so it might be
2658
215
    // best to make this behavior a command line or debugger tuning
2659
215
    // option.
2660
215
    FullSourceLoc Loc(D->getLocation(), CGM.getContext().getSourceManager());
2661
215
    if (Module *
M215
= D->getOwningModule()) {
2662
125
      // This is a (sub-)module.
2663
125
      auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
2664
125
      return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
2665
0
    } else {
2666
90
      // This the precompiled header being built.
2667
90
      return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
2668
90
    }
2669
3.72k
  }
2670
3.72k
2671
3.72k
  return nullptr;
2672
3.72k
}
2673
2674
5.53k
llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
2675
5.53k
  // Handle qualifiers, which recursively handles what they refer to.
2676
5.53k
  if (Ty.hasLocalQualifiers())
2677
312
    return CreateQualifiedType(Ty, Unit);
2678
5.22k
2679
5.22k
  // Work out details of type.
2680
5.22k
  switch (Ty->getTypeClass()) {
2681
5.22k
#define TYPE(Class, Base)
2682
5.22k
#define ABSTRACT_TYPE(Class, Base)
2683
5.22k
#define NON_CANONICAL_TYPE(Class, Base)
2684
0
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2685
5.22k
#include 
"clang/AST/TypeNodes.def"5.22k
2686
0
    llvm_unreachable("Dependent types cannot show up in debug information");
2687
0
2688
15
  case Type::ExtVector:
2689
15
  case Type::Vector:
2690
15
    return CreateType(cast<VectorType>(Ty), Unit);
2691
141
  case Type::ObjCObjectPointer:
2692
141
    return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2693
35
  case Type::ObjCObject:
2694
35
    return CreateType(cast<ObjCObjectType>(Ty), Unit);
2695
0
  case Type::ObjCTypeParam:
2696
0
    return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
2697
144
  case Type::ObjCInterface:
2698
144
    return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2699
1.37k
  case Type::Builtin:
2700
1.37k
    return CreateType(cast<BuiltinType>(Ty));
2701
2
  case Type::Complex:
2702
2
    return CreateType(cast<ComplexType>(Ty));
2703
834
  case Type::Pointer:
2704
834
    return CreateType(cast<PointerType>(Ty), Unit);
2705
19
  case Type::BlockPointer:
2706
19
    return CreateType(cast<BlockPointerType>(Ty), Unit);
2707
299
  case Type::Typedef:
2708
299
    return CreateType(cast<TypedefType>(Ty), Unit);
2709
1.02k
  case Type::Record:
2710
1.02k
    return CreateType(cast<RecordType>(Ty));
2711
82
  case Type::Enum:
2712
82
    return CreateEnumType(cast<EnumType>(Ty));
2713
893
  case Type::FunctionProto:
2714
893
  case Type::FunctionNoProto:
2715
893
    return CreateType(cast<FunctionType>(Ty), Unit);
2716
196
  case Type::ConstantArray:
2717
196
  case Type::VariableArray:
2718
196
  case Type::IncompleteArray:
2719
196
    return CreateType(cast<ArrayType>(Ty), Unit);
2720
196
2721
115
  case Type::LValueReference:
2722
115
    return CreateType(cast<LValueReferenceType>(Ty), Unit);
2723
9
  case Type::RValueReference:
2724
9
    return CreateType(cast<RValueReferenceType>(Ty), Unit);
2725
196
2726
34
  case Type::MemberPointer:
2727
34
    return CreateType(cast<MemberPointerType>(Ty), Unit);
2728
196
2729
1
  case Type::Atomic:
2730
1
    return CreateType(cast<AtomicType>(Ty), Unit);
2731
196
2732
0
  case Type::Pipe:
2733
0
    return CreateType(cast<PipeType>(Ty), Unit);
2734
196
2735
3
  case Type::TemplateSpecialization:
2736
3
    return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2737
196
2738
0
  case Type::Auto:
2739
0
  case Type::Attributed:
2740
0
  case Type::Adjusted:
2741
0
  case Type::Decayed:
2742
0
  case Type::DeducedTemplateSpecialization:
2743
0
  case Type::Elaborated:
2744
0
  case Type::Paren:
2745
0
  case Type::SubstTemplateTypeParm:
2746
0
  case Type::TypeOfExpr:
2747
0
  case Type::TypeOf:
2748
0
  case Type::Decltype:
2749
0
  case Type::UnaryTransform:
2750
0
  case Type::PackExpansion:
2751
0
    break;
2752
0
  }
2753
0
2754
0
  
llvm_unreachable0
("type should have been unwrapped!");
2755
0
}
2756
2757
llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
2758
847
                                                           llvm::DIFile *Unit) {
2759
847
  QualType QTy(Ty, 0);
2760
847
2761
847
  auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
2762
847
2763
847
  // We may have cached a forward decl when we could have created
2764
847
  // a non-forward decl. Go ahead and create a non-forward decl
2765
847
  // now.
2766
847
  if (
T && 847
!T->isForwardDecl()63
)
2767
0
    return T;
2768
847
2769
847
  // Otherwise create the type.
2770
847
  llvm::DICompositeType *Res = CreateLimitedType(Ty);
2771
847
2772
847
  // Propagate members from the declaration to the definition
2773
847
  // CreateType(const RecordType*) will overwrite this with the members in the
2774
847
  // correct order if the full type is needed.
2775
847
  DBuilder.replaceArrays(Res, T ? 
T->getElements()63
:
llvm::DINodeArray()784
);
2776
847
2777
847
  // And update the type cache.
2778
847
  TypeCache[QTy.getAsOpaquePtr()].reset(Res);
2779
847
  return Res;
2780
847
}
2781
2782
// TODO: Currently used for context chains when limiting debug info.
2783
847
llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2784
847
  RecordDecl *RD = Ty->getDecl();
2785
847
2786
847
  // Get overall information about the record type for the debug info.
2787
847
  llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2788
847
  unsigned Line = getLineNumber(RD->getLocation());
2789
847
  StringRef RDName = getClassName(RD);
2790
847
2791
847
  llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
2792
847
2793
847
  // If we ended up creating the type during the context chain construction,
2794
847
  // just return that.
2795
847
  auto *T = cast_or_null<llvm::DICompositeType>(
2796
847
      getTypeOrNull(CGM.getContext().getRecordType(RD)));
2797
847
  if (
T && 847
(!T->isForwardDecl() || 68
!RD->getDefinition()63
))
2798
5
    return T;
2799
842
2800
842
  // If this is just a forward or incomplete declaration, construct an
2801
842
  // appropriately marked node and just return it.
2802
842
  const RecordDecl *D = RD->getDefinition();
2803
842
  if (
!D || 842
!D->isCompleteDefinition()800
)
2804
43
    return getOrCreateRecordFwdDecl(Ty, RDContext);
2805
799
2806
799
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
2807
799
  auto Align = getDeclAlignIfRequired(D, CGM.getContext());
2808
799
2809
799
  SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2810
799
2811
799
  llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
2812
799
      getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
2813
799
      llvm::DINode::FlagZero, FullName);
2814
799
2815
799
  // Elements of composite types usually have back to the type, creating
2816
799
  // uniquing cycles.  Distinct nodes are more efficient.
2817
799
  switch (RealDecl->getTag()) {
2818
0
  default:
2819
0
    llvm_unreachable("invalid composite type tag");
2820
799
2821
0
  case llvm::dwarf::DW_TAG_array_type:
2822
0
  case llvm::dwarf::DW_TAG_enumeration_type:
2823
0
    // Array elements and most enumeration elements don't have back references,
2824
0
    // so they don't tend to be involved in uniquing cycles and there is some
2825
0
    // chance of merging them when linking together two modules.  Only make
2826
0
    // them distinct if they are ODR-uniqued.
2827
0
    if (FullName.empty())
2828
0
      break;
2829
0
    
LLVM_FALLTHROUGH0
;
2830
0
2831
799
  case llvm::dwarf::DW_TAG_structure_type:
2832
799
  case llvm::dwarf::DW_TAG_union_type:
2833
799
  case llvm::dwarf::DW_TAG_class_type:
2834
799
    // Immediatley resolve to a distinct node.
2835
799
    RealDecl =
2836
799
        llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
2837
799
    break;
2838
799
  }
2839
799
2840
799
  RegionMap[Ty->getDecl()].reset(RealDecl);
2841
799
  TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
2842
799
2843
799
  if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2844
283
    DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
2845
283
                           CollectCXXTemplateParams(TSpecial, DefUnit));
2846
847
  return RealDecl;
2847
847
}
2848
2849
void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2850
678
                                        llvm::DICompositeType *RealDecl) {
2851
678
  // A class's primary base or the class itself contains the vtable.
2852
678
  llvm::DICompositeType *ContainingType = nullptr;
2853
678
  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2854
678
  if (const CXXRecordDecl *
PBase678
= RL.getPrimaryBase()) {
2855
18
    // Seek non-virtual primary base root.
2856
19
    while (
119
) {
2857
19
      const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2858
19
      const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2859
19
      if (
PBT && 19
!BRL.isPrimaryBaseVirtual()1
)
2860
1
        PBase = PBT;
2861
19
      else
2862
18
        break;
2863
19
    }
2864
18
    ContainingType = cast<llvm::DICompositeType>(
2865
18
        getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2866
18
                        getOrCreateFile(RD->getLocation())));
2867
678
  } else 
if (660
RD->isDynamicClass()660
)
2868
52
    ContainingType = RealDecl;
2869
678
2870
678
  DBuilder.replaceVTableHolder(RealDecl, ContainingType);
2871
678
}
2872
2873
llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
2874
227
                                            StringRef Name, uint64_t *Offset) {
2875
227
  llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2876
227
  uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2877
227
  auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2878
227
  llvm::DIType *Ty =
2879
227
      DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
2880
227
                                *Offset, llvm::DINode::FlagZero, FieldTy);
2881
227
  *Offset += FieldSize;
2882
227
  return Ty;
2883
227
}
2884
2885
void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
2886
                                           StringRef &Name,
2887
                                           StringRef &LinkageName,
2888
                                           llvm::DIScope *&FDContext,
2889
                                           llvm::DINodeArray &TParamsArray,
2890
22.0k
                                           llvm::DINode::DIFlags &Flags) {
2891
22.0k
  const auto *FD = cast<FunctionDecl>(GD.getDecl());
2892
22.0k
  Name = getFunctionName(FD);
2893
22.0k
  // Use mangled name as linkage name for C/C++ functions.
2894
22.0k
  if (
FD->hasPrototype()22.0k
) {
2895
21.9k
    LinkageName = CGM.getMangledName(GD);
2896
21.9k
    Flags |= llvm::DINode::FlagPrototyped;
2897
21.9k
  }
2898
22.0k
  // No need to replicate the linkage name if it isn't different from the
2899
22.0k
  // subprogram name, no need to have it at all unless coverage is enabled or
2900
22.0k
  // debug is set to more than just line tables or extra debug info is needed.
2901
22.0k
  if (
LinkageName == Name || 22.0k
(!CGM.getCodeGenOpts().EmitGcovArcs &&
2902
21.4k
                              !CGM.getCodeGenOpts().EmitGcovNotes &&
2903
21.4k
                              !CGM.getCodeGenOpts().DebugInfoForProfiling &&
2904
21.4k
                              DebugKind <= codegenoptions::DebugLineTablesOnly))
2905
21.0k
    LinkageName = StringRef();
2906
22.0k
2907
22.0k
  if (
DebugKind >= codegenoptions::LimitedDebugInfo22.0k
) {
2908
1.18k
    if (const NamespaceDecl *NSDecl =
2909
1.18k
        dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2910
47
      FDContext = getOrCreateNamespace(NSDecl);
2911
1.14k
    else 
if (const RecordDecl *1.14k
RDecl1.14k
=
2912
617
             dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
2913
617
      llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
2914
617
      FDContext = getContextDescriptor(RDecl, Mod ? 
Mod14
:
TheCU603
);
2915
1.14k
    }
2916
1.18k
    // Check if it is a noreturn-marked function
2917
1.18k
    if (FD->isNoReturn())
2918
0
      Flags |= llvm::DINode::FlagNoReturn;
2919
1.18k
    // Collect template parameters.
2920
1.18k
    TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2921
1.18k
  }
2922
22.0k
}
2923
2924
void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
2925
                                      unsigned &LineNo, QualType &T,
2926
                                      StringRef &Name, StringRef &LinkageName,
2927
472
                                      llvm::DIScope *&VDContext) {
2928
472
  Unit = getOrCreateFile(VD->getLocation());
2929
472
  LineNo = getLineNumber(VD->getLocation());
2930
472
2931
472
  setLocation(VD->getLocation());
2932
472
2933
472
  T = VD->getType();
2934
472
  if (
T->isIncompleteArrayType()472
) {
2935
0
    // CodeGen turns int[] into int[1] so we'll do the same here.
2936
0
    llvm::APInt ConstVal(32, 1);
2937
0
    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2938
0
2939
0
    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2940
0
                                              ArrayType::Normal, 0);
2941
0
  }
2942
472
2943
472
  Name = VD->getName();
2944
472
  if (
VD->getDeclContext() && 472
!isa<FunctionDecl>(VD->getDeclContext())472
&&
2945
420
      !isa<ObjCMethodDecl>(VD->getDeclContext()))
2946
418
    LinkageName = CGM.getMangledName(VD);
2947
472
  if (LinkageName == Name)
2948
314
    LinkageName = StringRef();
2949
472
2950
472
  // Since we emit declarations (DW_AT_members) for static members, place the
2951
472
  // definition of those static members in the namespace they were declared in
2952
472
  // in the source code (the lexical decl context).
2953
472
  // FIXME: Generalize this for even non-member global variables where the
2954
472
  // declaration and definition may have different lexical decl contexts, once
2955
472
  // we have support for emitting declarations of (non-member) global variables.
2956
33
  const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
2957
439
                                                   : VD->getDeclContext();
2958
472
  // When a record type contains an in-line initialization of a static data
2959
472
  // member, and the record type is marked as __declspec(dllexport), an implicit
2960
472
  // definition of the member will be created in the record context.  DWARF
2961
472
  // doesn't seem to have a nice way to describe this in a form that consumers
2962
472
  // are likely to understand, so fake the "normal" situation of a definition
2963
472
  // outside the class by putting it in the global scope.
2964
472
  if (DC->isRecord())
2965
1
    DC = CGM.getContext().getTranslationUnitDecl();
2966
472
2967
472
 llvm::DIScope *Mod = getParentModuleOrNull(VD);
2968
472
 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? 
Mod18
:
TheCU454
);
2969
472
}
2970
2971
llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
2972
7
                                                          bool Stub) {
2973
7
  llvm::DINodeArray TParamsArray;
2974
7
  StringRef Name, LinkageName;
2975
7
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2976
7
  SourceLocation Loc = GD.getDecl()->getLocation();
2977
7
  llvm::DIFile *Unit = getOrCreateFile(Loc);
2978
7
  llvm::DIScope *DContext = Unit;
2979
7
  unsigned Line = getLineNumber(Loc);
2980
7
  collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext,
2981
7
                           TParamsArray, Flags);
2982
7
  auto *FD = dyn_cast<FunctionDecl>(GD.getDecl());
2983
7
2984
7
  // Build function type.
2985
7
  SmallVector<QualType, 16> ArgTypes;
2986
7
  if (FD)
2987
7
    for (const ParmVarDecl *Parm : FD->parameters())
2988
3
      ArgTypes.push_back(Parm->getType());
2989
7
  CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
2990
7
  QualType FnType = CGM.getContext().getFunctionType(
2991
7
      FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
2992
7
  if (
Stub7
) {
2993
3
    return DBuilder.createFunction(
2994
3
        DContext, Name, LinkageName, Unit, Line,
2995
3
        getOrCreateFunctionType(GD.getDecl(), FnType, Unit),
2996
3
        !FD->isExternallyVisible(),
2997
3
        /* isDefinition = */ true, 0, Flags, CGM.getLangOpts().Optimize,
2998
3
        TParamsArray.get(), getFunctionDeclaration(FD));
2999
3
  }
3000
4
3001
4
  llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
3002
4
      DContext, Name, LinkageName, Unit, Line,
3003
4
      getOrCreateFunctionType(GD.getDecl(), FnType, Unit),
3004
4
      !FD->isExternallyVisible(),
3005
4
      /* isDefinition = */ false, 0, Flags, CGM.getLangOpts().Optimize,
3006
4
      TParamsArray.get(), getFunctionDeclaration(FD));
3007
4
  const auto *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl());
3008
4
  FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3009
4
                                 std::make_tuple(CanonDecl),
3010
4
                                 std::make_tuple(SP));
3011
4
  return SP;
3012
4
}
3013
3014
llvm::DISubprogram *
3015
4
CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
3016
4
  return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3017
4
}
3018
3019
llvm::DISubprogram *
3020
3
CGDebugInfo::getFunctionStub(GlobalDecl GD) {
3021
3
  return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3022
3
}
3023
3024
llvm::DIGlobalVariable *
3025
4
CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3026
4
  QualType T;
3027
4
  StringRef Name, LinkageName;
3028
4
  SourceLocation Loc = VD->getLocation();
3029
4
  llvm::DIFile *Unit = getOrCreateFile(Loc);
3030
4
  llvm::DIScope *DContext = Unit;
3031
4
  unsigned Line = getLineNumber(Loc);
3032
4
3033
4
  collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext);
3034
4
  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3035
4
  auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3036
4
      DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
3037
4
      !VD->isExternallyVisible(), nullptr, Align);
3038
4
  FwdDeclReplaceMap.emplace_back(
3039
4
      std::piecewise_construct,
3040
4
      std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3041
4
      std::make_tuple(static_cast<llvm::Metadata *>(GV)));
3042
4
  return GV;
3043
4
}
3044
3045
40
llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
3046
40
  // We only need a declaration (not a definition) of the type - so use whatever
3047
40
  // we would otherwise do to get a type for a pointee. (forward declarations in
3048
40
  // limited debug info, full definitions (if the type definition is available)
3049
40
  // in unlimited debug info)
3050
40
  if (const auto *TD = dyn_cast<TypeDecl>(D))
3051
10
    return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
3052
10
                           getOrCreateFile(TD->getLocation()));
3053
30
  auto I = DeclCache.find(D->getCanonicalDecl());
3054
30
3055
30
  if (
I != DeclCache.end()30
) {
3056
7
    auto N = I->second;
3057
7
    if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3058
4
      return GVE->getVariable();
3059
3
    return dyn_cast_or_null<llvm::DINode>(N);
3060
3
  }
3061
23
3062
23
  // No definition for now. Emit a forward definition that might be
3063
23
  // merged with a potential upcoming definition.
3064
23
  
if (const auto *23
FD23
= dyn_cast<FunctionDecl>(D))
3065
4
    return getFunctionForwardDeclaration(FD);
3066
19
  else 
if (const auto *19
VD19
= dyn_cast<VarDecl>(D))
3067
4
    return getGlobalVariableForwardDeclaration(VD);
3068
15
3069
15
  return nullptr;
3070
15
}
3071
3072
22.5k
llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
3073
22.5k
  if (
!D || 22.5k
DebugKind <= codegenoptions::DebugLineTablesOnly22.4k
)
3074
21.0k
    return nullptr;
3075
1.51k
3076
1.51k
  const auto *FD = dyn_cast<FunctionDecl>(D);
3077
1.51k
  if (!FD)
3078
328
    return nullptr;
3079
1.18k
3080
1.18k
  // Setup context.
3081
1.18k
  auto *S = getDeclContextDescriptor(D);
3082
1.18k
3083
1.18k
  auto MI = SPCache.find(FD->getCanonicalDecl());
3084
1.18k
  if (
MI == SPCache.end()1.18k
) {
3085
817
    if (const auto *
MD817
= dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
3086
246
      return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
3087
246
                                     cast<llvm::DICompositeType>(S));
3088
246
    }
3089
942
  }
3090
942
  
if (942
MI != SPCache.end()942
) {
3091
371
    auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3092
371
    if (
SP && 371
!SP->isDefinition()371
)
3093
371
      return SP;
3094
571
  }
3095
571
3096
571
  
for (auto NextFD : FD->redecls()) 571
{
3097
590
    auto MI = SPCache.find(NextFD->getCanonicalDecl());
3098
590
    if (
MI != SPCache.end()590
) {
3099
0
      auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3100
0
      if (
SP && 0
!SP->isDefinition()0
)
3101
0
        return SP;
3102
571
    }
3103
590
  }
3104
571
  return nullptr;
3105
571
}
3106
3107
// getOrCreateFunctionType - Construct type. If it is a c++ method, include
3108
// implicit parameter "this".
3109
llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
3110
                                                             QualType FnType,
3111
22.5k
                                                             llvm::DIFile *F) {
3112
22.5k
  if (
!D || 22.5k
DebugKind <= codegenoptions::DebugLineTablesOnly22.4k
)
3113
22.5k
    // Create fake but valid subroutine type. Otherwise -verify would fail, and
3114
22.5k
    // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
3115
21.0k
    return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
3116
1.51k
3117
1.51k
  
if (const auto *1.51k
Method1.51k
= dyn_cast<CXXMethodDecl>(D))
3118
617
    return getOrCreateMethodType(Method, F);
3119
899
3120
899
  const auto *FTy = FnType->getAs<FunctionType>();
3121
899
  CallingConv CC = FTy ? 
FTy->getCallConv()899
:
CallingConv::CC_C0
;
3122
899
3123
899
  if (const auto *
OMethod899
= dyn_cast<ObjCMethodDecl>(D)) {
3124
128
    // Add "self" and "_cmd"
3125
128
    SmallVector<llvm::Metadata *, 16> Elts;
3126
128
3127
128
    // First element is always return type. For 'void' functions it is NULL.
3128
128
    QualType ResultTy = OMethod->getReturnType();
3129
128
3130
128
    // Replace the instancetype keyword with the actual type.
3131
128
    if (ResultTy == CGM.getContext().getObjCInstanceType())
3132
1
      ResultTy = CGM.getContext().getPointerType(
3133
1
          QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
3134
128
3135
128
    Elts.push_back(getOrCreateType(ResultTy, F));
3136
128
    // "self" pointer is always first argument.
3137
128
    QualType SelfDeclTy;
3138
128
    if (auto *SelfDecl = OMethod->getSelfDecl())
3139
108
      SelfDeclTy = SelfDecl->getType();
3140
20
    else 
if (auto *20
FPT20
= dyn_cast<FunctionProtoType>(FnType))
3141
20
      
if (20
FPT->getNumParams() > 120
)
3142
20
        SelfDeclTy = FPT->getParamType(0);
3143
128
    if (!SelfDeclTy.isNull())
3144
128
      Elts.push_back(CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
3145
128
    // "_cmd" pointer is always second argument.
3146
128
    Elts.push_back(DBuilder.createArtificialType(
3147
128
        getOrCreateType(CGM.getContext().getObjCSelType(), F)));
3148
128
    // Get rest of the arguments.
3149
128
    for (const auto *PI : OMethod->parameters())
3150
58
      Elts.push_back(getOrCreateType(PI->getType(), F));
3151
128
    // Variadic methods need a special marker at the end of the type list.
3152
128
    if (OMethod->isVariadic())
3153
2
      Elts.push_back(DBuilder.createUnspecifiedParameter());
3154
128
3155
128
    llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
3156
128
    return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3157
128
                                         getDwarfCC(CC));
3158
128
  }
3159
771
3160
771
  // Handle variadic function types; they need an additional
3161
771
  // unspecified parameter.
3162
771
  
if (const auto *771
FD771
= dyn_cast<FunctionDecl>(D))
3163
571
    
if (571
FD->isVariadic()571
) {
3164
2
      SmallVector<llvm::Metadata *, 16> EltTys;
3165
2
      EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
3166
2
      if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3167
2
        for (QualType ParamType : FPT->param_types())
3168
2
          EltTys.push_back(getOrCreateType(ParamType, F));
3169
571
      EltTys.push_back(DBuilder.createUnspecifiedParameter());
3170
571
      llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
3171
571
      return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3172
571
                                           getDwarfCC(CC));
3173
571
    }
3174
769
3175
769
  return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
3176
769
}
3177
3178
void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
3179
                                    SourceLocation ScopeLoc, QualType FnType,
3180
22.4k
                                    llvm::Function *Fn, CGBuilderTy &Builder) {
3181
22.4k
3182
22.4k
  StringRef Name;
3183
22.4k
  StringRef LinkageName;
3184
22.4k
3185
22.4k
  FnBeginRegionCount.push_back(LexicalBlockStack.size());
3186
22.4k
3187
22.4k
  const Decl *D = GD.getDecl();
3188
22.4k
  bool HasDecl = (D != nullptr);
3189
22.4k
3190
22.4k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3191
22.4k
  llvm::DIFile *Unit = getOrCreateFile(Loc);
3192
22.4k
  llvm::DIScope *FDContext = Unit;
3193
22.4k
  llvm::DINodeArray TParamsArray;
3194
22.4k
  if (
!HasDecl22.4k
) {
3195
81
    // Use llvm function name.
3196
81
    LinkageName = Fn->getName();
3197
22.4k
  } else 
if (const auto *22.4k
FD22.4k
= dyn_cast<FunctionDecl>(D)) {
3198
22.0k
    // If there is a subprogram for this function available then use it.
3199
22.0k
    auto FI = SPCache.find(FD->getCanonicalDecl());
3200
22.0k
    if (
FI != SPCache.end()22.0k
) {
3201
324
      auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3202
324
      if (
SP && 324
SP->isDefinition()324
) {
3203
0
        LexicalBlockStack.emplace_back(SP);
3204
0
        RegionMap[D].reset(SP);
3205
0
        return;
3206
0
      }
3207
22.0k
    }
3208
22.0k
    collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3209
22.0k
                             TParamsArray, Flags);
3210
22.4k
  } else 
if (const auto *362
OMD362
= dyn_cast<ObjCMethodDecl>(D)) {
3211
110
    Name = getObjCMethodName(OMD);
3212
110
    Flags |= llvm::DINode::FlagPrototyped;
3213
362
  } else {
3214
252
    // Use llvm function name.
3215
252
    Name = Fn->getName();
3216
252
    Flags |= llvm::DINode::FlagPrototyped;
3217
252
  }
3218
22.4k
  
if (22.4k
Name.startswith("\01")22.4k
)
3219
7
    Name = Name.substr(1);
3220
22.4k
3221
22.4k
  if (
!HasDecl || 22.4k
D->isImplicit()22.4k
) {
3222
602
    Flags |= llvm::DINode::FlagArtificial;
3223
602
    // Artificial functions should not silently reuse CurLoc.
3224
602
    CurLoc = SourceLocation();
3225
602
  }
3226
22.4k
  unsigned LineNo = getLineNumber(Loc);
3227
22.4k
  unsigned ScopeLine = getLineNumber(ScopeLoc);
3228
22.4k
3229
22.4k
  // FIXME: The function declaration we're constructing here is mostly reusing
3230
22.4k
  // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3231
22.4k
  // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3232
22.4k
  // all subprograms instead of the actual context since subprogram definitions
3233
22.4k
  // are emitted as CU level entities by the backend.
3234
22.4k
  llvm::DISubprogram *SP = DBuilder.createFunction(
3235
22.4k
      FDContext, Name, LinkageName, Unit, LineNo,
3236
22.4k
      getOrCreateFunctionType(D, FnType, Unit), Fn->hasLocalLinkage(),
3237
22.4k
      true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
3238
22.4k
      TParamsArray.get(), getFunctionDeclaration(D));
3239
22.4k
  Fn->setSubprogram(SP);
3240
22.4k
  // We might get here with a VarDecl in the case we're generating
3241
22.4k
  // code for the initialization of globals. Do not record these decls
3242
22.4k
  // as they will overwrite the actual VarDecl Decl in the cache.
3243
22.4k
  if (
HasDecl && 22.4k
isa<FunctionDecl>(D)22.4k
)
3244
22.0k
    DeclCache[D->getCanonicalDecl()].reset(SP);
3245
22.4k
3246
22.4k
  // Push the function onto the lexical block stack.
3247
22.4k
  LexicalBlockStack.emplace_back(SP);
3248
22.4k
3249
22.4k
  if (HasDecl)
3250
22.4k
    RegionMap[D].reset(SP);
3251
22.4k
}
3252
3253
void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
3254
31
                                   QualType FnType) {
3255
31
  StringRef Name;
3256
31
  StringRef LinkageName;
3257
31
3258
31
  const Decl *D = GD.getDecl();
3259
31
  if (!D)
3260
0
    return;
3261
31
3262
31
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3263
31
  llvm::DIFile *Unit = getOrCreateFile(Loc);
3264
31
  llvm::DIScope *FDContext = getDeclContextDescriptor(D);
3265
31
  llvm::DINodeArray TParamsArray;
3266
31
  if (
isa<FunctionDecl>(D)31
) {
3267
11
    // If there is a DISubprogram for this function available then use it.
3268
11
    collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3269
11
                             TParamsArray, Flags);
3270
31
  } else 
if (const auto *20
OMD20
= dyn_cast<ObjCMethodDecl>(D)) {
3271
20
    Name = getObjCMethodName(OMD);
3272
20
    Flags |= llvm::DINode::FlagPrototyped;
3273
20
  } else {
3274
0
    llvm_unreachable("not a function or ObjC method");
3275
20
  }
3276
31
  
if (31
!Name.empty() && 31
Name[0] == '\01'31
)
3277
0
    Name = Name.substr(1);
3278
31
3279
31
  if (
D->isImplicit()31
) {
3280
0
    Flags |= llvm::DINode::FlagArtificial;
3281
0
    // Artificial functions without a location should not silently reuse CurLoc.
3282
0
    if (Loc.isInvalid())
3283
0
      CurLoc = SourceLocation();
3284
0
  }
3285
31
  unsigned LineNo = getLineNumber(Loc);
3286
31
  unsigned ScopeLine = 0;
3287
31
3288
31
  DBuilder.retainType(DBuilder.createFunction(
3289
31
      FDContext, Name, LinkageName, Unit, LineNo,
3290
31
      getOrCreateFunctionType(D, FnType, Unit), false /*internalLinkage*/,
3291
31
      false /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
3292
31
      TParamsArray.get(), getFunctionDeclaration(D)));
3293
31
}
3294
3295
3
void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
3296
3
  const auto *FD = cast<FunctionDecl>(GD.getDecl());
3297
3
  // If there is a subprogram for this function available then use it.
3298
3
  auto FI = SPCache.find(FD->getCanonicalDecl());
3299
3
  llvm::DISubprogram *SP = nullptr;
3300
3
  if (FI != SPCache.end())
3301
1
    SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3302
3
  if (
!SP || 3
!SP->isDefinition()1
)
3303
3
    SP = getFunctionStub(GD);
3304
3
  FnBeginRegionCount.push_back(LexicalBlockStack.size());
3305
3
  LexicalBlockStack.emplace_back(SP);
3306
3
  setInlinedAt(Builder.getCurrentDebugLocation());
3307
3
  EmitLocation(Builder, FD->getLocation());
3308
3
}
3309
3310
3
void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
3311
3
  assert(CurInlinedAt && "unbalanced inline scope stack");
3312
3
  EmitFunctionEnd(Builder, nullptr);
3313
3
  setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
3314
3
}
3315
3316
1.10M
void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
3317
1.10M
  // Update our current location
3318
1.10M
  setLocation(Loc);
3319
1.10M
3320
1.10M
  if (
CurLoc.isInvalid() || 1.10M
CurLoc.isMacroID()1.10M
)
3321
206
    return;
3322
1.10M
3323
1.10M
  llvm::MDNode *Scope = LexicalBlockStack.back();
3324
1.10M
  Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
3325
1.10M
      getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope, CurInlinedAt));
3326
1.10M
}
3327
3328
578
void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
3329
578
  llvm::MDNode *Back = nullptr;
3330
578
  if (!LexicalBlockStack.empty())
3331
578
    Back = LexicalBlockStack.back().get();
3332
578
  LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
3333
578
      cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
3334
578
      getColumnNumber(CurLoc)));
3335
578
}
3336
3337
void CGDebugInfo::AppendAddressSpaceXDeref(
3338
    unsigned AddressSpace,
3339
3.69k
    SmallVectorImpl<int64_t> &Expr) const {
3340
3.69k
  Optional<unsigned> DWARFAddressSpace =
3341
3.69k
      CGM.getTarget().getDWARFAddressSpace(AddressSpace);
3342
3.69k
  if (!DWARFAddressSpace)
3343
3.60k
    return;
3344
84
3345
84
  Expr.push_back(llvm::dwarf::DW_OP_constu);
3346
84
  Expr.push_back(DWARFAddressSpace.getValue());
3347
84
  Expr.push_back(llvm::dwarf::DW_OP_swap);
3348
84
  Expr.push_back(llvm::dwarf::DW_OP_xderef);
3349
84
}
3350
3351
void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
3352
42.0k
                                        SourceLocation Loc) {
3353
42.0k
  // Set our current location.
3354
42.0k
  setLocation(Loc);
3355
42.0k
3356
42.0k
  // Emit a line table change for the current location inside the new scope.
3357
42.0k
  Builder.SetCurrentDebugLocation(
3358
42.0k
      llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc),
3359
42.0k
                          LexicalBlockStack.back(), CurInlinedAt));
3360
42.0k
3361
42.0k
  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3362
41.4k
    return;
3363
578
3364
578
  // Create a new lexical block and push it on the stack.
3365
578
  CreateLexicalBlock(Loc);
3366
578
}
3367
3368
void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
3369
42.0k
                                      SourceLocation Loc) {
3370
42.0k
  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3371
42.0k
3372
42.0k
  // Provide an entry in the line table for the end of the block.
3373
42.0k
  EmitLocation(Builder, Loc);
3374
42.0k
3375
42.0k
  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3376
41.4k
    return;
3377
578
3378
578
  LexicalBlockStack.pop_back();
3379
578
}
3380
3381
22.4k
void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
3382
22.4k
  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3383
22.4k
  unsigned RCount = FnBeginRegionCount.back();
3384
22.4k
  assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
3385
22.4k
3386
22.4k
  // Pop all regions for this function.
3387
44.9k
  while (
LexicalBlockStack.size() != RCount44.9k
) {
3388
22.4k
    // Provide an entry in the line table for the end of the block.
3389
22.4k
    EmitLocation(Builder, CurLoc);
3390
22.4k
    LexicalBlockStack.pop_back();
3391
22.4k
  }
3392
22.4k
  FnBeginRegionCount.pop_back();
3393
22.4k
3394
22.4k
  if (
Fn && 22.4k
Fn->getSubprogram()22.4k
)
3395
22.4k
    DBuilder.finalizeSubprogram(Fn->getSubprogram());
3396
22.4k
}
3397
3398
llvm::DIType *CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
3399
28
                                                        uint64_t *XOffset) {
3400
28
3401
28
  SmallVector<llvm::Metadata *, 5> EltTys;
3402
28
  QualType FType;
3403
28
  uint64_t FieldSize, FieldOffset;
3404
28
  uint32_t FieldAlign;
3405
28
3406
28
  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3407
28
  QualType Type = VD->getType();
3408
28
3409
28
  FieldOffset = 0;
3410
28
  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3411
28
  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
3412
28
  EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
3413
28
  FType = CGM.getContext().IntTy;
3414
28
  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
3415
28
  EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
3416
28
3417
28
  bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
3418
28
  if (
HasCopyAndDispose28
) {
3419
0
    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3420
0
    EltTys.push_back(
3421
0
        CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
3422
0
    EltTys.push_back(
3423
0
        CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
3424
0
  }
3425
28
  bool HasByrefExtendedLayout;
3426
28
  Qualifiers::ObjCLifetime Lifetime;
3427
28
  if (CGM.getContext().getByrefLifetime(Type, Lifetime,
3428
28
                                        HasByrefExtendedLayout) &&
3429
28
      
HasByrefExtendedLayout16
) {
3430
1
    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3431
1
    EltTys.push_back(
3432
1
        CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
3433
1
  }
3434
28
3435
28
  CharUnits Align = CGM.getContext().getDeclAlign(VD);
3436
28
  if (Align > CGM.getContext().toCharUnitsFromBits(
3437
28
                  CGM.getTarget().getPointerAlign(0))) {
3438
0
    CharUnits FieldOffsetInBytes =
3439
0
        CGM.getContext().toCharUnitsFromBits(FieldOffset);
3440
0
    CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
3441
0
    CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
3442
0
3443
0
    if (
NumPaddingBytes.isPositive()0
) {
3444
0
      llvm::APInt pad(32, NumPaddingBytes.getQuantity());
3445
0
      FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
3446
0
                                                    pad, ArrayType::Normal, 0);
3447
0
      EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
3448
0
    }
3449
0
  }
3450
28
3451
28
  FType = Type;
3452
28
  llvm::DIType *FieldTy = getOrCreateType(FType, Unit);
3453
28
  FieldSize = CGM.getContext().getTypeSize(FType);
3454
28
  FieldAlign = CGM.getContext().toBits(Align);
3455
28
3456
28
  *XOffset = FieldOffset;
3457
28
  FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize,
3458
28
                                      FieldAlign, FieldOffset,
3459
28
                                      llvm::DINode::FlagZero, FieldTy);
3460
28
  EltTys.push_back(FieldTy);
3461
28
  FieldOffset += FieldSize;
3462
28
3463
28
  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3464
28
3465
28
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagBlockByrefStruct;
3466
28
3467
28
  return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
3468
28
                                   nullptr, Elements);
3469
28
}
3470
3471
void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::Value *Storage,
3472
                              llvm::Optional<unsigned> ArgNo,
3473
3.22k
                              CGBuilderTy &Builder) {
3474
3.22k
  assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3475
3.22k
  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3476
3.22k
  if (VD->hasAttr<NoDebugAttr>())
3477
2
    return;
3478
3.22k
3479
3.22k
  bool Unwritten =
3480
1.66k
      VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
3481
1.66k
                           cast<Decl>(VD->getDeclContext())->isImplicit());
3482
3.22k
  llvm::DIFile *Unit = nullptr;
3483
3.22k
  if (!Unwritten)
3484
1.62k
    Unit = getOrCreateFile(VD->getLocation());
3485
3.22k
  llvm::DIType *Ty;
3486
3.22k
  uint64_t XOffset = 0;
3487
3.22k
  if (VD->hasAttr<BlocksAttr>())
3488
10
    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
3489
3.22k
  else
3490
3.21k
    Ty = getOrCreateType(VD->getType(), Unit);
3491
3.22k
3492
3.22k
  // If there is no debug info for this type then do not emit debug info
3493
3.22k
  // for this variable.
3494
3.22k
  if (!Ty)
3495
0
    return;
3496
3.22k
3497
3.22k
  // Get location information.
3498
3.22k
  unsigned Line = 0;
3499
3.22k
  unsigned Column = 0;
3500
3.22k
  if (
!Unwritten3.22k
) {
3501
1.62k
    Line = getLineNumber(VD->getLocation());
3502
1.62k
    Column = getColumnNumber(VD->getLocation());
3503
1.62k
  }
3504
3.22k
  SmallVector<int64_t, 13> Expr;
3505
3.22k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3506
3.22k
  if (VD->isImplicit())
3507
1.55k
    Flags |= llvm::DINode::FlagArtificial;
3508
3.22k
3509
3.22k
  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3510
3.22k
3511
3.22k
  unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
3512
3.22k
  AppendAddressSpaceXDeref(AddressSpace, Expr);
3513
3.22k
3514
3.22k
  // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
3515
3.22k
  // object pointer flag.
3516
3.22k
  if (const auto *
IPD3.22k
= dyn_cast<ImplicitParamDecl>(VD)) {
3517
1.23k
    if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
3518
637
        IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
3519
703
      Flags |= llvm::DINode::FlagObjectPointer;
3520
1.23k
  }
3521
3.22k
3522
3.22k
  // Note: Older versions of clang used to emit byval references with an extra
3523
3.22k
  // DW_OP_deref, because they referenced the IR arg directly instead of
3524
3.22k
  // referencing an alloca. Newer versions of LLVM don't treat allocas
3525
3.22k
  // differently from other function arguments when used in a dbg.declare.
3526
3.22k
  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
3527
3.22k
  StringRef Name = VD->getName();
3528
3.22k
  if (
!Name.empty()3.22k
) {
3529
2.82k
    if (
VD->hasAttr<BlocksAttr>()2.82k
) {
3530
10
      // Here, we need an offset *into* the alloca.
3531
10
      CharUnits offset = CharUnits::fromQuantity(32);
3532
10
      Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3533
10
      // offset of __forwarding field
3534
10
      offset = CGM.getContext().toCharUnitsFromBits(
3535
10
          CGM.getTarget().getPointerWidth(0));
3536
10
      Expr.push_back(offset.getQuantity());
3537
10
      Expr.push_back(llvm::dwarf::DW_OP_deref);
3538
10
      Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3539
10
      // offset of x field
3540
10
      offset = CGM.getContext().toCharUnitsFromBits(XOffset);
3541
10
      Expr.push_back(offset.getQuantity());
3542
10
    }
3543
3.22k
  } else 
if (const auto *399
RT399
= dyn_cast<RecordType>(VD->getType())) {
3544
2
    // If VD is an anonymous union then Storage represents value for
3545
2
    // all union fields.
3546
2
    const auto *RD = cast<RecordDecl>(RT->getDecl());
3547
2
    if (
RD->isUnion() && 2
RD->isAnonymousStructOrUnion()1
) {
3548
1
      // GDB has trouble finding local variables in anonymous unions, so we emit
3549
1
      // artifical local variables for each of the members.
3550
1
      //
3551
1
      // FIXME: Remove this code as soon as GDB supports this.
3552
1
      // The debug info verifier in LLVM operates based on the assumption that a
3553
1
      // variable has the same size as its storage and we had to disable the check
3554
1
      // for artificial variables.
3555
2
      for (const auto *Field : RD->fields()) {
3556
2
        llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3557
2
        StringRef FieldName = Field->getName();
3558
2
3559
2
        // Ignore unnamed fields. Do not ignore unnamed records.
3560
2
        if (
FieldName.empty() && 2
!isa<RecordType>(Field->getType())0
)
3561
0
          continue;
3562
2
3563
2
        // Use VarDecl's Tag, Scope and Line number.
3564
2
        auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
3565
2
        auto *D = DBuilder.createAutoVariable(
3566
2
            Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
3567
2
            Flags | llvm::DINode::FlagArtificial, FieldAlign);
3568
2
3569
2
        // Insert an llvm.dbg.declare into the current block.
3570
2
        DBuilder.insertDeclare(
3571
2
            Storage, D, DBuilder.createExpression(Expr),
3572
2
            llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
3573
2
            Builder.GetInsertBlock());
3574
2
      }
3575
1
    }
3576
399
  }
3577
3.22k
3578
3.22k
  // Create the descriptor for the variable.
3579
3.22k
  auto *D = ArgNo
3580
2.10k
                ? DBuilder.createParameterVariable(
3581
2.10k
                      Scope, Name, *ArgNo, Unit, Line, Ty,
3582
2.10k
                      CGM.getLangOpts().Optimize, Flags)
3583
1.11k
                : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
3584
1.11k
                                              CGM.getLangOpts().Optimize, Flags,
3585
1.11k
                                              Align);
3586
3.22k
3587
3.22k
  // Insert an llvm.dbg.declare into the current block.
3588
3.22k
  DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
3589
3.22k
                         llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
3590
3.22k
                         Builder.GetInsertBlock());
3591
3.22k
}
3592
3593
void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
3594
                                            llvm::Value *Storage,
3595
1.11k
                                            CGBuilderTy &Builder) {
3596
1.11k
  assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3597
1.11k
  EmitDeclare(VD, Storage, llvm::None, Builder);
3598
1.11k
}
3599
3600
llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
3601
134
                                          llvm::DIType *Ty) {
3602
134
  llvm::DIType *CachedTy = getTypeOrNull(QualTy);
3603
134
  if (CachedTy)
3604
134
    Ty = CachedTy;
3605
134
  return DBuilder.createObjectPointerType(Ty);
3606
134
}
3607
3608
void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
3609
    const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
3610
29
    const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
3611
29
  assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3612
29
  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3613
29
3614
29
  if (Builder.GetInsertBlock() == nullptr)
3615
0
    return;
3616
29
  
if (29
VD->hasAttr<NoDebugAttr>()29
)
3617
1
    return;
3618
28
3619
28
  bool isByRef = VD->hasAttr<BlocksAttr>();
3620
28
3621
28
  uint64_t XOffset = 0;
3622
28
  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3623
28
  llvm::DIType *Ty;
3624
28
  if (isByRef)
3625
9
    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
3626
28
  else
3627
19
    Ty = getOrCreateType(VD->getType(), Unit);
3628
28
3629
28
  // Self is passed along as an implicit non-arg variable in a
3630
28
  // block. Mark it as the object pointer.
3631
28
  if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
3632
6
    
if (6
IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf6
)
3633
6
      Ty = CreateSelfType(VD->getType(), Ty);
3634
28
3635
28
  // Get location information.
3636
28
  unsigned Line = getLineNumber(VD->getLocation());
3637
28
  unsigned Column = getColumnNumber(VD->getLocation());
3638
28
3639
28
  const llvm::DataLayout &target = CGM.getDataLayout();
3640
28
3641
28
  CharUnits offset = CharUnits::fromQuantity(
3642
28
      target.getStructLayout(blockInfo.StructureType)
3643
28
          ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
3644
28
3645
28
  SmallVector<int64_t, 9> addr;
3646
28
  addr.push_back(llvm::dwarf::DW_OP_deref);
3647
28
  addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3648
28
  addr.push_back(offset.getQuantity());
3649
28
  if (
isByRef28
) {
3650
9
    addr.push_back(llvm::dwarf::DW_OP_deref);
3651
9
    addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3652
9
    // offset of __forwarding field
3653
9
    offset =
3654
9
        CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
3655
9
    addr.push_back(offset.getQuantity());
3656
9
    addr.push_back(llvm::dwarf::DW_OP_deref);
3657
9
    addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3658
9
    // offset of x field
3659
9
    offset = CGM.getContext().toCharUnitsFromBits(XOffset);
3660
9
    addr.push_back(offset.getQuantity());
3661
9
  }
3662
28
3663
28
  // Create the descriptor for the variable.
3664
28
  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3665
28
  auto *D = DBuilder.createAutoVariable(
3666
28
      cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
3667
28
      Line, Ty, false, llvm::DINode::FlagZero, Align);
3668
28
3669
28
  // Insert an llvm.dbg.declare into the current block.
3670
28
  auto DL =
3671
28
      llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back(), CurInlinedAt);
3672
28
  auto *Expr = DBuilder.createExpression(addr);
3673
28
  if (InsertPoint)
3674
27
    DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
3675
28
  else
3676
1
    DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
3677
29
}
3678
3679
void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
3680
                                           unsigned ArgNo,
3681
2.10k
                                           CGBuilderTy &Builder) {
3682
2.10k
  assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3683
2.10k
  EmitDeclare(VD, AI, ArgNo, Builder);
3684
2.10k
}
3685
3686
namespace {
3687
struct BlockLayoutChunk {
3688
  uint64_t OffsetInBits;
3689
  const BlockDecl::Capture *Capture;
3690
};
3691
20
bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
3692
20
  return l.OffsetInBits < r.OffsetInBits;
3693
20
}
3694
}
3695
3696
void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
3697
                                                       llvm::Value *Arg,
3698
                                                       unsigned ArgNo,
3699
                                                       llvm::Value *LocalAddr,
3700
28
                                                       CGBuilderTy &Builder) {
3701
28
  assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3702
28
  ASTContext &C = CGM.getContext();
3703
28
  const BlockDecl *blockDecl = block.getBlockDecl();
3704
28
3705
28
  // Collect some general information about the block's location.
3706
28
  SourceLocation loc = blockDecl->getCaretLocation();
3707
28
  llvm::DIFile *tunit = getOrCreateFile(loc);
3708
28
  unsigned line = getLineNumber(loc);
3709
28
  unsigned column = getColumnNumber(loc);
3710
28
3711
28
  // Build the debug-info type for the block literal.
3712
28
  getDeclContextDescriptor(blockDecl);
3713
28
3714
28
  const llvm::StructLayout *blockLayout =
3715
28
      CGM.getDataLayout().getStructLayout(block.StructureType);
3716
28
3717
28
  SmallVector<llvm::Metadata *, 16> fields;
3718
28
  fields.push_back(createFieldType("__isa", C.VoidPtrTy, loc, AS_public,
3719
28
                                   blockLayout->getElementOffsetInBits(0),
3720
28
                                   tunit, tunit));
3721
28
  fields.push_back(createFieldType("__flags", C.IntTy, loc, AS_public,
3722
28
                                   blockLayout->getElementOffsetInBits(1),
3723
28
                                   tunit, tunit));
3724
28
  fields.push_back(createFieldType("__reserved", C.IntTy, loc, AS_public,
3725
28
                                   blockLayout->getElementOffsetInBits(2),
3726
28
                                   tunit, tunit));
3727
28
  auto *FnTy = block.getBlockExpr()->getFunctionType();
3728
28
  auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
3729
28
  fields.push_back(createFieldType("__FuncPtr", FnPtrType, loc, AS_public,
3730
28
                                   blockLayout->getElementOffsetInBits(3),
3731
28
                                   tunit, tunit));
3732
28
  fields.push_back(createFieldType(
3733
28
      "__descriptor", C.getPointerType(block.NeedsCopyDispose
3734
17
                                           ? C.getBlockDescriptorExtendedType()
3735
11
                                           : C.getBlockDescriptorType()),
3736
28
      loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit));
3737
28
3738
28
  // We want to sort the captures by offset, not because DWARF
3739
28
  // requires this, but because we're paranoid about debuggers.
3740
28
  SmallVector<BlockLayoutChunk, 8> chunks;
3741
28
3742
28
  // 'this' capture.
3743
28
  if (
blockDecl->capturesCXXThis()28
) {
3744
1
    BlockLayoutChunk chunk;
3745
1
    chunk.OffsetInBits =
3746
1
        blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3747
1
    chunk.Capture = nullptr;
3748
1
    chunks.push_back(chunk);
3749
1
  }
3750
28
3751
28
  // Variable captures.
3752
29
  for (const auto &capture : blockDecl->captures()) {
3753
29
    const VarDecl *variable = capture.getVariable();
3754
29
    const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3755
29
3756
29
    // Ignore constant captures.
3757
29
    if (captureInfo.isConstant())
3758
0
      continue;
3759
29
3760
29
    BlockLayoutChunk chunk;
3761
29
    chunk.OffsetInBits =
3762
29
        blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3763
29
    chunk.Capture = &capture;
3764
29
    chunks.push_back(chunk);
3765
29
  }
3766
28
3767
28
  // Sort by offset.
3768
28
  llvm::array_pod_sort(chunks.begin(), chunks.end());
3769
28
3770
30
  for (const BlockLayoutChunk &Chunk : chunks) {
3771
30
    uint64_t offsetInBits = Chunk.OffsetInBits;
3772
30
    const BlockDecl::Capture *capture = Chunk.Capture;
3773
30
3774
30
    // If we have a null capture, this must be the C++ 'this' capture.
3775
30
    if (
!capture30
) {
3776
1
      QualType type;
3777
1
      if (auto *Method =
3778
1
              cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
3779
0
        type = Method->getThisType(C);
3780
1
      else 
if (auto *1
RDecl1
= dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
3781
1
        type = QualType(RDecl->getTypeForDecl(), 0);
3782
1
      else
3783
0
        llvm_unreachable("unexpected block declcontext");
3784
1
3785
1
      fields.push_back(createFieldType("this", type, loc, AS_public,
3786
1
                                       offsetInBits, tunit, tunit));
3787
1
      continue;
3788
29
    }
3789
29
3790
29
    const VarDecl *variable = capture->getVariable();
3791
29
    StringRef name = variable->getName();
3792
29
3793
29
    llvm::DIType *fieldType;
3794
29
    if (
capture->isByRef()29
) {
3795
9
      TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
3796
9
      auto Align = PtrInfo.AlignIsRequired ? 
PtrInfo.Align0
:
09
;
3797
9
3798
9
      // FIXME: this creates a second copy of this type!
3799
9
      uint64_t xoffset;
3800
9
      fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3801
9
      fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
3802
9
      fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3803
9
                                            PtrInfo.Width, Align, offsetInBits,
3804
9
                                            llvm::DINode::FlagZero, fieldType);
3805
29
    } else {
3806
20
      auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
3807
20
      fieldType = createFieldType(name, variable->getType(), loc, AS_public,
3808
20
                                  offsetInBits, Align, tunit, tunit);
3809
20
    }
3810
30
    fields.push_back(fieldType);
3811
30
  }
3812
28
3813
28
  SmallString<36> typeName;
3814
28
  llvm::raw_svector_ostream(typeName) << "__block_literal_"
3815
28
                                      << CGM.getUniqueBlockCount();
3816
28
3817
28
  llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
3818
28
3819
28
  llvm::DIType *type =
3820
28
      DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3821
28
                                CGM.getContext().toBits(block.BlockSize), 0,
3822
28
                                llvm::DINode::FlagZero, nullptr, fieldsArray);
3823
28
  type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3824
28
3825
28
  // Get overall information about the block.
3826
28
  llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
3827
28
  auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
3828
28
3829
28
  // Create the descriptor for the parameter.
3830
28
  auto *debugVar = DBuilder.createParameterVariable(
3831
28
      scope, Arg->getName(), ArgNo, tunit, line, type,
3832
28
      CGM.getLangOpts().Optimize, flags);
3833
28
3834
28
  if (
LocalAddr28
) {
3835
28
    // Insert an llvm.dbg.value into the current block.
3836
28
    DBuilder.insertDbgValueIntrinsic(
3837
28
        LocalAddr, debugVar, DBuilder.createExpression(),
3838
28
        llvm::DebugLoc::get(line, column, scope, CurInlinedAt),
3839
28
        Builder.GetInsertBlock());
3840
28
  }
3841
28
3842
28
  // Insert an llvm.dbg.declare into the current block.
3843
28
  DBuilder.insertDeclare(Arg, debugVar, DBuilder.createExpression(),
3844
28
                         llvm::DebugLoc::get(line, column, scope, CurInlinedAt),
3845
28
                         Builder.GetInsertBlock());
3846
28
}
3847
3848
llvm::DIDerivedType *
3849
483
CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3850
483
  if (!D->isStaticDataMember())
3851
450
    return nullptr;
3852
33
3853
33
  auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
3854
33
  if (
MI != StaticDataMemberCache.end()33
) {
3855
11
    assert(MI->second && "Static data member declaration should still exist");
3856
11
    return MI->second;
3857
11
  }
3858
22
3859
22
  // If the member wasn't found in the cache, lazily construct and add it to the
3860
22
  // type (used when a limited form of the type is emitted).
3861
22
  auto DC = D->getDeclContext();
3862
22
  auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
3863
22
  return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
3864
22
}
3865
3866
llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
3867
    const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
3868
4
    StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
3869
4
  llvm::DIGlobalVariableExpression *GVE = nullptr;
3870
4
3871
8
  for (const auto *Field : RD->fields()) {
3872
8
    llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3873
8
    StringRef FieldName = Field->getName();
3874
8
3875
8
    // Ignore unnamed fields, but recurse into anonymous records.
3876
8
    if (
FieldName.empty()8
) {
3877
2
      if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
3878
2
        GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
3879
2
                                    Var, DContext);
3880
2
      continue;
3881
2
    }
3882
6
    // Use VarDecl's Tag, Scope and Line number.
3883
6
    GVE = DBuilder.createGlobalVariableExpression(
3884
6
        DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
3885
6
        Var->hasLocalLinkage());
3886
6
    Var->addDebugInfo(GVE);
3887
6
  }
3888
4
  return GVE;
3889
4
}
3890
3891
void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3892
475
                                     const VarDecl *D) {
3893
475
  assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3894
475
  if (D->hasAttr<NoDebugAttr>())
3895
4
    return;
3896
471
3897
471
  // If we already created a DIGlobalVariable for this declaration, just attach
3898
471
  // it to the llvm::GlobalVariable.
3899
471
  auto Cached = DeclCache.find(D->getCanonicalDecl());
3900
471
  if (Cached != DeclCache.end())
3901
3
    return Var->addDebugInfo(
3902
3
        cast<llvm::DIGlobalVariableExpression>(Cached->second));
3903
468
3904
468
  // Create global variable debug descriptor.
3905
468
  llvm::DIFile *Unit = nullptr;
3906
468
  llvm::DIScope *DContext = nullptr;
3907
468
  unsigned LineNo;
3908
468
  StringRef DeclName, LinkageName;
3909
468
  QualType T;
3910
468
  collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext);
3911
468
3912
468
  // Attempt to store one global variable for the declaration - even if we
3913
468
  // emit a lot of fields.
3914
468
  llvm::DIGlobalVariableExpression *GVE = nullptr;
3915
468
3916
468
  // If this is an anonymous union then we'll want to emit a global
3917
468
  // variable for each member of the anonymous union so that it's possible
3918
468
  // to find the name of any field in the union.
3919
468
  if (
T->isUnionType() && 468
DeclName.empty()20
) {
3920
2
    const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
3921
2
    assert(RD->isAnonymousStructOrUnion() &&
3922
2
           "unnamed non-anonymous struct or union?");
3923
2
    GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
3924
468
  } else {
3925
466
    auto Align = getDeclAlignIfRequired(D, CGM.getContext());
3926
466
3927
466
    SmallVector<int64_t, 4> Expr;
3928
466
    unsigned AddressSpace =
3929
466
        CGM.getContext().getTargetAddressSpace(D->getType());
3930
466
    AppendAddressSpaceXDeref(AddressSpace, Expr);
3931
466
3932
466
    GVE = DBuilder.createGlobalVariableExpression(
3933
466
        DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3934
466
        Var->hasLocalLinkage(),
3935
466
        Expr.empty() ? 
nullptr446
:
DBuilder.createExpression(Expr)20
,
3936
466
        getOrCreateStaticDataMemberDeclarationOrNull(D), Align);
3937
466
    Var->addDebugInfo(GVE);
3938
466
  }
3939
475
  DeclCache[D->getCanonicalDecl()].reset(GVE);
3940
475
}
3941
3942
65
void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
3943
65
  assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3944
65
  if (VD->hasAttr<NoDebugAttr>())
3945
2
    return;
3946
63
  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3947
63
  // Create the descriptor for the variable.
3948
63
  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3949
63
  StringRef Name = VD->getName();
3950
63
  llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
3951
63
  if (const auto *
ECD63
= dyn_cast<EnumConstantDecl>(VD)) {
3952
30
    const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
3953
30
    assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3954
30
    Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3955
30
  }
3956
63
  // Do not use global variables for enums.
3957
63
  //
3958
63
  // FIXME: why not?
3959
63
  if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3960
30
    return;
3961
33
  // Do not emit separate definitions for function local const/statics.
3962
33
  
if (33
isa<FunctionDecl>(VD->getDeclContext())33
)
3963
2
    return;
3964
31
  VD = cast<ValueDecl>(VD->getCanonicalDecl());
3965
31
  auto *VarD = cast<VarDecl>(VD);
3966
31
  if (
VarD->isStaticDataMember()31
) {
3967
13
    auto *RD = cast<RecordDecl>(VarD->getDeclContext());
3968
13
    getDeclContextDescriptor(VarD);
3969
13
    // Ensure that the type is retained even though it's otherwise unreferenced.
3970
13
    //
3971
13
    // FIXME: This is probably unnecessary, since Ty should reference RD
3972
13
    // through its scope.
3973
13
    RetainedTypes.push_back(
3974
13
        CGM.getContext().getRecordType(RD).getAsOpaquePtr());
3975
13
    return;
3976
13
  }
3977
18
3978
18
  llvm::DIScope *DContext = getDeclContextDescriptor(VD);
3979
18
3980
18
  auto &GV = DeclCache[VD];
3981
18
  if (GV)
3982
1
    return;
3983
17
  llvm::DIExpression *InitExpr = nullptr;
3984
17
  if (
CGM.getContext().getTypeSize(VD->getType()) <= 6417
) {
3985
14
    // FIXME: Add a representation for integer constants wider than 64 bits.
3986
14
    if (Init.isInt())
3987
4
      InitExpr =
3988
4
          DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
3989
10
    else 
if (10
Init.isFloat()10
)
3990
10
      InitExpr = DBuilder.createConstantValueExpression(
3991
10
          Init.getFloat().bitcastToAPInt().getZExtValue());
3992
14
  }
3993
65
  GV.reset(DBuilder.createGlobalVariableExpression(
3994
65
      DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
3995
65
      true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
3996
65
      Align));
3997
65
}
3998
3999
48
llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
4000
48
  if (!LexicalBlockStack.empty())
4001
26
    return LexicalBlockStack.back();
4002
22
  llvm::DIScope *Mod = getParentModuleOrNull(D);
4003
22
  return getContextDescriptor(D, Mod ? 
Mod0
:
TheCU22
);
4004
48
}
4005
4006
6.19k
void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
4007
6.19k
  if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
4008
6.16k
    return;
4009
22
  const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
4010
22
  if (!NSDecl->isAnonymousNamespace() ||
4011
22
      
CGM.getCodeGenOpts().DebugExplicitImport13
) {
4012
11
    auto Loc = UD.getLocation();
4013
11
    DBuilder.createImportedModule(
4014
11
        getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
4015
11
        getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
4016
11
  }
4017
6.19k
}
4018
4019
78
void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
4020
78
  if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
4021
37
    return;
4022
78
  assert(UD.shadow_size() &&
4023
41
         "We shouldn't be codegening an invalid UsingDecl containing no decls");
4024
41
  // Emitting one decl is sufficient - debuggers can detect that this is an
4025
41
  // overloaded name & provide lookup for all the overloads.
4026
41
  const UsingShadowDecl &USD = **UD.shadow_begin();
4027
41
4028
41
  // FIXME: Skip functions with undeduced auto return type for now since we
4029
41
  // don't currently have the plumbing for separate declarations & definitions
4030
41
  // of free functions and mismatched types (auto in the declaration, concrete
4031
41
  // return type in the definition)
4032
41
  if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
4033
8
    
if (const auto *8
AT8
=
4034
8
            FD->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
4035
2
      
if (2
AT->getDeducedType().isNull()2
)
4036
1
        return;
4037
40
  
if (llvm::DINode *40
Target40
=
4038
25
          getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
4039
25
    auto Loc = USD.getLocation();
4040
25
    DBuilder.createImportedDeclaration(
4041
25
        getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
4042
25
        getOrCreateFile(Loc), getLineNumber(Loc));
4043
25
  }
4044
78
}
4045
4046
20
void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
4047
20
  if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
4048
14
    return;
4049
6
  
if (Module *6
M6
= ID.getImportedModule()) {
4050
6
    auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
4051
6
    auto Loc = ID.getLocation();
4052
6
    DBuilder.createImportedDeclaration(
4053
6
        getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
4054
6
        getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
4055
6
        getLineNumber(Loc));
4056
6
  }
4057
20
}
4058
4059
llvm::DIImportedEntity *
4060
11
CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
4061
11
  if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
4062
3
    return nullptr;
4063
8
  auto &VH = NamespaceAliasCache[&NA];
4064
8
  if (VH)
4065
2
    return cast<llvm::DIImportedEntity>(VH);
4066
6
  llvm::DIImportedEntity *R;
4067
6
  auto Loc = NA.getLocation();
4068
6
  if (const auto *Underlying =
4069
6
          dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
4070
6
    // This could cache & dedup here rather than relying on metadata deduping.
4071
2
    R = DBuilder.createImportedDeclaration(
4072
2
        getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4073
2
        EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
4074
2
        getLineNumber(Loc), NA.getName());
4075
6
  else
4076
4
    R = DBuilder.createImportedDeclaration(
4077
4
        getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4078
4
        getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
4079
4
        getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
4080
11
  VH.reset(R);
4081
11
  return R;
4082
11
}
4083
4084
llvm::DINamespace *
4085
359
CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
4086
359
  // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
4087
359
  // if necessary, and this way multiple declarations of the same namespace in
4088
359
  // different parent modules stay distinct.
4089
359
  auto I = NamespaceCache.find(NSDecl);
4090
359
  if (I != NamespaceCache.end())
4091
239
    return cast<llvm::DINamespace>(I->second);
4092
120
4093
120
  llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
4094
120
  // Don't trust the context if it is a DIModule (see comment above).
4095
120
  llvm::DINamespace *NS =
4096
120
      DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
4097
120
  NamespaceCache[NSDecl].reset(NS);
4098
120
  return NS;
4099
120
}
4100
4101
22
void CGDebugInfo::setDwoId(uint64_t Signature) {
4102
22
  assert(TheCU && "no main compile unit");
4103
22
  TheCU->setDWOId(Signature);
4104
22
}
4105
4106
4107
1.32k
void CGDebugInfo::finalize() {
4108
1.32k
  // Creating types might create further types - invalidating the current
4109
1.32k
  // element and the size(), so don't cache/reference them.
4110
1.40k
  for (size_t i = 0; 
i != ObjCInterfaceCache.size()1.40k
;
++i85
) {
4111
85
    ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
4112
85
    llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
4113
70
                           ? CreateTypeDefinition(E.Type, E.Unit)
4114
15
                           : E.Decl;
4115
85
    DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
4116
85
  }
4117
1.32k
4118
313
  for (auto p : ReplaceMap) {
4119
313
    assert(p.second);
4120
313
    auto *Ty = cast<llvm::DIType>(p.second);
4121
313
    assert(Ty->isForwardDecl());
4122
313
4123
313
    auto it = TypeCache.find(p.first);
4124
313
    assert(it != TypeCache.end());
4125
313
    assert(it->second);
4126
313
4127
313
    DBuilder.replaceTemporary(llvm::TempDIType(Ty),
4128
313
                              cast<llvm::DIType>(it->second));
4129
313
  }
4130
1.32k
4131
8
  for (const auto &p : FwdDeclReplaceMap) {
4132
8
    assert(p.second);
4133
8
    llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(p.second));
4134
8
    llvm::Metadata *Repl;
4135
8
4136
8
    auto it = DeclCache.find(p.first);
4137
8
    // If there has been no definition for the declaration, call RAUW
4138
8
    // with ourselves, that will destroy the temporary MDNode and
4139
8
    // replace it with a standard one, avoiding leaking memory.
4140
8
    if (it == DeclCache.end())
4141
4
      Repl = p.second;
4142
8
    else
4143
4
      Repl = it->second;
4144
8
4145
8
    if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
4146
2
      Repl = GVE->getVariable();
4147
8
    DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
4148
8
  }
4149
1.32k
4150
1.32k
  // We keep our own list of retained types, because we need to look
4151
1.32k
  // up the final type in the type cache.
4152
1.32k
  for (auto &RT : RetainedTypes)
4153
254
    
if (auto 254
MD254
= TypeCache[RT])
4154
254
      DBuilder.retainType(cast<llvm::DIType>(MD));
4155
1.32k
4156
1.32k
  DBuilder.finalize();
4157
1.32k
}
4158
4159
14.4k
void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
4160
14.4k
  if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
4161
14.3k
    return;
4162
91
4163
91
  
if (auto *91
DieTy91
= getOrCreateType(Ty, getOrCreateMainFile()))
4164
91
    // Don't ignore in case of explicit cast where it is referenced indirectly.
4165
72
    DBuilder.retainType(DieTy);
4166
14.4k
}
4167
4168
17.4k
llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
4169
17.4k
  if (LexicalBlockStack.empty())
4170
0
    return llvm::DebugLoc();
4171
17.4k
4172
17.4k
  llvm::MDNode *Scope = LexicalBlockStack.back();
4173
17.4k
  return llvm::DebugLoc::get(
4174
17.4k
          getLineNumber(Loc), getColumnNumber(Loc), Scope);
4175
17.4k
}