Coverage Report

Created: 2020-09-15 12:33

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp
<
Line
Count
Source (jump to first uncovered line)
1
//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements semantic analysis for C++ declarations.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/ASTConsumer.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/ASTLambda.h"
16
#include "clang/AST/ASTMutationListener.h"
17
#include "clang/AST/CXXInheritance.h"
18
#include "clang/AST/CharUnits.h"
19
#include "clang/AST/ComparisonCategories.h"
20
#include "clang/AST/EvaluatedExprVisitor.h"
21
#include "clang/AST/ExprCXX.h"
22
#include "clang/AST/RecordLayout.h"
23
#include "clang/AST/RecursiveASTVisitor.h"
24
#include "clang/AST/StmtVisitor.h"
25
#include "clang/AST/TypeLoc.h"
26
#include "clang/AST/TypeOrdering.h"
27
#include "clang/Basic/AttributeCommonInfo.h"
28
#include "clang/Basic/PartialDiagnostic.h"
29
#include "clang/Basic/TargetInfo.h"
30
#include "clang/Lex/LiteralSupport.h"
31
#include "clang/Lex/Preprocessor.h"
32
#include "clang/Sema/CXXFieldCollector.h"
33
#include "clang/Sema/DeclSpec.h"
34
#include "clang/Sema/Initialization.h"
35
#include "clang/Sema/Lookup.h"
36
#include "clang/Sema/ParsedTemplate.h"
37
#include "clang/Sema/Scope.h"
38
#include "clang/Sema/ScopeInfo.h"
39
#include "clang/Sema/SemaInternal.h"
40
#include "clang/Sema/Template.h"
41
#include "llvm/ADT/ScopeExit.h"
42
#include "llvm/ADT/SmallString.h"
43
#include "llvm/ADT/STLExtras.h"
44
#include "llvm/ADT/StringExtras.h"
45
#include <map>
46
#include <set>
47
48
using namespace clang;
49
50
//===----------------------------------------------------------------------===//
51
// CheckDefaultArgumentVisitor
52
//===----------------------------------------------------------------------===//
53
54
namespace {
55
/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
56
/// the default argument of a parameter to determine whether it
57
/// contains any ill-formed subexpressions. For example, this will
58
/// diagnose the use of local variables or parameters within the
59
/// default argument expression.
60
class CheckDefaultArgumentVisitor
61
    : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
62
  Sema &S;
63
  const Expr *DefaultArg;
64
65
public:
66
  CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
67
79.2k
      : S(S), DefaultArg(DefaultArg) {}
68
69
  bool VisitExpr(const Expr *Node);
70
  bool VisitDeclRefExpr(const DeclRefExpr *DRE);
71
  bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
72
  bool VisitLambdaExpr(const LambdaExpr *Lambda);
73
  bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
74
};
75
76
/// VisitExpr - Visit all of the children of this expression.
77
85.5k
bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
78
85.5k
  bool IsInvalid = false;
79
85.5k
  for (const Stmt *SubStmt : Node->children())
80
33.7k
    IsInvalid |= Visit(SubStmt);
81
85.5k
  return IsInvalid;
82
85.5k
}
83
84
/// VisitDeclRefExpr - Visit a reference to a declaration, to
85
/// determine whether this declaration can be used in the default
86
/// argument expression.
87
27.1k
bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
88
27.1k
  const NamedDecl *Decl = DRE->getDecl();
89
27.1k
  if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
90
    // C++ [dcl.fct.default]p9:
91
    //   [...] parameters of a function shall not be used in default
92
    //   argument expressions, even if they are not evaluated. [...]
93
    //
94
    // C++17 [dcl.fct.default]p9 (by CWG 2082):
95
    //   [...] A parameter shall not appear as a potentially-evaluated
96
    //   expression in a default argument. [...]
97
    //
98
18
    if (DRE->isNonOdrUse() != NOUR_Unevaluated)
99
12
      return S.Diag(DRE->getBeginLoc(),
100
12
                    diag::err_param_default_argument_references_param)
101
12
             << Param->getDeclName() << DefaultArg->getSourceRange();
102
27.1k
  } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
103
    // C++ [dcl.fct.default]p7:
104
    //   Local variables shall not be used in default argument
105
    //   expressions.
106
    //
107
    // C++17 [dcl.fct.default]p7 (by CWG 2082):
108
    //   A local variable shall not appear as a potentially-evaluated
109
    //   expression in a default argument.
110
    //
111
    // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
112
    //   Note: A local variable cannot be odr-used (6.3) in a default argument.
113
    //
114
12.0k
    if (VDecl->isLocalVarDecl() && 
!DRE->isNonOdrUse()12
)
115
4
      return S.Diag(DRE->getBeginLoc(),
116
4
                    diag::err_param_default_argument_references_local)
117
4
             << VDecl->getDeclName() << DefaultArg->getSourceRange();
118
27.1k
  }
119
27.1k
120
27.1k
  return false;
121
27.1k
}
122
123
/// VisitCXXThisExpr - Visit a C++ "this" expression.
124
7
bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
125
  // C++ [dcl.fct.default]p8:
126
  //   The keyword this shall not be used in a default argument of a
127
  //   member function.
128
7
  return S.Diag(ThisE->getBeginLoc(),
129
7
                diag::err_param_default_argument_references_this)
130
7
         << ThisE->getSourceRange();
131
7
}
132
133
bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
134
1
    const PseudoObjectExpr *POE) {
135
1
  bool Invalid = false;
136
2
  for (const Expr *E : POE->semantics()) {
137
    // Look through bindings.
138
2
    if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
139
1
      E = OVE->getSourceExpr();
140
1
      assert(E && "pseudo-object binding without source expression?");
141
1
    }
142
2
143
2
    Invalid |= Visit(E);
144
2
  }
145
1
  return Invalid;
146
1
}
147
148
260
bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
149
  // C++11 [expr.lambda.prim]p13:
150
  //   A lambda-expression appearing in a default argument shall not
151
  //   implicitly or explicitly capture any entity.
152
260
  if (Lambda->capture_begin() == Lambda->capture_end())
153
257
    return false;
154
3
155
3
  return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
156
3
}
157
} // namespace
158
159
void
160
Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
161
61.8k
                                                 const CXXMethodDecl *Method) {
162
  // If we have an MSAny spec already, don't bother.
163
61.8k
  if (!Method || ComputedEST == EST_MSAny)
164
0
    return;
165
61.8k
166
61.8k
  const FunctionProtoType *Proto
167
61.8k
    = Method->getType()->getAs<FunctionProtoType>();
168
61.8k
  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
169
61.8k
  if (!Proto)
170
1
    return;
171
61.8k
172
61.8k
  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
173
61.8k
174
  // If we have a throw-all spec at this point, ignore the function.
175
61.8k
  if (ComputedEST == EST_None)
176
392
    return;
177
61.4k
178
61.4k
  if (EST == EST_None && 
Method->hasAttr<NoThrowAttr>()1.15k
)
179
0
    EST = EST_BasicNoexcept;
180
61.4k
181
61.4k
  switch (EST) {
182
0
  case EST_Unparsed:
183
0
  case EST_Uninstantiated:
184
0
  case EST_Unevaluated:
185
0
    llvm_unreachable("should not see unresolved exception specs here");
186
0
187
  // If this function can throw any exceptions, make a note of that.
188
1.15k
  case EST_MSAny:
189
1.15k
  case EST_None:
190
    // FIXME: Whichever we see last of MSAny and None determines our result.
191
    // We should make a consistent, order-independent choice here.
192
1.15k
    ClearExceptions();
193
1.15k
    ComputedEST = EST;
194
1.15k
    return;
195
276
  case EST_NoexceptFalse:
196
276
    ClearExceptions();
197
276
    ComputedEST = EST_None;
198
276
    return;
199
  // FIXME: If the call to this decl is using any of its default arguments, we
200
  // need to search them for potentially-throwing calls.
201
  // If this function has a basic noexcept, it doesn't affect the outcome.
202
59.3k
  case EST_BasicNoexcept:
203
59.3k
  case EST_NoexceptTrue:
204
59.3k
  case EST_NoThrow:
205
59.3k
    return;
206
  // If we're still at noexcept(true) and there's a throw() callee,
207
  // change to that specification.
208
657
  case EST_DynamicNone:
209
657
    if (ComputedEST == EST_BasicNoexcept)
210
15
      ComputedEST = EST_DynamicNone;
211
657
    return;
212
0
  case EST_DependentNoexcept:
213
0
    llvm_unreachable(
214
59.3k
        "should not generate implicit declarations for dependent cases");
215
24
  case EST_Dynamic:
216
24
    break;
217
24
  }
218
24
  assert(EST == EST_Dynamic && "EST case not considered earlier.");
219
24
  assert(ComputedEST != EST_None &&
220
24
         "Shouldn't collect exceptions when throw-all is guaranteed.");
221
24
  ComputedEST = EST_Dynamic;
222
  // Record the exceptions in this function's exception specification.
223
24
  for (const auto &E : Proto->exceptions())
224
24
    if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
225
24
      Exceptions.push_back(E);
226
24
}
227
228
1.12k
void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
229
1.12k
  if (!S || ComputedEST == EST_MSAny)
230
0
    return;
231
1.12k
232
  // FIXME:
233
  //
234
  // C++0x [except.spec]p14:
235
  //   [An] implicit exception-specification specifies the type-id T if and
236
  // only if T is allowed by the exception-specification of a function directly
237
  // invoked by f's implicit definition; f shall allow all exceptions if any
238
  // function it directly invokes allows all exceptions, and f shall allow no
239
  // exceptions if every function it directly invokes allows no exceptions.
240
  //
241
  // Note in particular that if an implicit exception-specification is generated
242
  // for a function containing a throw-expression, that specification can still
243
  // be noexcept(true).
244
  //
245
  // Note also that 'directly invoked' is not defined in the standard, and there
246
  // is no indication that we should only consider potentially-evaluated calls.
247
  //
248
  // Ultimately we should implement the intent of the standard: the exception
249
  // specification should be the set of exceptions which can be thrown by the
250
  // implicit definition. For now, we assume that any non-nothrow expression can
251
  // throw any exception.
252
1.12k
253
1.12k
  if (Self->canThrow(S))
254
221
    ComputedEST = EST_None;
255
1.12k
}
256
257
ExprResult Sema::ConvertParamDefaultArgument(const ParmVarDecl *Param,
258
                                             Expr *Arg,
259
79.3k
                                             SourceLocation EqualLoc) {
260
79.3k
  if (RequireCompleteType(Param->getLocation(), Param->getType(),
261
79.3k
                          diag::err_typecheck_decl_incomplete_type))
262
18
    return true;
263
79.3k
264
  // C++ [dcl.fct.default]p5
265
  //   A default argument expression is implicitly converted (clause
266
  //   4) to the parameter type. The default argument expression has
267
  //   the same semantic constraints as the initializer expression in
268
  //   a declaration of a variable of the parameter type, using the
269
  //   copy-initialization semantics (8.5).
270
79.3k
  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
271
79.3k
                                                                    Param);
272
79.3k
  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
273
79.3k
                                                           EqualLoc);
274
79.3k
  InitializationSequence InitSeq(*this, Entity, Kind, Arg);
275
79.3k
  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
276
79.3k
  if (Result.isInvalid())
277
36
    return true;
278
79.3k
  Arg = Result.getAs<Expr>();
279
79.3k
280
79.3k
  CheckCompletedExpr(Arg, EqualLoc);
281
79.3k
  Arg = MaybeCreateExprWithCleanups(Arg);
282
79.3k
283
79.3k
  return Arg;
284
79.3k
}
285
286
void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
287
79.2k
                                   SourceLocation EqualLoc) {
288
  // Add the default argument to the parameter
289
79.2k
  Param->setDefaultArg(Arg);
290
79.2k
291
  // We have already instantiated this parameter; provide each of the
292
  // instantiations with the uninstantiated default argument.
293
79.2k
  UnparsedDefaultArgInstantiationsMap::iterator InstPos
294
79.2k
    = UnparsedDefaultArgInstantiations.find(Param);
295
79.2k
  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
296
8
    for (unsigned I = 0, N = InstPos->second.size(); I != N; 
++I5
)
297
5
      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
298
3
299
    // We're done tracking this parameter's instantiations.
300
3
    UnparsedDefaultArgInstantiations.erase(InstPos);
301
3
  }
302
79.2k
}
303
304
/// ActOnParamDefaultArgument - Check whether the default argument
305
/// provided for a function parameter is well-formed. If so, attach it
306
/// to the parameter declaration.
307
void
308
Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
309
79.3k
                                Expr *DefaultArg) {
310
79.3k
  if (!param || !DefaultArg)
311
0
    return;
312
79.3k
313
79.3k
  ParmVarDecl *Param = cast<ParmVarDecl>(param);
314
79.3k
  UnparsedDefaultArgLocs.erase(Param);
315
79.3k
316
87
  auto Fail = [&] {
317
87
    Param->setInvalidDecl();
318
87
    Param->setDefaultArg(new (Context) OpaqueValueExpr(
319
87
        EqualLoc, Param->getType().getNonReferenceType(), VK_RValue));
320
87
  };
321
79.3k
322
  // Default arguments are only permitted in C++
323
79.3k
  if (!getLangOpts().CPlusPlus) {
324
1
    Diag(EqualLoc, diag::err_param_default_argument)
325
1
      << DefaultArg->getSourceRange();
326
1
    return Fail();
327
1
  }
328
79.3k
329
  // Check for unexpanded parameter packs.
330
79.3k
  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
331
14
    return Fail();
332
14
  }
333
79.3k
334
  // C++11 [dcl.fct.default]p3
335
  //   A default argument expression [...] shall not be specified for a
336
  //   parameter pack.
337
79.3k
  if (Param->isParameterPack()) {
338
1
    Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
339
1
        << DefaultArg->getSourceRange();
340
    // Recover by discarding the default argument.
341
1
    Param->setDefaultArg(nullptr);
342
1
    return;
343
1
  }
344
79.3k
345
79.3k
  ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
346
79.3k
  if (Result.isInvalid())
347
47
    return Fail();
348
79.2k
349
79.2k
  DefaultArg = Result.getAs<Expr>();
350
79.2k
351
  // Check that the default argument is well-formed
352
79.2k
  CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
353
79.2k
  if (DefaultArgChecker.Visit(DefaultArg))
354
25
    return Fail();
355
79.2k
356
79.2k
  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
357
79.2k
}
358
359
/// ActOnParamUnparsedDefaultArgument - We've seen a default
360
/// argument for a function parameter, but we can't parse it yet
361
/// because we're inside a class definition. Note that this default
362
/// argument will be parsed later.
363
void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
364
                                             SourceLocation EqualLoc,
365
65.6k
                                             SourceLocation ArgLoc) {
366
65.6k
  if (!param)
367
0
    return;
368
65.6k
369
65.6k
  ParmVarDecl *Param = cast<ParmVarDecl>(param);
370
65.6k
  Param->setUnparsedDefaultArg();
371
65.6k
  UnparsedDefaultArgLocs[Param] = ArgLoc;
372
65.6k
}
373
374
/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
375
/// the default argument for the parameter param failed.
376
void Sema::ActOnParamDefaultArgumentError(Decl *param,
377
289
                                          SourceLocation EqualLoc) {
378
289
  if (!param)
379
0
    return;
380
289
381
289
  ParmVarDecl *Param = cast<ParmVarDecl>(param);
382
289
  Param->setInvalidDecl();
383
289
  UnparsedDefaultArgLocs.erase(Param);
384
289
  Param->setDefaultArg(new(Context)
385
289
                       OpaqueValueExpr(EqualLoc,
386
289
                                       Param->getType().getNonReferenceType(),
387
289
                                       VK_RValue));
388
289
}
389
390
/// CheckExtraCXXDefaultArguments - Check for any extra default
391
/// arguments in the declarator, which is not a function declaration
392
/// or definition and therefore is not permitted to have default
393
/// arguments. This routine should be invoked for every declarator
394
/// that is not a function declaration or definition.
395
15.2M
void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
396
  // C++ [dcl.fct.default]p3
397
  //   A default argument expression shall be specified only in the
398
  //   parameter-declaration-clause of a function declaration or in a
399
  //   template-parameter (14.1). It shall not be specified for a
400
  //   parameter pack. If it is specified in a
401
  //   parameter-declaration-clause, it shall not occur within a
402
  //   declarator or abstract-declarator of a parameter-declaration.
403
15.2M
  bool MightBeFunction = D.isFunctionDeclarationContext();
404
21.0M
  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; 
++i5.85M
) {
405
5.85M
    DeclaratorChunk &chunk = D.getTypeObject(i);
406
5.85M
    if (chunk.Kind == DeclaratorChunk::Function) {
407
2.66M
      if (MightBeFunction) {
408
        // This is a function declaration. It can have default arguments, but
409
        // keep looking in case its return type is a function type with default
410
        // arguments.
411
2.51M
        MightBeFunction = false;
412
2.51M
        continue;
413
2.51M
      }
414
392k
      
for (unsigned argIdx = 0, e = chunk.Fun.NumParams; 148k
argIdx != e;
415
243k
           ++argIdx) {
416
243k
        ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
417
243k
        if (Param->hasUnparsedDefaultArg()) {
418
3
          std::unique_ptr<CachedTokens> Toks =
419
3
              std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
420
3
          SourceRange SR;
421
3
          if (Toks->size() > 1)
422
2
            SR = SourceRange((*Toks)[1].getLocation(),
423
2
                             Toks->back().getLocation());
424
1
          else
425
1
            SR = UnparsedDefaultArgLocs[Param];
426
3
          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
427
3
            << SR;
428
243k
        } else if (Param->getDefaultArg()) {
429
10
          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
430
10
            << Param->getDefaultArg()->getSourceRange();
431
10
          Param->setDefaultArg(nullptr);
432
10
        }
433
243k
      }
434
3.19M
    } else if (chunk.Kind != DeclaratorChunk::Paren) {
435
3.06M
      MightBeFunction = false;
436
3.06M
    }
437
5.85M
  }
438
15.2M
}
439
440
32.2k
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
441
63.0k
  return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) {
442
63.0k
    return P->hasDefaultArg() && 
!P->hasInheritedDefaultArg()51
;
443
63.0k
  });
444
32.2k
}
445
446
/// MergeCXXFunctionDecl - Merge two declarations of the same C++
447
/// function, once we already know that they have the same
448
/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
449
/// error, false otherwise.
450
bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
451
219k
                                Scope *S) {
452
219k
  bool Invalid = false;
453
219k
454
  // The declaration context corresponding to the scope is the semantic
455
  // parent, unless this is a local function declaration, in which case
456
  // it is that surrounding function.
457
219k
  DeclContext *ScopeDC = New->isLocalExternDecl()
458
216
                             ? New->getLexicalDeclContext()
459
219k
                             : New->getDeclContext();
460
219k
461
  // Find the previous declaration for the purpose of default arguments.
462
219k
  FunctionDecl *PrevForDefaultArgs = Old;
463
219k
  for (/**/; PrevForDefaultArgs;
464
       // Don't bother looking back past the latest decl if this is a local
465
       // extern declaration; nothing else could work.
466
586
       PrevForDefaultArgs = New->isLocalExternDecl()
467
177
                                ? nullptr
468
219k
                                : 
PrevForDefaultArgs->getPreviousDecl()409
) {
469
    // Ignore hidden declarations.
470
219k
    if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
471
312
      continue;
472
219k
473
219k
    if (S && 
!isDeclInScope(PrevForDefaultArgs, ScopeDC, S)204k
&&
474
243
        !New->isCXXClassMember()) {
475
      // Ignore default arguments of old decl if they are not in
476
      // the same scope and this is not an out-of-line definition of
477
      // a member function.
478
243
      continue;
479
243
    }
480
218k
481
218k
    if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
482
      // If only one of these is a local function declaration, then they are
483
      // declared in different scopes, even though isDeclInScope may think
484
      // they're in the same scope. (If both are local, the scope check is
485
      // sufficient, and if neither is local, then they are in the same scope.)
486
31
      continue;
487
31
    }
488
218k
489
    // We found the right previous declaration.
490
218k
    break;
491
218k
  }
492
219k
493
  // C++ [dcl.fct.default]p4:
494
  //   For non-template functions, default arguments can be added in
495
  //   later declarations of a function in the same
496
  //   scope. Declarations in different scopes have completely
497
  //   distinct sets of default arguments. That is, declarations in
498
  //   inner scopes do not acquire default arguments from
499
  //   declarations in outer scopes, and vice versa. In a given
500
  //   function declaration, all parameters subsequent to a
501
  //   parameter with a default argument shall have default
502
  //   arguments supplied in this or previous declarations. A
503
  //   default argument shall not be redefined by a later
504
  //   declaration (not even to the same value).
505
  //
506
  // C++ [dcl.fct.default]p6:
507
  //   Except for member functions of class templates, the default arguments
508
  //   in a member function definition that appears outside of the class
509
  //   definition are added to the set of default arguments provided by the
510
  //   member function declaration in the class definition.
511
219k
  for (unsigned p = 0, NumParams = PrevForDefaultArgs
512
218k
                                       ? PrevForDefaultArgs->getNumParams()
513
420
                                       : 0;
514
574k
       p < NumParams; 
++p354k
) {
515
354k
    ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
516
354k
    ParmVarDecl *NewParam = New->getParamDecl(p);
517
354k
518
354k
    bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : 
false0
;
519
354k
    bool NewParamHasDfl = NewParam->hasDefaultArg();
520
354k
521
354k
    if (OldParamHasDfl && 
NewParamHasDfl23.6k
) {
522
14
      unsigned DiagDefaultParamID =
523
14
        diag::err_param_default_argument_redefinition;
524
14
525
      // MSVC accepts that default parameters be redefined for member functions
526
      // of template class. The new default parameter's value is ignored.
527
14
      Invalid = true;
528
14
      if (getLangOpts().MicrosoftExt) {
529
3
        CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
530
3
        if (MD && MD->getParent()->getDescribedClassTemplate()) {
531
          // Merge the old default argument into the new parameter.
532
3
          NewParam->setHasInheritedDefaultArg();
533
3
          if (OldParam->hasUninstantiatedDefaultArg())
534
0
            NewParam->setUninstantiatedDefaultArg(
535
0
                                      OldParam->getUninstantiatedDefaultArg());
536
3
          else
537
3
            NewParam->setDefaultArg(OldParam->getInit());
538
3
          DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
539
3
          Invalid = false;
540
3
        }
541
3
      }
542
14
543
      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
544
      // hint here. Alternatively, we could walk the type-source information
545
      // for NewParam to find the last source location in the type... but it
546
      // isn't worth the effort right now. This is the kind of test case that
547
      // is hard to get right:
548
      //   int f(int);
549
      //   void g(int (*fp)(int) = f);
550
      //   void g(int (*fp)(int) = &f);
551
14
      Diag(NewParam->getLocation(), DiagDefaultParamID)
552
14
        << NewParam->getDefaultArgRange();
553
14
554
      // Look for the function declaration where the default argument was
555
      // actually written, which may be a declaration prior to Old.
556
14
      for (auto Older = PrevForDefaultArgs;
557
16
           OldParam->hasInheritedDefaultArg(); /**/) {
558
2
        Older = Older->getPreviousDecl();
559
2
        OldParam = Older->getParamDecl(p);
560
2
      }
561
14
562
14
      Diag(OldParam->getLocation(), diag::note_previous_definition)
563
14
        << OldParam->getDefaultArgRange();
564
354k
    } else if (OldParamHasDfl) {
565
      // Merge the old default argument into the new parameter unless the new
566
      // function is a friend declaration in a template class. In the latter
567
      // case the default arguments will be inherited when the friend
568
      // declaration will be instantiated.
569
23.6k
      if (New->getFriendObjectKind() == Decl::FOK_None ||
570
23.6k
          
!New->getLexicalDeclContext()->isDependentContext()245
) {
571
        // It's important to use getInit() here;  getDefaultArg()
572
        // strips off any top-level ExprWithCleanups.
573
23.6k
        NewParam->setHasInheritedDefaultArg();
574
23.6k
        if (OldParam->hasUnparsedDefaultArg())
575
3
          NewParam->setUnparsedDefaultArg();
576
23.6k
        else if (OldParam->hasUninstantiatedDefaultArg())
577
19
          NewParam->setUninstantiatedDefaultArg(
578
19
                                       OldParam->getUninstantiatedDefaultArg());
579
23.6k
        else
580
23.6k
          NewParam->setDefaultArg(OldParam->getInit());
581
23.6k
      }
582
331k
    } else if (NewParamHasDfl) {
583
104
      if (New->getDescribedFunctionTemplate()) {
584
        // Paragraph 4, quoted above, only applies to non-template functions.
585
6
        Diag(NewParam->getLocation(),
586
6
             diag::err_param_default_argument_template_redecl)
587
6
          << NewParam->getDefaultArgRange();
588
6
        Diag(PrevForDefaultArgs->getLocation(),
589
6
             diag::note_template_prev_declaration)
590
6
            << false;
591
98
      } else if (New->getTemplateSpecializationKind()
592
98
                   != TSK_ImplicitInstantiation &&
593
98
                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
594
        // C++ [temp.expr.spec]p21:
595
        //   Default function arguments shall not be specified in a declaration
596
        //   or a definition for one of the following explicit specializations:
597
        //     - the explicit specialization of a function template;
598
        //     - the explicit specialization of a member function template;
599
        //     - the explicit specialization of a member function of a class
600
        //       template where the class template specialization to which the
601
        //       member function specialization belongs is implicitly
602
        //       instantiated.
603
2
        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
604
2
          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
605
2
          << New->getDeclName()
606
2
          << NewParam->getDefaultArgRange();
607
96
      } else if (New->getDeclContext()->isDependentContext()) {
608
        // C++ [dcl.fct.default]p6 (DR217):
609
        //   Default arguments for a member function of a class template shall
610
        //   be specified on the initial declaration of the member function
611
        //   within the class template.
612
        //
613
        // Reading the tea leaves a bit in DR217 and its reference to DR205
614
        // leads me to the conclusion that one cannot add default function
615
        // arguments for an out-of-line definition of a member function of a
616
        // dependent type.
617
7
        int WhichKind = 2;
618
7
        if (CXXRecordDecl *Record
619
7
              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
620
7
          if (Record->getDescribedClassTemplate())
621
6
            WhichKind = 0;
622
1
          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
623
0
            WhichKind = 1;
624
1
          else
625
1
            WhichKind = 2;
626
7
        }
627
7
628
7
        Diag(NewParam->getLocation(),
629
7
             diag::err_param_default_argument_member_template_redecl)
630
7
          << WhichKind
631
7
          << NewParam->getDefaultArgRange();
632
7
      }
633
104
    }
634
354k
  }
635
219k
636
  // DR1344: If a default argument is added outside a class definition and that
637
  // default argument makes the function a special member function, the program
638
  // is ill-formed. This can only happen for constructors.
639
219k
  if (isa<CXXConstructorDecl>(New) &&
640
31.9k
      New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
641
7
    CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
642
7
                     OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
643
7
    if (NewSM != OldSM) {
644
7
      ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
645
7
      assert(NewParam->hasDefaultArg());
646
7
      Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
647
7
        << NewParam->getDefaultArgRange() << NewSM;
648
7
      Diag(Old->getLocation(), diag::note_previous_declaration);
649
7
    }
650
7
  }
651
219k
652
219k
  const FunctionDecl *Def;
653
  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
654
  // template has a constexpr specifier then all its declarations shall
655
  // contain the constexpr specifier.
656
219k
  if (New->getConstexprKind() != Old->getConstexprKind()) {
657
79
    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
658
79
        << New << New->getConstexprKind() << Old->getConstexprKind();
659
79
    Diag(Old->getLocation(), diag::note_previous_declaration);
660
79
    Invalid = true;
661
219k
  } else if (!Old->getMostRecentDecl()->isInlined() && 
New->isInlined()181k
&&
662
69.7k
             Old->isDefined(Def) &&
663
             // If a friend function is inlined but does not have 'inline'
664
             // specifier, it is a definition. Do not report attribute conflict
665
             // in this case, redefinition will be diagnosed later.
666
17
             (New->isInlineSpecified() ||
667
15
              
New->getFriendObjectKind() == Decl::FOK_None2
)) {
668
    // C++11 [dcl.fcn.spec]p4:
669
    //   If the definition of a function appears in a translation unit before its
670
    //   first declaration as inline, the program is ill-formed.
671
15
    Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
672
15
    Diag(Def->getLocation(), diag::note_previous_definition);
673
15
    Invalid = true;
674
15
  }
675
219k
676
  // C++17 [temp.deduct.guide]p3:
677
  //   Two deduction guide declarations in the same translation unit
678
  //   for the same class template shall not have equivalent
679
  //   parameter-declaration-clauses.
680
219k
  if (isa<CXXDeductionGuideDecl>(New) &&
681
7
      !New->isFunctionTemplateSpecialization() && 
isVisible(Old)3
) {
682
2
    Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
683
2
    Diag(Old->getLocation(), diag::note_previous_declaration);
684
2
  }
685
219k
686
  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
687
  // argument expression, that declaration shall be a definition and shall be
688
  // the only declaration of the function or function template in the
689
  // translation unit.
690
219k
  if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
691
1.38k
      functionDeclHasDefaultArgument(Old)) {
692
4
    Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
693
4
    Diag(Old->getLocation(), diag::note_previous_declaration);
694
4
    Invalid = true;
695
4
  }
696
219k
697
219k
  return Invalid;
698
219k
}
699
700
NamedDecl *
701
Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
702
329
                                   MultiTemplateParamsArg TemplateParamLists) {
703
329
  assert(D.isDecompositionDeclarator());
704
329
  const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
705
329
706
  // The syntax only allows a decomposition declarator as a simple-declaration,
707
  // a for-range-declaration, or a condition in Clang, but we parse it in more
708
  // cases than that.
709
329
  if (!D.mayHaveDecompositionDeclarator()) {
710
2
    Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
711
2
      << Decomp.getSourceRange();
712
2
    return nullptr;
713
2
  }
714
327
715
327
  if (!TemplateParamLists.empty()) {
716
    // FIXME: There's no rule against this, but there are also no rules that
717
    // would actually make it usable, so we reject it for now.
718
2
    Diag(TemplateParamLists.front()->getTemplateLoc(),
719
2
         diag::err_decomp_decl_template);
720
2
    return nullptr;
721
2
  }
722
325
723
325
  Diag(Decomp.getLSquareLoc(),
724
325
       !getLangOpts().CPlusPlus17
725
13
           ? diag::ext_decomp_decl
726
312
           : D.getContext() == DeclaratorContext::ConditionContext
727
30
                 ? diag::ext_decomp_decl_cond
728
282
                 : diag::warn_cxx14_compat_decomp_decl)
729
325
      << Decomp.getSourceRange();
730
325
731
  // The semantic context is always just the current context.
732
325
  DeclContext *const DC = CurContext;
733
325
734
  // C++17 [dcl.dcl]/8:
735
  //   The decl-specifier-seq shall contain only the type-specifier auto
736
  //   and cv-qualifiers.
737
  // C++2a [dcl.dcl]/8:
738
  //   If decl-specifier-seq contains any decl-specifier other than static,
739
  //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
740
325
  auto &DS = D.getDeclSpec();
741
325
  {
742
325
    SmallVector<StringRef, 8> BadSpecifiers;
743
325
    SmallVector<SourceLocation, 8> BadSpecifierLocs;
744
325
    SmallVector<StringRef, 8> CPlusPlus20Specifiers;
745
325
    SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
746
325
    if (auto SCS = DS.getStorageClassSpec()) {
747
21
      if (SCS == DeclSpec::SCS_static) {
748
16
        CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
749
16
        CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
750
5
      } else {
751
5
        BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
752
5
        BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
753
5
      }
754
21
    }
755
325
    if (auto TSCS = DS.getThreadStorageClassSpec()) {
756
8
      CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
757
8
      CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
758
8
    }
759
325
    if (DS.hasConstexprSpecifier()) {
760
4
      BadSpecifiers.push_back(
761
4
          DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
762
4
      BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
763
4
    }
764
325
    if (DS.isInlineSpecified()) {
765
4
      BadSpecifiers.push_back("inline");
766
4
      BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
767
4
    }
768
325
    if (!BadSpecifiers.empty()) {
769
11
      auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
770
11
      Err << (int)BadSpecifiers.size()
771
11
          << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
772
      // Don't add FixItHints to remove the specifiers; we do still respect
773
      // them when building the underlying variable.
774
11
      for (auto Loc : BadSpecifierLocs)
775
13
        Err << SourceRange(Loc, Loc);
776
314
    } else if (!CPlusPlus20Specifiers.empty()) {
777
16
      auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
778
16
                         getLangOpts().CPlusPlus20
779
4
                             ? diag::warn_cxx17_compat_decomp_decl_spec
780
12
                             : diag::ext_decomp_decl_spec);
781
16
      Warn << (int)CPlusPlus20Specifiers.size()
782
16
           << llvm::join(CPlusPlus20Specifiers.begin(),
783
16
                         CPlusPlus20Specifiers.end(), " ");
784
16
      for (auto Loc : CPlusPlus20SpecifierLocs)
785
20
        Warn << SourceRange(Loc, Loc);
786
16
    }
787
    // We can't recover from it being declared as a typedef.
788
325
    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
789
2
      return nullptr;
790
323
  }
791
323
792
  // C++2a [dcl.struct.bind]p1:
793
  //   A cv that includes volatile is deprecated
794
323
  if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
795
5
      getLangOpts().CPlusPlus20)
796
1
    Diag(DS.getVolatileSpecLoc(),
797
1
         diag::warn_deprecated_volatile_structured_binding);
798
323
799
323
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
800
323
  QualType R = TInfo->getType();
801
323
802
323
  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
803
323
                                      UPPC_DeclarationType))
804
0
    D.setInvalidType();
805
323
806
  // The syntax only allows a single ref-qualifier prior to the decomposition
807
  // declarator. No other declarator chunks are permitted. Also check the type
808
  // specifier here.
809
323
  if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
810
306
      D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
811
306
      (D.getNumTypeObjects() == 1 &&
812
90
       D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
813
23
    Diag(Decomp.getLSquareLoc(),
814
23
         (D.hasGroupingParens() ||
815
23
          (D.getNumTypeObjects() &&
816
6
           D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
817
2
             ? diag::err_decomp_decl_parens
818
21
             : diag::err_decomp_decl_type)
819
23
        << R;
820
23
821
    // In most cases, there's no actual problem with an explicitly-specified
822
    // type, but a function type won't work here, and ActOnVariableDeclarator
823
    // shouldn't be called for such a type.
824
23
    if (R->isFunctionType())
825
0
      D.setInvalidType();
826
23
  }
827
323
828
  // Build the BindingDecls.
829
323
  SmallVector<BindingDecl*, 8> Bindings;
830
323
831
  // Build the BindingDecls.
832
584
  for (auto &B : D.getDecompositionDeclarator().bindings()) {
833
    // Check for name conflicts.
834
584
    DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
835
584
    LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
836
584
                          ForVisibleRedeclaration);
837
584
    LookupName(Previous, S,
838
584
               /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
839
584
840
    // It's not permitted to shadow a template parameter name.
841
584
    if (Previous.isSingleResult() &&
842
53
        Previous.getFoundDecl()->isTemplateParameter()) {
843
0
      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
844
0
                                      Previous.getFoundDecl());
845
0
      Previous.clear();
846
0
    }
847
584
848
584
    bool ConsiderLinkage = DC->isFunctionOrMethod() &&
849
508
                           DS.getStorageClassSpec() == DeclSpec::SCS_extern;
850
584
    FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
851
584
                         /*AllowInlineNamespace*/false);
852
584
    if (!Previous.empty()) {
853
1
      auto *Old = Previous.getRepresentativeDecl();
854
1
      Diag(B.NameLoc, diag::err_redefinition) << B.Name;
855
1
      Diag(Old->getLocation(), diag::note_previous_definition);
856
1
    }
857
584
858
584
    auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
859
584
    PushOnScopeChains(BD, S, true);
860
584
    Bindings.push_back(BD);
861
584
    ParsingInitForAutoVars.insert(BD);
862
584
  }
863
323
864
  // There are no prior lookup results for the variable itself, because it
865
  // is unnamed.
866
323
  DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
867
323
                               Decomp.getLSquareLoc());
868
323
  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
869
323
                        ForVisibleRedeclaration);
870
323
871
  // Build the variable that holds the non-decomposed object.
872
323
  bool AddToScope = true;
873
323
  NamedDecl *New =
874
323
      ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
875
323
                              MultiTemplateParamsArg(), AddToScope, Bindings);
876
323
  if (AddToScope) {
877
323
    S->AddDecl(New);
878
323
    CurContext->addHiddenDecl(New);
879
323
  }
880
323
881
323
  if (isInOpenMPDeclareTargetContext())
882
0
    checkDeclIsAllowedInOpenMPTarget(nullptr, New);
883
323
884
323
  return New;
885
323
}
886
887
static bool checkSimpleDecomposition(
888
    Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
889
    QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
890
51
    llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
891
51
  if ((int64_t)Bindings.size() != NumElems) {
892
2
    S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
893
2
        << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
894
2
        << (NumElems < Bindings.size());
895
2
    return true;
896
2
  }
897
49
898
49
  unsigned I = 0;
899
99
  for (auto *B : Bindings) {
900
99
    SourceLocation Loc = B->getLocation();
901
99
    ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
902
99
    if (E.isInvalid())
903
0
      return true;
904
99
    E = GetInit(Loc, E.get(), I++);
905
99
    if (E.isInvalid())
906
0
      return true;
907
99
    B->setBinding(ElemType, E.get());
908
99
  }
909
49
910
49
  return false;
911
49
}
912
913
static bool checkArrayLikeDecomposition(Sema &S,
914
                                        ArrayRef<BindingDecl *> Bindings,
915
                                        ValueDecl *Src, QualType DecompType,
916
                                        const llvm::APSInt &NumElems,
917
48
                                        QualType ElemType) {
918
48
  return checkSimpleDecomposition(
919
48
      S, Bindings, Src, DecompType, NumElems, ElemType,
920
93
      [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
921
93
        ExprResult E = S.ActOnIntegerConstant(Loc, I);
922
93
        if (E.isInvalid())
923
0
          return ExprError();
924
93
        return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
925
93
      });
926
48
}
927
928
static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
929
                                    ValueDecl *Src, QualType DecompType,
930
46
                                    const ConstantArrayType *CAT) {
931
46
  return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
932
46
                                     llvm::APSInt(CAT->getSize()),
933
46
                                     CAT->getElementType());
934
46
}
935
936
static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
937
                                     ValueDecl *Src, QualType DecompType,
938
2
                                     const VectorType *VT) {
939
2
  return checkArrayLikeDecomposition(
940
2
      S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
941
2
      S.Context.getQualifiedType(VT->getElementType(),
942
2
                                 DecompType.getQualifiers()));
943
2
}
944
945
static bool checkComplexDecomposition(Sema &S,
946
                                      ArrayRef<BindingDecl *> Bindings,
947
                                      ValueDecl *Src, QualType DecompType,
948
3
                                      const ComplexType *CT) {
949
3
  return checkSimpleDecomposition(
950
3
      S, Bindings, Src, DecompType, llvm::APSInt::get(2),
951
3
      S.Context.getQualifiedType(CT->getElementType(),
952
3
                                 DecompType.getQualifiers()),
953
6
      [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
954
3
        return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
955
6
      });
956
3
}
957
958
static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
959
4
                                     TemplateArgumentListInfo &Args) {
960
4
  SmallString<128> SS;
961
4
  llvm::raw_svector_ostream OS(SS);
962
4
  bool First = true;
963
7
  for (auto &Arg : Args.arguments()) {
964
7
    if (!First)
965
3
      OS << ", ";
966
7
    Arg.getArgument().print(PrintingPolicy, OS);
967
7
    First = false;
968
7
  }
969
4
  return std::string(OS.str());
970
4
}
971
972
static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
973
                                     SourceLocation Loc, StringRef Trait,
974
                                     TemplateArgumentListInfo &Args,
975
329
                                     unsigned DiagID) {
976
154
  auto DiagnoseMissing = [&] {
977
154
    if (DiagID)
978
1
      S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
979
1
                                               Args);
980
154
    return true;
981
154
  };
982
329
983
  // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
984
329
  NamespaceDecl *Std = S.getStdNamespace();
985
329
  if (!Std)
986
138
    return DiagnoseMissing();
987
191
988
  // Look up the trait itself, within namespace std. We can diagnose various
989
  // problems with this lookup even if we've been asked to not diagnose a
990
  // missing specialization, because this can only fail if the user has been
991
  // declaring their own names in namespace std or we don't support the
992
  // standard library implementation in use.
993
191
  LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
994
191
                      Loc, Sema::LookupOrdinaryName);
995
191
  if (!S.LookupQualifiedName(Result, Std))
996
16
    return DiagnoseMissing();
997
175
  if (Result.isAmbiguous())
998
0
    return true;
999
175
1000
175
  ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1001
175
  if (!TraitTD) {
1002
0
    Result.suppressDiagnostics();
1003
0
    NamedDecl *Found = *Result.begin();
1004
0
    S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1005
0
    S.Diag(Found->getLocation(), diag::note_declared_at);
1006
0
    return true;
1007
0
  }
1008
175
1009
  // Build the template-id.
1010
175
  QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1011
175
  if (TraitTy.isNull())
1012
0
    return true;
1013
175
  if (!S.isCompleteType(Loc, TraitTy)) {
1014
36
    if (DiagID)
1015
2
      S.RequireCompleteType(
1016
2
          Loc, TraitTy, DiagID,
1017
2
          printTemplateArgs(S.Context.getPrintingPolicy(), Args));
1018
36
    return true;
1019
36
  }
1020
139
1021
139
  CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1022
139
  assert(RD && "specialization of class template is not a class?");
1023
139
1024
  // Look up the member of the trait type.
1025
139
  S.LookupQualifiedName(TraitMemberLookup, RD);
1026
139
  return TraitMemberLookup.isAmbiguous();
1027
139
}
1028
1029
static TemplateArgumentLoc
1030
getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1031
169
                                   uint64_t I) {
1032
169
  TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1033
169
  return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1034
169
}
1035
1036
static TemplateArgumentLoc
1037
329
getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1038
329
  return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1039
329
}
1040
1041
namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1042
1043
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1044
246
                               llvm::APSInt &Size) {
1045
246
  EnterExpressionEvaluationContext ContextRAII(
1046
246
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1047
246
1048
246
  DeclarationName Value = S.PP.getIdentifierInfo("value");
1049
246
  LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1050
246
1051
  // Form template argument list for tuple_size<T>.
1052
246
  TemplateArgumentListInfo Args(Loc, Loc);
1053
246
  Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1054
246
1055
  // If there's no tuple_size specialization or the lookup of 'value' is empty,
1056
  // it's not tuple-like.
1057
246
  if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1058
59
      R.empty())
1059
189
    return IsTupleLike::NotTupleLike;
1060
57
1061
  // If we get this far, we've committed to the tuple interpretation, but
1062
  // we can still fail if there actually isn't a usable ::value.
1063
57
1064
57
  struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1065
57
    LookupResult &R;
1066
57
    TemplateArgumentListInfo &Args;
1067
57
    ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1068
57
        : R(R), Args(Args) {}
1069
57
    Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1070
1
                                               SourceLocation Loc) override {
1071
1
      return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1072
1
          << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1073
1
    }
1074
57
  } Diagnoser(R, Args);
1075
57
1076
57
  ExprResult E =
1077
57
      S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1078
57
  if (E.isInvalid())
1079
0
    return IsTupleLike::Error;
1080
57
1081
57
  E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1082
57
  if (E.isInvalid())
1083
1
    return IsTupleLike::Error;
1084
56
1085
56
  return IsTupleLike::TupleLike;
1086
56
}
1087
1088
/// \return std::tuple_element<I, T>::type.
1089
static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1090
83
                                        unsigned I, QualType T) {
1091
  // Form template argument list for tuple_element<I, T>.
1092
83
  TemplateArgumentListInfo Args(Loc, Loc);
1093
83
  Args.addArgument(
1094
83
      getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1095
83
  Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1096
83
1097
83
  DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1098
83
  LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1099
83
  if (lookupStdTypeTraitMember(
1100
83
          S, R, Loc, "tuple_element", Args,
1101
83
          diag::err_decomp_decl_std_tuple_element_not_specialized))
1102
3
    return QualType();
1103
80
1104
80
  auto *TD = R.getAsSingle<TypeDecl>();
1105
80
  if (!TD) {
1106
0
    R.suppressDiagnostics();
1107
0
    S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1108
0
      << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1109
0
    if (!R.empty())
1110
0
      S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1111
0
    return QualType();
1112
0
  }
1113
80
1114
80
  return S.Context.getTypeDeclType(TD);
1115
80
}
1116
1117
namespace {
1118
struct InitializingBinding {
1119
  Sema &S;
1120
86
  InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1121
86
    Sema::CodeSynthesisContext Ctx;
1122
86
    Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1123
86
    Ctx.PointOfInstantiation = BD->getLocation();
1124
86
    Ctx.Entity = BD;
1125
86
    S.pushCodeSynthesisContext(Ctx);
1126
86
  }
1127
86
  ~InitializingBinding() {
1128
86
    S.popCodeSynthesisContext();
1129
86
  }
1130
};
1131
}
1132
1133
static bool checkTupleLikeDecomposition(Sema &S,
1134
                                        ArrayRef<BindingDecl *> Bindings,
1135
                                        VarDecl *Src, QualType DecompType,
1136
56
                                        const llvm::APSInt &TupleSize) {
1137
56
  if ((int64_t)Bindings.size() != TupleSize) {
1138
3
    S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1139
3
        << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1140
3
        << (TupleSize < Bindings.size());
1141
3
    return true;
1142
3
  }
1143
53
1144
53
  if (Bindings.empty())
1145
0
    return false;
1146
53
1147
53
  DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1148
53
1149
  // [dcl.decomp]p3:
1150
  //   The unqualified-id get is looked up in the scope of E by class member
1151
  //   access lookup ...
1152
53
  LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1153
53
  bool UseMemberGet = false;
1154
53
  if (S.isCompleteType(Src->getLocation(), DecompType)) {
1155
53
    if (auto *RD = DecompType->getAsCXXRecordDecl())
1156
53
      S.LookupQualifiedName(MemberGet, RD);
1157
53
    if (MemberGet.isAmbiguous())
1158
1
      return true;
1159
    //   ... and if that finds at least one declaration that is a function
1160
    //   template whose first template parameter is a non-type parameter ...
1161
52
    for (NamedDecl *D : MemberGet) {
1162
35
      if (FunctionTemplateDecl *FTD =
1163
31
              dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1164
31
        TemplateParameterList *TPL = FTD->getTemplateParameters();
1165
31
        if (TPL->size() != 0 &&
1166
31
            isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1167
          //   ... the initializer is e.get<i>().
1168
29
          UseMemberGet = true;
1169
29
          break;
1170
29
        }
1171
31
      }
1172
35
    }
1173
52
  }
1174
53
1175
52
  unsigned I = 0;
1176
86
  for (auto *B : Bindings) {
1177
86
    InitializingBinding InitContext(S, B);
1178
86
    SourceLocation Loc = B->getLocation();
1179
86
1180
86
    ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1181
86
    if (E.isInvalid())
1182
0
      return true;
1183
86
1184
    //   e is an lvalue if the type of the entity is an lvalue reference and
1185
    //   an xvalue otherwise
1186
86
    if (!Src->getType()->isLValueReferenceType())
1187
66
      E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1188
66
                                   E.get(), nullptr, VK_XValue,
1189
66
                                   FPOptionsOverride());
1190
86
1191
86
    TemplateArgumentListInfo Args(Loc, Loc);
1192
86
    Args.addArgument(
1193
86
        getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1194
86
1195
86
    if (UseMemberGet) {
1196
      //   if [lookup of member get] finds at least one declaration, the
1197
      //   initializer is e.get<i-1>().
1198
37
      E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1199
37
                                     CXXScopeSpec(), SourceLocation(), nullptr,
1200
37
                                     MemberGet, &Args, nullptr);
1201
37
      if (E.isInvalid())
1202
0
        return true;
1203
37
1204
37
      E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1205
49
    } else {
1206
      //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1207
      //   in the associated namespaces.
1208
49
      Expr *Get = UnresolvedLookupExpr::Create(
1209
49
          S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1210
49
          DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1211
49
          UnresolvedSetIterator(), UnresolvedSetIterator());
1212
49
1213
49
      Expr *Arg = E.get();
1214
49
      E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1215
49
    }
1216
86
    if (E.isInvalid())
1217
3
      return true;
1218
83
    Expr *Init = E.get();
1219
83
1220
    //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1221
83
    QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1222
83
    if (T.isNull())
1223
3
      return true;
1224
80
1225
    //   each vi is a variable of type "reference to T" initialized with the
1226
    //   initializer, where the reference is an lvalue reference if the
1227
    //   initializer is an lvalue and an rvalue reference otherwise
1228
80
    QualType RefType =
1229
80
        S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1230
80
    if (RefType.isNull())
1231
0
      return true;
1232
80
    auto *RefVD = VarDecl::Create(
1233
80
        S.Context, Src->getDeclContext(), Loc, Loc,
1234
80
        B->getDeclName().getAsIdentifierInfo(), RefType,
1235
80
        S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1236
80
    RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1237
80
    RefVD->setTSCSpec(Src->getTSCSpec());
1238
80
    RefVD->setImplicit();
1239
80
    if (Src->isInlineSpecified())
1240
0
      RefVD->setInlineSpecified();
1241
80
    RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1242
80
1243
80
    InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1244
80
    InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1245
80
    InitializationSequence Seq(S, Entity, Kind, Init);
1246
80
    E = Seq.Perform(S, Entity, Kind, Init);
1247
80
    if (E.isInvalid())
1248
2
      return true;
1249
78
    E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1250
78
    if (E.isInvalid())
1251
0
      return true;
1252
78
    RefVD->setInit(E.get());
1253
78
    if (!E.get()->isValueDependent())
1254
75
      RefVD->checkInitIsICE();
1255
78
1256
78
    E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1257
78
                                   DeclarationNameInfo(B->getDeclName(), Loc),
1258
78
                                   RefVD);
1259
78
    if (E.isInvalid())
1260
0
      return true;
1261
78
1262
78
    B->setBinding(T, E.get());
1263
78
    I++;
1264
78
  }
1265
52
1266
44
  return false;
1267
52
}
1268
1269
/// Find the base class to decompose in a built-in decomposition of a class type.
1270
/// This base class search is, unfortunately, not quite like any other that we
1271
/// perform anywhere else in C++.
1272
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1273
                                                const CXXRecordDecl *RD,
1274
182
                                                CXXCastPath &BasePath) {
1275
182
  auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1276
30
                          CXXBasePath &Path) {
1277
30
    return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1278
30
  };
1279
182
1280
182
  const CXXRecordDecl *ClassWithFields = nullptr;
1281
182
  AccessSpecifier AS = AS_public;
1282
182
  if (RD->hasDirectFields())
1283
    // [dcl.decomp]p4:
1284
    //   Otherwise, all of E's non-static data members shall be public direct
1285
    //   members of E ...
1286
161
    ClassWithFields = RD;
1287
21
  else {
1288
    //   ... or of ...
1289
21
    CXXBasePaths Paths;
1290
21
    Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1291
21
    if (!RD->lookupInBases(BaseHasFields, Paths)) {
1292
      // If no classes have fields, just decompose RD itself. (This will work
1293
      // if and only if zero bindings were provided.)
1294
3
      return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1295
3
    }
1296
18
1297
18
    CXXBasePath *BestPath = nullptr;
1298
22
    for (auto &P : Paths) {
1299
22
      if (!BestPath)
1300
18
        BestPath = &P;
1301
4
      else if (!S.Context.hasSameType(P.back().Base->getType(),
1302
1
                                      BestPath->back().Base->getType())) {
1303
        //   ... the same ...
1304
1
        S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1305
1
          << false << RD << BestPath->back().Base->getType()
1306
1
          << P.back().Base->getType();
1307
1
        return DeclAccessPair();
1308
3
      } else if (P.Access < BestPath->Access) {
1309
0
        BestPath = &P;
1310
0
      }
1311
22
    }
1312
18
1313
    //   ... unambiguous ...
1314
17
    QualType BaseType = BestPath->back().Base->getType();
1315
17
    if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1316
2
      S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1317
2
        << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1318
2
      return DeclAccessPair();
1319
2
    }
1320
15
1321
    //   ... [accessible, implied by other rules] base class of E.
1322
15
    S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1323
15
                           *BestPath, diag::err_decomp_decl_inaccessible_base);
1324
15
    AS = BestPath->Access;
1325
15
1326
15
    ClassWithFields = BaseType->getAsCXXRecordDecl();
1327
15
    S.BuildBasePathArray(Paths, BasePath);
1328
15
  }
1329
182
1330
  // The above search did not check whether the selected class itself has base
1331
  // classes with fields, so check that now.
1332
176
  CXXBasePaths Paths;
1333
176
  if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1334
1
    S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1335
1
      << (ClassWithFields == RD) << RD << ClassWithFields
1336
1
      << Paths.front().back().Base->getType();
1337
1
    return DeclAccessPair();
1338
1
  }
1339
175
1340
175
  return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1341
175
}
1342
1343
static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1344
                                     ValueDecl *Src, QualType DecompType,
1345
182
                                     const CXXRecordDecl *OrigRD) {
1346
182
  if (S.RequireCompleteType(Src->getLocation(), DecompType,
1347
182
                            diag::err_incomplete_type))
1348
0
    return true;
1349
182
1350
182
  CXXCastPath BasePath;
1351
182
  DeclAccessPair BasePair =
1352
182
      findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1353
182
  const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1354
182
  if (!RD)
1355
4
    return true;
1356
178
  QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1357
178
                                                 DecompType.getQualifiers());
1358
178
1359
7
  auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1360
7
    unsigned NumFields =
1361
7
        std::count_if(RD->field_begin(), RD->field_end(),
1362
10
                      [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1363
7
    assert(Bindings.size() != NumFields);
1364
7
    S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1365
7
        << DecompType << (unsigned)Bindings.size() << NumFields
1366
7
        << (NumFields < Bindings.size());
1367
7
    return true;
1368
7
  };
1369
178
1370
  //   all of E's non-static data members shall be [...] well-formed
1371
  //   when named as e.name in the context of the structured binding,
1372
  //   E shall not have an anonymous union member, ...
1373
178
  unsigned I = 0;
1374
333
  for (auto *FD : RD->fields()) {
1375
333
    if (FD->isUnnamedBitfield())
1376
2
      continue;
1377
331
1378
331
    if (FD->isAnonymousStructOrUnion()) {
1379
2
      S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1380
2
        << DecompType << FD->getType()->isUnionType();
1381
2
      S.Diag(FD->getLocation(), diag::note_declared_at);
1382
2
      return true;
1383
2
    }
1384
329
1385
    // We have a real field to bind.
1386
329
    if (I >= Bindings.size())
1387
2
      return DiagnoseBadNumberOfBindings();
1388
327
    auto *B = Bindings[I++];
1389
327
    SourceLocation Loc = B->getLocation();
1390
327
1391
    // The field must be accessible in the context of the structured binding.
1392
    // We already checked that the base class is accessible.
1393
    // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1394
    // const_cast here.
1395
327
    S.CheckStructuredBindingMemberAccess(
1396
327
        Loc, const_cast<CXXRecordDecl *>(OrigRD),
1397
327
        DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1398
327
                                     BasePair.getAccess(), FD->getAccess())));
1399
327
1400
    // Initialize the binding to Src.FD.
1401
327
    ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1402
327
    if (E.isInvalid())
1403
0
      return true;
1404
327
    E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1405
327
                            VK_LValue, &BasePath);
1406
327
    if (E.isInvalid())
1407
0
      return true;
1408
327
    E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1409
327
                                  CXXScopeSpec(), FD,
1410
327
                                  DeclAccessPair::make(FD, FD->getAccess()),
1411
327
                                  DeclarationNameInfo(FD->getDeclName(), Loc));
1412
327
    if (E.isInvalid())
1413
0
      return true;
1414
327
1415
    // If the type of the member is T, the referenced type is cv T, where cv is
1416
    // the cv-qualification of the decomposition expression.
1417
    //
1418
    // FIXME: We resolve a defect here: if the field is mutable, we do not add
1419
    // 'const' to the type of the field.
1420
327
    Qualifiers Q = DecompType.getQualifiers();
1421
327
    if (FD->isMutable())
1422
7
      Q.removeConst();
1423
327
    B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1424
327
  }
1425
178
1426
174
  if (I != Bindings.size())
1427
5
    return DiagnoseBadNumberOfBindings();
1428
169
1429
169
  return false;
1430
169
}
1431
1432
311
void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1433
311
  QualType DecompType = DD->getType();
1434
311
1435
  // If the type of the decomposition is dependent, then so is the type of
1436
  // each binding.
1437
311
  if (DecompType->isDependentType()) {
1438
14
    for (auto *B : DD->bindings())
1439
25
      B->setType(Context.DependentTy);
1440
14
    return;
1441
14
  }
1442
297
1443
297
  DecompType = DecompType.getNonReferenceType();
1444
297
  ArrayRef<BindingDecl*> Bindings = DD->bindings();
1445
297
1446
  // C++1z [dcl.decomp]/2:
1447
  //   If E is an array type [...]
1448
  // As an extension, we also support decomposition of built-in complex and
1449
  // vector types.
1450
297
  if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1451
46
    if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1452
2
      DD->setInvalidDecl();
1453
46
    return;
1454
46
  }
1455
251
  if (auto *VT = DecompType->getAs<VectorType>()) {
1456
2
    if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1457
0
      DD->setInvalidDecl();
1458
2
    return;
1459
2
  }
1460
249
  if (auto *CT = DecompType->getAs<ComplexType>()) {
1461
3
    if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1462
0
      DD->setInvalidDecl();
1463
3
    return;
1464
3
  }
1465
246
1466
  // C++1z [dcl.decomp]/3:
1467
  //   if the expression std::tuple_size<E>::value is a well-formed integral
1468
  //   constant expression, [...]
1469
246
  llvm::APSInt TupleSize(32);
1470
246
  switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1471
1
  case IsTupleLike::Error:
1472
1
    DD->setInvalidDecl();
1473
1
    return;
1474
0
1475
56
  case IsTupleLike::TupleLike:
1476
56
    if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1477
12
      DD->setInvalidDecl();
1478
56
    return;
1479
0
1480
189
  case IsTupleLike::NotTupleLike:
1481
189
    break;
1482
189
  }
1483
189
1484
  // C++1z [dcl.dcl]/8:
1485
  //   [E shall be of array or non-union class type]
1486
189
  CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1487
189
  if (!RD || 
RD->isUnion()182
) {
1488
7
    Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1489
7
        << DD << !RD << DecompType;
1490
7
    DD->setInvalidDecl();
1491
7
    return;
1492
7
  }
1493
182
1494
  // C++1z [dcl.decomp]/4:
1495
  //   all of E's non-static data members shall be [...] direct members of
1496
  //   E or of the same unambiguous public base class of E, ...
1497
182
  if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1498
13
    DD->setInvalidDecl();
1499
182
}
1500
1501
/// Merge the exception specifications of two variable declarations.
1502
///
1503
/// This is called when there's a redeclaration of a VarDecl. The function
1504
/// checks if the redeclaration might have an exception specification and
1505
/// validates compatibility and merges the specs if necessary.
1506
55.6k
void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1507
  // Shortcut if exceptions are disabled.
1508
55.6k
  if (!getLangOpts().CXXExceptions)
1509
5.02k
    return;
1510
50.5k
1511
50.5k
  assert(Context.hasSameType(New->getType(), Old->getType()) &&
1512
50.5k
         "Should only be called if types are otherwise the same.");
1513
50.5k
1514
50.5k
  QualType NewType = New->getType();
1515
50.5k
  QualType OldType = Old->getType();
1516
50.5k
1517
  // We're only interested in pointers and references to functions, as well
1518
  // as pointers to member functions.
1519
50.5k
  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1520
10
    NewType = R->getPointeeType();
1521
10
    OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1522
50.5k
  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1523
232
    NewType = P->getPointeeType();
1524
232
    OldType = OldType->castAs<PointerType>()->getPointeeType();
1525
50.3k
  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1526
0
    NewType = M->getPointeeType();
1527
0
    OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1528
0
  }
1529
50.5k
1530
50.5k
  if (!NewType->isFunctionProtoType())
1531
50.5k
    return;
1532
24
1533
  // There's lots of special cases for functions. For function pointers, system
1534
  // libraries are hopefully not as broken so that we don't need these
1535
  // workarounds.
1536
24
  if (CheckEquivalentExceptionSpec(
1537
24
        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1538
7
        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1539
7
    New->setInvalidDecl();
1540
7
  }
1541
24
}
1542
1543
/// CheckCXXDefaultArguments - Verify that the default arguments for a
1544
/// function declaration are well-formed according to C++
1545
/// [dcl.fct.default].
1546
1.86M
void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1547
1.86M
  unsigned NumParams = FD->getNumParams();
1548
1.86M
  unsigned ParamIdx = 0;
1549
1.86M
1550
  // This checking doesn't make sense for explicit specializations; their
1551
  // default arguments are determined by the declaration we're specializing,
1552
  // not by FD.
1553
1.86M
  if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1554
4.61k
    return;
1555
1.86M
  if (auto *FTD = FD->getDescribedFunctionTemplate())
1556
384k
    if (FTD->isMemberSpecialization())
1557
59
      return;
1558
1.86M
1559
  // Find first parameter with a default argument
1560
5.31M
  
for (; 1.86M
ParamIdx < NumParams;
++ParamIdx3.45M
) {
1561
3.55M
    ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1562
3.55M
    if (Param->hasDefaultArg())
1563
105k
      break;
1564
3.55M
  }
1565
1.86M
1566
  // C++20 [dcl.fct.default]p4:
1567
  //   In a given function declaration, each parameter subsequent to a parameter
1568
  //   with a default argument shall have a default argument supplied in this or
1569
  //   a previous declaration, unless the parameter was expanded from a
1570
  //   parameter pack, or shall be a function parameter pack.
1571
1.98M
  for (; ParamIdx < NumParams; 
++ParamIdx117k
) {
1572
117k
    ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1573
117k
    if (!Param->hasDefaultArg() && 
!Param->isParameterPack()124
&&
1574
74
        !(CurrentInstantiationScope &&
1575
55
          CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1576
19
      if (Param->isInvalidDecl())
1577
0
        /* We already complained about this parameter. */;
1578
19
      else if (Param->getIdentifier())
1579
11
        Diag(Param->getLocation(),
1580
11
             diag::err_param_default_argument_missing_name)
1581
11
          << Param->getIdentifier();
1582
8
      else
1583
8
        Diag(Param->getLocation(),
1584
8
             diag::err_param_default_argument_missing);
1585
19
    }
1586
117k
  }
1587
1.86M
}
1588
1589
/// Check that the given type is a literal type. Issue a diagnostic if not,
1590
/// if Kind is Diagnose.
1591
/// \return \c true if a problem has been found (and optionally diagnosed).
1592
template <typename... Ts>
1593
static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1594
                             SourceLocation Loc, QualType T, unsigned DiagID,
1595
194k
                             Ts &&...DiagArgs) {
1596
194k
  if (T->isDependentType())
1597
96.8k
    return false;
1598
98.1k
1599
98.1k
  switch (Kind) {
1600
96.6k
  case Sema::CheckConstexprKind::Diagnose:
1601
96.6k
    return SemaRef.RequireLiteralType(Loc, T, DiagID,
1602
96.6k
                                      std::forward<Ts>(DiagArgs)...);
1603
0
1604
1.46k
  case Sema::CheckConstexprKind::CheckValid:
1605
1.46k
    return !T->isLiteralType(SemaRef.Context);
1606
0
  }
1607
0
1608
0
  llvm_unreachable("unknown CheckConstexprKind");
1609
0
}
SemaDeclCXX.cpp:bool CheckLiteralType<bool>(clang::Sema&, clang::Sema::CheckConstexprKind, clang::SourceLocation, clang::QualType, unsigned int, bool&&)
Line
Count
Source
1595
109k
                             Ts &&...DiagArgs) {
1596
109k
  if (T->isDependentType())
1597
49.8k
    return false;
1598
59.7k
1599
59.7k
  switch (Kind) {
1600
58.5k
  case Sema::CheckConstexprKind::Diagnose:
1601
58.5k
    return SemaRef.RequireLiteralType(Loc, T, DiagID,
1602
58.5k
                                      std::forward<Ts>(DiagArgs)...);
1603
0
1604
1.22k
  case Sema::CheckConstexprKind::CheckValid:
1605
1.22k
    return !T->isLiteralType(SemaRef.Context);
1606
0
  }
1607
0
1608
0
  llvm_unreachable("unknown CheckConstexprKind");
1609
0
}
SemaDeclCXX.cpp:bool CheckLiteralType<unsigned int, clang::SourceRange, bool, bool>(clang::Sema&, clang::Sema::CheckConstexprKind, clang::SourceLocation, clang::QualType, unsigned int, unsigned int&&, clang::SourceRange&&, bool&&, bool&&)
Line
Count
Source
1595
85.2k
                             Ts &&...DiagArgs) {
1596
85.2k
  if (T->isDependentType())
1597
46.9k
    return false;
1598
38.3k
1599
38.3k
  switch (Kind) {
1600
38.0k
  case Sema::CheckConstexprKind::Diagnose:
1601
38.0k
    return SemaRef.RequireLiteralType(Loc, T, DiagID,
1602
38.0k
                                      std::forward<Ts>(DiagArgs)...);
1603
0
1604
243
  case Sema::CheckConstexprKind::CheckValid:
1605
243
    return !T->isLiteralType(SemaRef.Context);
1606
0
  }
1607
0
1608
0
  llvm_unreachable("unknown CheckConstexprKind");
1609
0
}
1610
1611
/// Determine whether a destructor cannot be constexpr due to
1612
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1613
                                               const CXXDestructorDecl *DD,
1614
2
                                               Sema::CheckConstexprKind Kind) {
1615
2
  auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1616
2
    const CXXRecordDecl *RD =
1617
2
        T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1618
2
    if (!RD || RD->hasConstexprDestructor())
1619
0
      return true;
1620
2
1621
2
    if (Kind == Sema::CheckConstexprKind::Diagnose) {
1622
2
      SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1623
2
          << DD->getConstexprKind() << !FD
1624
1
          << (FD ? FD->getDeclName() : DeclarationName()) << T;
1625
2
      SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1626
1
          << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1627
2
    }
1628
2
    return false;
1629
2
  };
1630
2
1631
2
  const CXXRecordDecl *RD = DD->getParent();
1632
2
  for (const CXXBaseSpecifier &B : RD->bases())
1633
1
    if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1634
1
      return false;
1635
1
  for (const FieldDecl *FD : RD->fields())
1636
1
    if (!Check(FD->getLocation(), FD->getType(), FD))
1637
1
      return false;
1638
0
  return true;
1639
1
}
1640
1641
/// Check whether a function's parameter types are all literal types. If so,
1642
/// return true. If not, produce a suitable diagnostic and return false.
1643
static bool CheckConstexprParameterTypes(Sema &SemaRef,
1644
                                         const FunctionDecl *FD,
1645
125k
                                         Sema::CheckConstexprKind Kind) {
1646
125k
  unsigned ArgIndex = 0;
1647
125k
  const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1648
125k
  for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1649
125k
                                              e = FT->param_type_end();
1650
210k
       i != e; 
++i, ++ArgIndex85.1k
) {
1651
85.2k
    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1652
85.2k
    SourceLocation ParamLoc = PD->getLocation();
1653
85.2k
    if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1654
85.2k
                         diag::err_constexpr_non_literal_param, ArgIndex + 1,
1655
85.2k
                         PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1656
85.2k
                         FD->isConsteval()))
1657
56
      return false;
1658
85.2k
  }
1659
125k
  return true;
1660
125k
}
1661
1662
/// Check whether a function's return type is a literal type. If so, return
1663
/// true. If not, produce a suitable diagnostic and return false.
1664
static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1665
107k
                                     Sema::CheckConstexprKind Kind) {
1666
107k
  if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1667
107k
                       diag::err_constexpr_non_literal_return,
1668
107k
                       FD->isConsteval()))
1669
18
    return false;
1670
107k
  return true;
1671
107k
}
1672
1673
/// Get diagnostic %select index for tag kind for
1674
/// record diagnostic message.
1675
/// WARNING: Indexes apply to particular diagnostics only!
1676
///
1677
/// \returns diagnostic %select index.
1678
24
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1679
24
  switch (Tag) {
1680
19
  case TTK_Struct: return 0;
1681
1
  case TTK_Interface: return 1;
1682
4
  case TTK_Class:  return 2;
1683
0
  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1684
24
  }
1685
24
}
1686
1687
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1688
                                       Stmt *Body,
1689
                                       Sema::CheckConstexprKind Kind);
1690
1691
// Check whether a function declaration satisfies the requirements of a
1692
// constexpr function definition or a constexpr constructor definition. If so,
1693
// return true. If not, produce appropriate diagnostics (unless asked not to by
1694
// Kind) and return false.
1695
//
1696
// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1697
bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1698
125k
                                            CheckConstexprKind Kind) {
1699
125k
  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1700
125k
  if (MD && 
MD->isInstance()93.4k
) {
1701
    // C++11 [dcl.constexpr]p4:
1702
    //  The definition of a constexpr constructor shall satisfy the following
1703
    //  constraints:
1704
    //  - the class shall not have any virtual base classes;
1705
    //
1706
    // FIXME: This only applies to constructors and destructors, not arbitrary
1707
    // member functions.
1708
31.6k
    const CXXRecordDecl *RD = MD->getParent();
1709
31.6k
    if (RD->getNumVBases()) {
1710
13
      if (Kind == CheckConstexprKind::CheckValid)
1711
0
        return false;
1712
13
1713
13
      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1714
13
        << isa<CXXConstructorDecl>(NewFD)
1715
13
        << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1716
13
      for (const auto &I : RD->vbases())
1717
13
        Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1718
13
            << I.getSourceRange();
1719
13
      return false;
1720
13
    }
1721
31.6k
  }
1722
125k
1723
125k
  if (!isa<CXXConstructorDecl>(NewFD)) {
1724
    // C++11 [dcl.constexpr]p3:
1725
    //  The definition of a constexpr function shall satisfy the following
1726
    //  constraints:
1727
    // - it shall not be virtual; (removed in C++20)
1728
107k
    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1729
107k
    if (Method && 
Method->isVirtual()75.4k
) {
1730
41
      if (getLangOpts().CPlusPlus20) {
1731
28
        if (Kind == CheckConstexprKind::Diagnose)
1732
28
          Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1733
13
      } else {
1734
13
        if (Kind == CheckConstexprKind::CheckValid)
1735
0
          return false;
1736
13
1737
13
        Method = Method->getCanonicalDecl();
1738
13
        Diag(Method->getLocation(), diag::err_constexpr_virtual);
1739
13
1740
        // If it's not obvious why this function is virtual, find an overridden
1741
        // function which uses the 'virtual' keyword.
1742
13
        const CXXMethodDecl *WrittenVirtual = Method;
1743
20
        while (!WrittenVirtual->isVirtualAsWritten())
1744
7
          WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1745
13
        if (WrittenVirtual != Method)
1746
5
          Diag(WrittenVirtual->getLocation(),
1747
5
               diag::note_overridden_virtual_function);
1748
13
        return false;
1749
13
      }
1750
41
    }
1751
107k
1752
    // - its return type shall be a literal type;
1753
107k
    if (!CheckConstexprReturnType(*this, NewFD, Kind))
1754
18
      return false;
1755
125k
  }
1756
125k
1757
125k
  if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1758
    // A destructor can be constexpr only if the defaulted destructor could be;
1759
    // we don't need to check the members and bases if we already know they all
1760
    // have constexpr destructors.
1761
58
    if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1762
2
      if (Kind == CheckConstexprKind::CheckValid)
1763
0
        return false;
1764
2
      if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1765
2
        return false;
1766
125k
    }
1767
58
  }
1768
125k
1769
  // - each of its parameter types shall be a literal type;
1770
125k
  if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1771
56
    return false;
1772
125k
1773
125k
  Stmt *Body = NewFD->getBody();
1774
125k
  assert(Body &&
1775
125k
         "CheckConstexprFunctionDefinition called on function with no body");
1776
125k
  return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1777
125k
}
1778
1779
/// Check the given declaration statement is legal within a constexpr function
1780
/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1781
///
1782
/// \return true if the body is OK (maybe only as an extension), false if we
1783
///         have diagnosed a problem.
1784
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1785
                                   DeclStmt *DS, SourceLocation &Cxx1yLoc,
1786
12.0k
                                   Sema::CheckConstexprKind Kind) {
1787
  // C++11 [dcl.constexpr]p3 and p4:
1788
  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1789
  //  contain only
1790
12.0k
  for (const auto *DclIt : DS->decls()) {
1791
12.0k
    switch (DclIt->getKind()) {
1792
3.00k
    case Decl::StaticAssert:
1793
3.00k
    case Decl::Using:
1794
3.00k
    case Decl::UsingShadow:
1795
3.00k
    case Decl::UsingDirective:
1796
3.00k
    case Decl::UnresolvedUsingTypename:
1797
3.00k
    case Decl::UnresolvedUsingValue:
1798
      //   - static_assert-declarations
1799
      //   - using-declarations,
1800
      //   - using-directives,
1801
3.00k
      continue;
1802
3.00k
1803
6.95k
    case Decl::Typedef:
1804
6.95k
    case Decl::TypeAlias: {
1805
      //   - typedef declarations and alias-declarations that do not define
1806
      //     classes or enumerations,
1807
6.95k
      const auto *TN = cast<TypedefNameDecl>(DclIt);
1808
6.95k
      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1809
        // Don't allow variably-modified types in constexpr functions.
1810
0
        if (Kind == Sema::CheckConstexprKind::Diagnose) {
1811
0
          TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1812
0
          SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1813
0
            << TL.getSourceRange() << TL.getType()
1814
0
            << isa<CXXConstructorDecl>(Dcl);
1815
0
        }
1816
0
        return false;
1817
0
      }
1818
6.95k
      continue;
1819
6.95k
    }
1820
6.95k
1821
102
    case Decl::Enum:
1822
102
    case Decl::CXXRecord:
1823
      // C++1y allows types to be defined, not just declared.
1824
102
      if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1825
88
        if (Kind == Sema::CheckConstexprKind::Diagnose) {
1826
65
          SemaRef.Diag(DS->getBeginLoc(),
1827
65
                       SemaRef.getLangOpts().CPlusPlus14
1828
59
                           ? diag::warn_cxx11_compat_constexpr_type_definition
1829
6
                           : diag::ext_constexpr_type_definition)
1830
65
              << isa<CXXConstructorDecl>(Dcl);
1831
23
        } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1832
0
          return false;
1833
0
        }
1834
102
      }
1835
102
      continue;
1836
102
1837
0
    case Decl::EnumConstant:
1838
0
    case Decl::IndirectField:
1839
0
    case Decl::ParmVar:
1840
      // These can only appear with other declarations which are banned in
1841
      // C++11 and permitted in C++1y, so ignore them.
1842
0
      continue;
1843
0
1844
1.97k
    case Decl::Var:
1845
1.97k
    case Decl::Decomposition: {
1846
      // C++1y [dcl.constexpr]p3 allows anything except:
1847
      //   a definition of a variable of non-literal type or of static or
1848
      //   thread storage duration or [before C++2a] for which no
1849
      //   initialization is performed.
1850
1.97k
      const auto *VD = cast<VarDecl>(DclIt);
1851
1.97k
      if (VD->isThisDeclarationADefinition()) {
1852
1.93k
        if (VD->isStaticLocal()) {
1853
16
          if (Kind == Sema::CheckConstexprKind::Diagnose) {
1854
13
            SemaRef.Diag(VD->getLocation(),
1855
13
                         diag::err_constexpr_local_var_static)
1856
13
              << isa<CXXConstructorDecl>(Dcl)
1857
13
              << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1858
13
          }
1859
16
          return false;
1860
16
        }
1861
1.92k
        if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1862
1.92k
                             diag::err_constexpr_local_var_non_literal_type,
1863
1.92k
                             isa<CXXConstructorDecl>(Dcl)))
1864
19
          return false;
1865
1.90k
        if (!VD->getType()->isDependentType() &&
1866
1.07k
            !VD->hasInit() && 
!VD->isCXXForRangeDecl()46
) {
1867
42
          if (Kind == Sema::CheckConstexprKind::Diagnose) {
1868
26
            SemaRef.Diag(
1869
26
                VD->getLocation(),
1870
26
                SemaRef.getLangOpts().CPlusPlus20
1871
22
                    ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1872
4
                    : diag::ext_constexpr_local_var_no_init)
1873
26
                << isa<CXXConstructorDecl>(Dcl);
1874
16
          } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1875
7
            return false;
1876
7
          }
1877
35
          continue;
1878
35
        }
1879
1.90k
      }
1880
1.89k
      if (Kind == Sema::CheckConstexprKind::Diagnose) {
1881
1.63k
        SemaRef.Diag(VD->getLocation(),
1882
1.63k
                     SemaRef.getLangOpts().CPlusPlus14
1883
1.62k
                      ? diag::warn_cxx11_compat_constexpr_local_var
1884
6
                      : diag::ext_constexpr_local_var)
1885
1.63k
          << isa<CXXConstructorDecl>(Dcl);
1886
264
      } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1887
0
        return false;
1888
0
      }
1889
1.89k
      continue;
1890
1.89k
    }
1891
1.89k
1892
17
    case Decl::NamespaceAlias:
1893
17
    case Decl::Function:
1894
      // These are disallowed in C++11 and permitted in C++1y. Allow them
1895
      // everywhere as an extension.
1896
17
      if (!Cxx1yLoc.isValid())
1897
17
        Cxx1yLoc = DS->getBeginLoc();
1898
17
      continue;
1899
17
1900
0
    default:
1901
0
      if (Kind == Sema::CheckConstexprKind::Diagnose) {
1902
0
        SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1903
0
            << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1904
0
      }
1905
0
      return false;
1906
12.0k
    }
1907
12.0k
  }
1908
12.0k
1909
11.9k
  return true;
1910
12.0k
}
1911
1912
/// Check that the given field is initialized within a constexpr constructor.
1913
///
1914
/// \param Dcl The constexpr constructor being checked.
1915
/// \param Field The field being checked. This may be a member of an anonymous
1916
///        struct or union nested within the class being checked.
1917
/// \param Inits All declarations, including anonymous struct/union members and
1918
///        indirect members, for which any initialization was provided.
1919
/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1920
///        multiple notes for different members to the same error.
1921
/// \param Kind Whether we're diagnosing a constructor as written or determining
1922
///        whether the formal requirements are satisfied.
1923
/// \return \c false if we're checking for validity and the constructor does
1924
///         not satisfy the requirements on a constexpr constructor.
1925
static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1926
                                          const FunctionDecl *Dcl,
1927
                                          FieldDecl *Field,
1928
                                          llvm::SmallSet<Decl*, 16> &Inits,
1929
                                          bool &Diagnosed,
1930
373
                                          Sema::CheckConstexprKind Kind) {
1931
  // In C++20 onwards, there's nothing to check for validity.
1932
373
  if (Kind == Sema::CheckConstexprKind::CheckValid &&
1933
0
      SemaRef.getLangOpts().CPlusPlus20)
1934
0
    return true;
1935
373
1936
373
  if (Field->isInvalidDecl())
1937
1
    return true;
1938
372
1939
372
  if (Field->isUnnamedBitfield())
1940
4
    return true;
1941
368
1942
  // Anonymous unions with no variant members and empty anonymous structs do not
1943
  // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1944
  // indirect fields don't need initializing.
1945
368
  if (Field->isAnonymousStructOrUnion() &&
1946
172
      (Field->getType()->isUnionType()
1947
125
           ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1948
47
           : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1949
6
    return true;
1950
362
1951
362
  if (!Inits.count(Field)) {
1952
40
    if (Kind == Sema::CheckConstexprKind::Diagnose) {
1953
40
      if (!Diagnosed) {
1954
25
        SemaRef.Diag(Dcl->getLocation(),
1955
25
                     SemaRef.getLangOpts().CPlusPlus20
1956
9
                         ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1957
16
                         : diag::ext_constexpr_ctor_missing_init);
1958
25
        Diagnosed = true;
1959
25
      }
1960
40
      SemaRef.Diag(Field->getLocation(),
1961
40
                   diag::note_constexpr_ctor_missing_init);
1962
0
    } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1963
0
      return false;
1964
0
    }
1965
322
  } else if (Field->isAnonymousStructOrUnion()) {
1966
143
    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1967
143
    for (auto *I : RD->fields())
1968
      // If an anonymous union contains an anonymous struct of which any member
1969
      // is initialized, all members must be initialized.
1970
323
      if (!RD->isUnion() || 
Inits.count(I)227
)
1971
198
        if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1972
198
                                           Kind))
1973
0
          return false;
1974
143
  }
1975
362
  return true;
1976
362
}
1977
1978
/// Check the provided statement is allowed in a constexpr function
1979
/// definition.
1980
static bool
1981
CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1982
                           SmallVectorImpl<SourceLocation> &ReturnStmts,
1983
                           SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
1984
127k
                           Sema::CheckConstexprKind Kind) {
1985
  // - its function-body shall be [...] a compound-statement that contains only
1986
127k
  switch (S->getStmtClass()) {
1987
30
  case Stmt::NullStmtClass:
1988
    //   - null statements,
1989
30
    return true;
1990
0
1991
12.0k
  case Stmt::DeclStmtClass:
1992
    //   - static_assert-declarations
1993
    //   - using-declarations,
1994
    //   - using-directives,
1995
    //   - typedef declarations and alias-declarations that do not define
1996
    //     classes or enumerations,
1997
12.0k
    if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
1998
42
      return false;
1999
11.9k
    return true;
2000
11.9k
2001
107k
  case Stmt::ReturnStmtClass:
2002
    //   - and exactly one return statement;
2003
107k
    if (isa<CXXConstructorDecl>(Dcl)) {
2004
      // C++1y allows return statements in constexpr constructors.
2005
3
      if (!Cxx1yLoc.isValid())
2006
3
        Cxx1yLoc = S->getBeginLoc();
2007
3
      return true;
2008
3
    }
2009
107k
2010
107k
    ReturnStmts.push_back(S->getBeginLoc());
2011
107k
    return true;
2012
107k
2013
804
  case Stmt::CompoundStmtClass: {
2014
    // C++1y allows compound-statements.
2015
804
    if (!Cxx1yLoc.isValid())
2016
30
      Cxx1yLoc = S->getBeginLoc();
2017
804
2018
804
    CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2019
1.90k
    for (auto *BodyIt : CompStmt->body()) {
2020
1.90k
      if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2021
1.90k
                                      Cxx1yLoc, Cxx2aLoc, Kind))
2022
3
        return false;
2023
1.90k
    }
2024
801
    return true;
2025
804
  }
2026
804
2027
0
  case Stmt::AttributedStmtClass:
2028
0
    if (!Cxx1yLoc.isValid())
2029
0
      Cxx1yLoc = S->getBeginLoc();
2030
0
    return true;
2031
804
2032
1.85k
  case Stmt::IfStmtClass: {
2033
    // C++1y allows if-statements.
2034
1.85k
    if (!Cxx1yLoc.isValid())
2035
660
      Cxx1yLoc = S->getBeginLoc();
2036
1.85k
2037
1.85k
    IfStmt *If = cast<IfStmt>(S);
2038
1.85k
    if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2039
1.85k
                                    Cxx1yLoc, Cxx2aLoc, Kind))
2040
0
      return false;
2041
1.85k
    if (If->getElse() &&
2042
312
        !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2043
312
                                    Cxx1yLoc, Cxx2aLoc, Kind))
2044
0
      return false;
2045
1.85k
    return true;
2046
1.85k
  }
2047
1.85k
2048
511
  case Stmt::WhileStmtClass:
2049
511
  case Stmt::DoStmtClass:
2050
511
  case Stmt::ForStmtClass:
2051
511
  case Stmt::CXXForRangeStmtClass:
2052
511
  case Stmt::ContinueStmtClass:
2053
    // C++1y allows all of these. We don't allow them as extensions in C++11,
2054
    // because they don't make sense without variable mutation.
2055
511
    if (!SemaRef.getLangOpts().CPlusPlus14)
2056
3
      break;
2057
508
    if (!Cxx1yLoc.isValid())
2058
151
      Cxx1yLoc = S->getBeginLoc();
2059
508
    for (Stmt *SubStmt : S->children())
2060
1.75k
      if (SubStmt &&
2061
1.34k
          !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2062
1.34k
                                      Cxx1yLoc, Cxx2aLoc, Kind))
2063
0
        return false;
2064
508
    return true;
2065
508
2066
301
  case Stmt::SwitchStmtClass:
2067
301
  case Stmt::CaseStmtClass:
2068
301
  case Stmt::DefaultStmtClass:
2069
301
  case Stmt::BreakStmtClass:
2070
    // C++1y allows switch-statements, and since they don't need variable
2071
    // mutation, we can reasonably allow them in C++11 as an extension.
2072
301
    if (!Cxx1yLoc.isValid())
2073
22
      Cxx1yLoc = S->getBeginLoc();
2074
301
    for (Stmt *SubStmt : S->children())
2075
281
      if (SubStmt &&
2076
281
          !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2077
281
                                      Cxx1yLoc, Cxx2aLoc, Kind))
2078
0
        return false;
2079
301
    return true;
2080
301
2081
21
  case Stmt::GCCAsmStmtClass:
2082
21
  case Stmt::MSAsmStmtClass:
2083
    // C++2a allows inline assembly statements.
2084
21
  case Stmt::CXXTryStmtClass:
2085
21
    if (Cxx2aLoc.isInvalid())
2086
21
      Cxx2aLoc = S->getBeginLoc();
2087
18
    for (Stmt *SubStmt : S->children()) {
2088
18
      if (SubStmt &&
2089
18
          !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2090
18
                                      Cxx1yLoc, Cxx2aLoc, Kind))
2091
3
        return false;
2092
18
    }
2093
18
    return true;
2094
21
2095
16
  case Stmt::CXXCatchStmtClass:
2096
    // Do not bother checking the language mode (already covered by the
2097
    // try block check).
2098
16
    if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2099
16
                                    cast<CXXCatchStmt>(S)->getHandlerBlock(),
2100
16
                                    ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2101
3
      return false;
2102
13
    return true;
2103
13
2104
3.72k
  default:
2105
3.72k
    if (!isa<Expr>(S))
2106
8
      break;
2107
3.72k
2108
    // C++1y allows expression-statements.
2109
3.72k
    if (!Cxx1yLoc.isValid())
2110
1.33k
      Cxx1yLoc = S->getBeginLoc();
2111
3.72k
    return true;
2112
11
  }
2113
11
2114
11
  if (Kind == Sema::CheckConstexprKind::Diagnose) {
2115
11
    SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2116
11
        << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2117
11
  }
2118
11
  return false;
2119
11
}
2120
2121
/// Check the body for the given constexpr function declaration only contains
2122
/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2123
///
2124
/// \return true if the body is OK, false if we have found or diagnosed a
2125
/// problem.
2126
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2127
                                       Stmt *Body,
2128
125k
                                       Sema::CheckConstexprKind Kind) {
2129
125k
  SmallVector<SourceLocation, 4> ReturnStmts;
2130
125k
2131
125k
  if (isa<CXXTryStmt>(Body)) {
2132
    // C++11 [dcl.constexpr]p3:
2133
    //  The definition of a constexpr function shall satisfy the following
2134
    //  constraints: [...]
2135
    // - its function-body shall be = delete, = default, or a
2136
    //   compound-statement
2137
    //
2138
    // C++11 [dcl.constexpr]p4:
2139
    //  In the definition of a constexpr constructor, [...]
2140
    // - its function-body shall not be a function-try-block;
2141
    //
2142
    // This restriction is lifted in C++2a, as long as inner statements also
2143
    // apply the general constexpr rules.
2144
7
    switch (Kind) {
2145
0
    case Sema::CheckConstexprKind::CheckValid:
2146
0
      if (!SemaRef.getLangOpts().CPlusPlus20)
2147
0
        return false;
2148
0
      break;
2149
0
2150
7
    case Sema::CheckConstexprKind::Diagnose:
2151
7
      SemaRef.Diag(Body->getBeginLoc(),
2152
7
           !SemaRef.getLangOpts().CPlusPlus20
2153
5
               ? diag::ext_constexpr_function_try_block_cxx20
2154
2
               : diag::warn_cxx17_compat_constexpr_function_try_block)
2155
7
          << isa<CXXConstructorDecl>(Dcl);
2156
7
      break;
2157
125k
    }
2158
125k
  }
2159
125k
2160
  // - its function-body shall be [...] a compound-statement that contains only
2161
  //   [... list of cases ...]
2162
  //
2163
  // Note that walking the children here is enough to properly check for
2164
  // CompoundStmt and CXXTryStmt body.
2165
125k
  SourceLocation Cxx1yLoc, Cxx2aLoc;
2166
121k
  for (Stmt *SubStmt : Body->children()) {
2167
121k
    if (SubStmt &&
2168
121k
        !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2169
121k
                                    Cxx1yLoc, Cxx2aLoc, Kind))
2170
53
      return false;
2171
121k
  }
2172
125k
2173
125k
  if (Kind == Sema::CheckConstexprKind::CheckValid) {
2174
    // If this is only valid as an extension, report that we don't satisfy the
2175
    // constraints of the current language.
2176
1.30k
    if ((Cxx2aLoc.isValid() && 
!SemaRef.getLangOpts().CPlusPlus209
) ||
2177
1.29k
        (Cxx1yLoc.isValid() && 
!SemaRef.getLangOpts().CPlusPlus17323
))
2178
6
      return false;
2179
124k
  } else if (Cxx2aLoc.isValid()) {
2180
9
    SemaRef.Diag(Cxx2aLoc,
2181
9
         SemaRef.getLangOpts().CPlusPlus20
2182
3
           ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2183
6
           : diag::ext_constexpr_body_invalid_stmt_cxx20)
2184
9
      << isa<CXXConstructorDecl>(Dcl);
2185
124k
  } else if (Cxx1yLoc.isValid()) {
2186
1.87k
    SemaRef.Diag(Cxx1yLoc,
2187
1.87k
         SemaRef.getLangOpts().CPlusPlus14
2188
1.87k
           ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2189
7
           : diag::ext_constexpr_body_invalid_stmt)
2190
1.87k
      << isa<CXXConstructorDecl>(Dcl);
2191
1.87k
  }
2192
125k
2193
125k
  if (const CXXConstructorDecl *Constructor
2194
17.9k
        = dyn_cast<CXXConstructorDecl>(Dcl)) {
2195
17.9k
    const CXXRecordDecl *RD = Constructor->getParent();
2196
    // DR1359:
2197
    // - every non-variant non-static data member and base class sub-object
2198
    //   shall be initialized;
2199
    // DR1460:
2200
    // - if the class is a union having variant members, exactly one of them
2201
    //   shall be initialized;
2202
17.9k
    if (RD->isUnion()) {
2203
88
      if (Constructor->getNumCtorInitializers() == 0 &&
2204
7
          RD->hasVariantMembers()) {
2205
0
        if (Kind == Sema::CheckConstexprKind::Diagnose) {
2206
0
          SemaRef.Diag(
2207
0
              Dcl->getLocation(),
2208
0
              SemaRef.getLangOpts().CPlusPlus20
2209
0
                  ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2210
0
                  : diag::ext_constexpr_union_ctor_no_init);
2211
0
        } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2212
0
          return false;
2213
0
        }
2214
17.8k
      }
2215
17.8k
    } else if (!Constructor->isDependentContext() &&
2216
2.73k
               !Constructor->isDelegatingConstructor()) {
2217
2.73k
      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2218
2.73k
2219
      // Skip detailed checking if we have enough initializers, and we would
2220
      // allow at most one initializer per member.
2221
2.73k
      bool AnyAnonStructUnionMembers = false;
2222
2.73k
      unsigned Fields = 0;
2223
2.73k
      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2224
8.17k
           E = RD->field_end(); I != E; 
++I, ++Fields5.44k
) {
2225
5.51k
        if (I->isAnonymousStructOrUnion()) {
2226
69
          AnyAnonStructUnionMembers = true;
2227
69
          break;
2228
69
        }
2229
5.51k
      }
2230
      // DR1460:
2231
      // - if the class is a union-like class, but is not a union, for each of
2232
      //   its anonymous union members having variant members, exactly one of
2233
      //   them shall be initialized;
2234
2.73k
      if (AnyAnonStructUnionMembers ||
2235
2.66k
          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2236
        // Check initialization of non-static data members. Base classes are
2237
        // always initialized so do not need to be checked. Dependent bases
2238
        // might not have initializers in the member initializer list.
2239
79
        llvm::SmallSet<Decl*, 16> Inits;
2240
180
        for (const auto *I: Constructor->inits()) {
2241
180
          if (FieldDecl *FD = I->getMember())
2242
34
            Inits.insert(FD);
2243
146
          else if (IndirectFieldDecl *ID = I->getIndirectMember())
2244
145
            Inits.insert(ID->chain_begin(), ID->chain_end());
2245
180
        }
2246
79
2247
79
        bool Diagnosed = false;
2248
79
        for (auto *I : RD->fields())
2249
175
          if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2250
175
                                             Kind))
2251
0
            return false;
2252
79
      }
2253
2.73k
    }
2254
107k
  } else {
2255
107k
    if (ReturnStmts.empty()) {
2256
      // C++1y doesn't require constexpr functions to contain a 'return'
2257
      // statement. We still do, unless the return type might be void, because
2258
      // otherwise if there's no return statement, the function cannot
2259
      // be used in a core constant expression.
2260
1.03k
      bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2261
1.03k
                (Dcl->getReturnType()->isVoidType() ||
2262
242
                 Dcl->getReturnType()->isDependentType());
2263
1.03k
      switch (Kind) {
2264
321
      case Sema::CheckConstexprKind::Diagnose:
2265
321
        SemaRef.Diag(Dcl->getLocation(),
2266
315
                     OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2267
6
                        : diag::err_constexpr_body_no_return)
2268
321
            << Dcl->isConsteval();
2269
321
        if (!OK)
2270
6
          return false;
2271
315
        break;
2272
315
2273
711
      case Sema::CheckConstexprKind::CheckValid:
2274
        // The formal requirements don't include this rule in C++14, even
2275
        // though the "must be able to produce a constant expression" rules
2276
        // still imply it in some cases.
2277
711
        if (!SemaRef.getLangOpts().CPlusPlus14)
2278
0
          return false;
2279
711
        break;
2280
106k
      }
2281
106k
    } else if (ReturnStmts.size() > 1) {
2282
623
      switch (Kind) {
2283
600
      case Sema::CheckConstexprKind::Diagnose:
2284
600
        SemaRef.Diag(
2285
600
            ReturnStmts.back(),
2286
600
            SemaRef.getLangOpts().CPlusPlus14
2287
599
                ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2288
1
                : diag::ext_constexpr_body_multiple_return);
2289
1.73k
        for (unsigned I = 0; I < ReturnStmts.size() - 1; 
++I1.13k
)
2290
1.13k
          SemaRef.Diag(ReturnStmts[I],
2291
1.13k
                       diag::note_constexpr_body_previous_return);
2292
600
        break;
2293
0
2294
23
      case Sema::CheckConstexprKind::CheckValid:
2295
23
        if (!SemaRef.getLangOpts().CPlusPlus14)
2296
0
          return false;
2297
23
        break;
2298
623
      }
2299
623
    }
2300
107k
  }
2301
125k
2302
  // C++11 [dcl.constexpr]p5:
2303
  //   if no function argument values exist such that the function invocation
2304
  //   substitution would produce a constant expression, the program is
2305
  //   ill-formed; no diagnostic required.
2306
  // C++11 [dcl.constexpr]p3:
2307
  //   - every constructor call and implicit conversion used in initializing the
2308
  //     return value shall be one of those allowed in a constant expression.
2309
  // C++11 [dcl.constexpr]p4:
2310
  //   - every constructor involved in initializing non-static data members and
2311
  //     base class sub-objects shall be a constexpr constructor.
2312
  //
2313
  // Note that this rule is distinct from the "requirements for a constexpr
2314
  // function", so is not checked in CheckValid mode.
2315
125k
  SmallVector<PartialDiagnosticAt, 8> Diags;
2316
125k
  if (Kind == Sema::CheckConstexprKind::Diagnose &&
2317
124k
      !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2318
2.70k
    SemaRef.Diag(Dcl->getLocation(),
2319
2.70k
                 diag::ext_constexpr_function_never_constant_expr)
2320
2.70k
        << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2321
7.78k
    for (size_t I = 0, N = Diags.size(); I != N; 
++I5.08k
)
2322
5.08k
      SemaRef.Diag(Diags[I].first, Diags[I].second);
2323
    // Don't return false here: we allow this for compatibility in
2324
    // system headers.
2325
2.70k
  }
2326
125k
2327
125k
  return true;
2328
125k
}
2329
2330
/// Get the class that is directly named by the current context. This is the
2331
/// class for which an unqualified-id in this scope could name a constructor
2332
/// or destructor.
2333
///
2334
/// If the scope specifier denotes a class, this will be that class.
2335
/// If the scope specifier is empty, this will be the class whose
2336
/// member-specification we are currently within. Otherwise, there
2337
/// is no such class.
2338
2.19M
CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2339
2.19M
  assert(getLangOpts().CPlusPlus && "No class names in C!");
2340
2.19M
2341
2.19M
  if (SS && 
SS->isInvalid()795k
)
2342
31
    return nullptr;
2343
2.19M
2344
2.19M
  if (SS && 
SS->isNotEmpty()795k
) {
2345
334k
    DeclContext *DC = computeDeclContext(*SS, true);
2346
334k
    return dyn_cast_or_null<CXXRecordDecl>(DC);
2347
334k
  }
2348
1.86M
2349
1.86M
  return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2350
1.86M
}
2351
2352
/// isCurrentClassName - Determine whether the identifier II is the
2353
/// name of the class type currently being defined. In the case of
2354
/// nested classes, this will only return true if II is the name of
2355
/// the innermost class.
2356
bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2357
1.94M
                              const CXXScopeSpec *SS) {
2358
1.94M
  CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2359
1.94M
  return CurDecl && 
&II == CurDecl->getIdentifier()1.73M
;
2360
1.94M
}
2361
2362
/// Determine whether the identifier II is a typo for the name of
2363
/// the class type currently being defined. If so, update it to the identifier
2364
/// that should have been used.
2365
40
bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2366
40
  assert(getLangOpts().CPlusPlus && "No class names in C!");
2367
40
2368
40
  if (!getLangOpts().SpellChecking)
2369
0
    return false;
2370
40
2371
40
  CXXRecordDecl *CurDecl;
2372
40
  if (SS && 
SS->isSet()24
&&
!SS->isInvalid()18
) {
2373
18
    DeclContext *DC = computeDeclContext(*SS, true);
2374
18
    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2375
18
  } else
2376
22
    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2377
40
2378
40
  if (CurDecl && 
CurDecl->getIdentifier()36
&&
II != CurDecl->getIdentifier()31
&&
2379
31
      3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2380
10
          < II->getLength()) {
2381
10
    II = CurDecl->getIdentifier();
2382
10
    return true;
2383
10
  }
2384
30
2385
30
  return false;
2386
30
}
2387
2388
/// Determine whether the given class is a base class of the given
2389
/// class, including looking at dependent bases.
2390
static bool findCircularInheritance(const CXXRecordDecl *Class,
2391
23
                                    const CXXRecordDecl *Current) {
2392
23
  SmallVector<const CXXRecordDecl*, 8> Queue;
2393
23
2394
23
  Class = Class->getCanonicalDecl();
2395
24
  while (true) {
2396
7
    for (const auto &I : Current->bases()) {
2397
7
      CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2398
7
      if (!Base)
2399
5
        continue;
2400
2
2401
2
      Base = Base->getDefinition();
2402
2
      if (!Base)
2403
0
        continue;
2404
2
2405
2
      if (Base->getCanonicalDecl() == Class)
2406
1
        return true;
2407
1
2408
1
      Queue.push_back(Base);
2409
1
    }
2410
24
2411
23
    if (Queue.empty())
2412
22
      return false;
2413
1
2414
1
    Current = Queue.pop_back_val();
2415
1
  }
2416
23
2417
0
  return false;
2418
23
}
2419
2420
/// Check the validity of a C++ base class specifier.
2421
///
2422
/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2423
/// and returns NULL otherwise.
2424
CXXBaseSpecifier *
2425
Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2426
                         SourceRange SpecifierRange,
2427
                         bool Virtual, AccessSpecifier Access,
2428
                         TypeSourceInfo *TInfo,
2429
402k
                         SourceLocation EllipsisLoc) {
2430
402k
  QualType BaseType = TInfo->getType();
2431
402k
  if (BaseType->containsErrors()) {
2432
    // Already emitted a diagnostic when parsing the error type.
2433
3
    return nullptr;
2434
3
  }
2435
  // C++ [class.union]p1:
2436
  //   A union shall not have base classes.
2437
402k
  if (Class->isUnion()) {
2438
1
    Diag(Class->getLocation(), diag::err_base_clause_on_union)
2439
1
      << SpecifierRange;
2440
1
    return nullptr;
2441
1
  }
2442
402k
2443
402k
  if (EllipsisLoc.isValid() &&
2444
434
      !TInfo->getType()->containsUnexpandedParameterPack()) {
2445
2
    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2446
2
      << TInfo->getTypeLoc().getSourceRange();
2447
2
    EllipsisLoc = SourceLocation();
2448
2
  }
2449
402k
2450
402k
  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2451
402k
2452
402k
  if (BaseType->isDependentType()) {
2453
    // Make sure that we don't have circular inheritance among our dependent
2454
    // bases. For non-dependent bases, the check for completeness below handles
2455
    // this.
2456
107k
    if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2457
31
      if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2458
29
          ((BaseDecl = BaseDecl->getDefinition()) &&
2459
23
           findCircularInheritance(Class, BaseDecl))) {
2460
3
        Diag(BaseLoc, diag::err_circular_inheritance)
2461
3
          << BaseType << Context.getTypeDeclType(Class);
2462
3
2463
3
        if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2464
1
          Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2465
1
            << BaseType;
2466
3
2467
3
        return nullptr;
2468
3
      }
2469
107k
    }
2470
107k
2471
107k
    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2472
107k
                                          Class->getTagKind() == TTK_Class,
2473
107k
                                          Access, TInfo, EllipsisLoc);
2474
107k
  }
2475
294k
2476
  // Base specifiers must be record types.
2477
294k
  if (!BaseType->isRecordType()) {
2478
6
    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2479
6
    return nullptr;
2480
6
  }
2481
294k
2482
  // C++ [class.union]p1:
2483
  //   A union shall not be used as a base class.
2484
294k
  if (BaseType->isUnionType()) {
2485
1
    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2486
1
    return nullptr;
2487
1
  }
2488
294k
2489
  // For the MS ABI, propagate DLL attributes to base class templates.
2490
294k
  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2491
4.07k
    if (Attr *ClassAttr = getDLLAttr(Class)) {
2492
297
      if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2493
241
              BaseType->getAsCXXRecordDecl())) {
2494
241
        propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2495
241
                                            BaseLoc);
2496
241
      }
2497
297
    }
2498
4.07k
  }
2499
294k
2500
  // C++ [class.derived]p2:
2501
  //   The class-name in a base-specifier shall not be an incompletely
2502
  //   defined class.
2503
294k
  if (RequireCompleteType(BaseLoc, BaseType,
2504
1.08k
                          diag::err_incomplete_base_class, SpecifierRange)) {
2505
1.08k
    Class->setInvalidDecl();
2506
1.08k
    return nullptr;
2507
1.08k
  }
2508
293k
2509
  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2510
293k
  RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2511
293k
  assert(BaseDecl && "Record type has no declaration");
2512
293k
  BaseDecl = BaseDecl->getDefinition();
2513
293k
  assert(BaseDecl && "Base type is not incomplete, but has no definition");
2514
293k
  CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2515
293k
  assert(CXXBaseDecl && "Base type is not a C++ type");
2516
293k
2517
  // Microsoft docs say:
2518
  // "If a base-class has a code_seg attribute, derived classes must have the
2519
  // same attribute."
2520
293k
  const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2521
293k
  const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2522
293k
  if ((DerivedCSA || 
BaseCSA293k
) &&
2523
34
      (!BaseCSA || 
!DerivedCSA30
||
BaseCSA->getName() != DerivedCSA->getName()26
)) {
2524
19
    Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2525
19
    Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2526
19
      << CXXBaseDecl;
2527
19
    return nullptr;
2528
19
  }
2529
293k
2530
  // A class which contains a flexible array member is not suitable for use as a
2531
  // base class:
2532
  //   - If the layout determines that a base comes before another base,
2533
  //     the flexible array member would index into the subsequent base.
2534
  //   - If the layout determines that base comes before the derived class,
2535
  //     the flexible array member would index into the derived class.
2536
293k
  if (CXXBaseDecl->hasFlexibleArrayMember()) {
2537
1
    Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2538
1
      << CXXBaseDecl->getDeclName();
2539
1
    return nullptr;
2540
1
  }
2541
293k
2542
  // C++ [class]p3:
2543
  //   If a class is marked final and it appears as a base-type-specifier in
2544
  //   base-clause, the program is ill-formed.
2545
293k
  if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2546
8
    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2547
8
      << CXXBaseDecl->getDeclName()
2548
8
      << FA->isSpelledAsSealed();
2549
8
    Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2550
8
        << CXXBaseDecl->getDeclName() << FA->getRange();
2551
8
    return nullptr;
2552
8
  }
2553
293k
2554
293k
  if (BaseDecl->isInvalidDecl())
2555
50
    Class->setInvalidDecl();
2556
293k
2557
  // Create the base specifier.
2558
293k
  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2559
293k
                                        Class->getTagKind() == TTK_Class,
2560
293k
                                        Access, TInfo, EllipsisLoc);
2561
293k
}
2562
2563
/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2564
/// one entry in the base class list of a class specifier, for
2565
/// example:
2566
///    class foo : public bar, virtual private baz {
2567
/// 'public bar' and 'virtual private baz' are each base-specifiers.
2568
BaseResult
2569
Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2570
                         ParsedAttributes &Attributes,
2571
                         bool Virtual, AccessSpecifier Access,
2572
                         ParsedType basetype, SourceLocation BaseLoc,
2573
181k
                         SourceLocation EllipsisLoc) {
2574
181k
  if (!classdecl)
2575
49
    return true;
2576
181k
2577
181k
  AdjustDeclIfTemplate(classdecl);
2578
181k
  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2579
181k
  if (!Class)
2580
0
    return true;
2581
181k
2582
  // We haven't yet attached the base specifiers.
2583
181k
  Class->setIsParsingBaseSpecifiers();
2584
181k
2585
  // We do not support any C++11 attributes on base-specifiers yet.
2586
  // Diagnose any attributes we see.
2587
18
  for (const ParsedAttr &AL : Attributes) {
2588
18
    if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2589
0
      continue;
2590
18
    Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2591
17
                          ? (unsigned)diag::warn_unknown_attribute_ignored
2592
1
                          : (unsigned)diag::err_base_specifier_attribute)
2593
18
        << AL;
2594
18
  }
2595
181k
2596
181k
  TypeSourceInfo *TInfo = nullptr;
2597
181k
  GetTypeFromParser(basetype, &TInfo);
2598
181k
2599
181k
  if (EllipsisLoc.isInvalid() &&
2600
181k
      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2601
181k
                                      UPPC_BaseType))
2602
1
    return true;
2603
181k
2604
181k
  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2605
181k
                                                      Virtual, Access, TInfo,
2606
181k
                                                      EllipsisLoc))
2607
181k
    return BaseSpec;
2608
55
  else
2609
55
    Class->setInvalidDecl();
2610
181k
2611
55
  return true;
2612
181k
}
2613
2614
/// Use small set to collect indirect bases.  As this is only used
2615
/// locally, there's no need to abstract the small size parameter.
2616
typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2617
2618
/// Recursively add the bases of Type.  Don't add Type itself.
2619
static void
2620
NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2621
                  const QualType &Type)
2622
34.4k
{
2623
  // Even though the incoming type is a base, it might not be
2624
  // a class -- it could be a template parm, for instance.
2625
34.4k
  if (auto Rec = Type->getAs<RecordType>()) {
2626
28.9k
    auto Decl = Rec->getAsCXXRecordDecl();
2627
28.9k
2628
    // Iterate over its bases.
2629
9.71k
    for (const auto &BaseSpec : Decl->bases()) {
2630
9.71k
      QualType Base = Context.getCanonicalType(BaseSpec.getType())
2631
9.71k
        .getUnqualifiedType();
2632
9.71k
      if (Set.insert(Base).second)
2633
        // If we've not already seen it, recurse.
2634
8.97k
        NoteIndirectBases(Context, Set, Base);
2635
9.71k
    }
2636
28.9k
  }
2637
34.4k
}
2638
2639
/// Performs the actual work of attaching the given base class
2640
/// specifiers to a C++ class.
2641
bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2642
893k
                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2643
893k
 if (Bases.empty())
2644
453k
    return false;
2645
440k
2646
  // Used to keep track of which base types we have already seen, so
2647
  // that we can properly diagnose redundant direct base types. Note
2648
  // that the key is always the unqualified canonical type of the base
2649
  // class.
2650
440k
  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2651
440k
2652
  // Used to track indirect bases so we can see if a direct base is
2653
  // ambiguous.
2654
440k
  IndirectBaseSet IndirectBaseTypes;
2655
440k
2656
  // Copy non-redundant base specifiers into permanent storage.
2657
440k
  unsigned NumGoodBases = 0;
2658
440k
  bool Invalid = false;
2659
893k
  for (unsigned idx = 0; idx < Bases.size(); 
++idx453k
) {
2660
453k
    QualType NewBaseType
2661
453k
      = Context.getCanonicalType(Bases[idx]->getType());
2662
453k
    NewBaseType = NewBaseType.getLocalUnqualifiedType();
2663
453k
2664
453k
    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2665
453k
    if (KnownBase) {
2666
      // C++ [class.mi]p3:
2667
      //   A class shall not be specified as a direct base class of a
2668
      //   derived class more than once.
2669
2
      Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2670
2
          << KnownBase->getType() << Bases[idx]->getSourceRange();
2671
2
2672
      // Delete the duplicate base class specifier; we're going to
2673
      // overwrite its pointer later.
2674
2
      Context.Deallocate(Bases[idx]);
2675
2
2676
2
      Invalid = true;
2677
453k
    } else {
2678
      // Okay, add this new base class.
2679
453k
      KnownBase = Bases[idx];
2680
453k
      Bases[NumGoodBases++] = Bases[idx];
2681
453k
2682
      // Note this base's direct & indirect bases, if there could be ambiguity.
2683
453k
      if (Bases.size() > 1)
2684
25.4k
        NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2685
453k
2686
453k
      if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2687
345k
        const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2688
345k
        if (Class->isInterface() &&
2689
25
              (!RD->isInterfaceLike() ||
2690
15
               KnownBase->getAccessSpecifier() != AS_public)) {
2691
          // The Microsoft extension __interface does not permit bases that
2692
          // are not themselves public interfaces.
2693
11
          Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2694
11
              << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2695
11
              << RD->getSourceRange();
2696
11
          Invalid = true;
2697
11
        }
2698
345k
        if (RD->hasAttr<WeakAttr>())
2699
4
          Class->addAttr(WeakAttr::CreateImplicit(Context));
2700
345k
      }
2701
453k
    }
2702
453k
  }
2703
440k
2704
  // Attach the remaining base class specifiers to the derived class.
2705
440k
  Class->setBases(Bases.data(), NumGoodBases);
2706
440k
2707
  // Check that the only base classes that are duplicate are virtual.
2708
893k
  for (unsigned idx = 0; idx < NumGoodBases; 
++idx453k
) {
2709
    // Check whether this direct base is inaccessible due to ambiguity.
2710
453k
    QualType BaseType = Bases[idx]->getType();
2711
453k
2712
    // Skip all dependent types in templates being used as base specifiers.
2713
    // Checks below assume that the base specifier is a CXXRecord.
2714
453k
    if (BaseType->isDependentType())
2715
107k
      continue;
2716
345k
2717
345k
    CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2718
345k
      .getUnqualifiedType();
2719
345k
2720
345k
    if (IndirectBaseTypes.count(CanonicalBase)) {
2721
356
      CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2722
356
                         /*DetectVirtual=*/true);
2723
356
      bool found
2724
356
        = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2725
356
      assert(found);
2726
356
      (void)found;
2727
356
2728
356
      if (Paths.isAmbiguous(CanonicalBase))
2729
249
        Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2730
249
            << BaseType << getAmbiguousPathsDisplayString(Paths)
2731
249
            << Bases[idx]->getSourceRange();
2732
356
      else
2733
356
        assert(Bases[idx]->isVirtual());
2734
356
    }
2735
345k
2736
    // Delete the base class specifier, since its data has been copied
2737
    // into the CXXRecordDecl.
2738
345k
    Context.Deallocate(Bases[idx]);
2739
345k
  }
2740
440k
2741
440k
  return Invalid;
2742
440k
}
2743
2744
/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2745
/// class, after checking whether there are any duplicate base
2746
/// classes.
2747
void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2748
175k
                               MutableArrayRef<CXXBaseSpecifier *> Bases) {
2749
175k
  if (!ClassDecl || 
Bases.empty()175k
)
2750
215
    return;
2751
175k
2752
175k
  AdjustDeclIfTemplate(ClassDecl);
2753
175k
  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2754
175k
}
2755
2756
/// Determine whether the type \p Derived is a C++ class that is
2757
/// derived from the type \p Base.
2758
5.09M
bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2759
5.09M
  if (!getLangOpts().CPlusPlus)
2760
1.87k
    return false;
2761
5.09M
2762
5.09M
  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2763
5.09M
  if (!DerivedRD)
2764
1.19M
    return false;
2765
3.90M
2766
3.90M
  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2767
3.90M
  if (!BaseRD)
2768
3.45M
    return false;
2769
443k
2770
  // If either the base or the derived type is invalid, don't try to
2771
  // check whether one is derived from the other.
2772
443k
  if (BaseRD->isInvalidDecl() || 
DerivedRD->isInvalidDecl()443k
)
2773
10
    return false;
2774
443k
2775
  // FIXME: In a modules build, do we need the entire path to be visible for us
2776
  // to be able to use the inheritance relationship?
2777
443k
  if (!isCompleteType(Loc, Derived) && 
!DerivedRD->isBeingDefined()6.26k
)
2778
5.70k
    return false;
2779
438k
2780
438k
  return DerivedRD->isDerivedFrom(BaseRD);
2781
438k
}
2782
2783
/// Determine whether the type \p Derived is a C++ class that is
2784
/// derived from the type \p Base.
2785
bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2786
90.4k
                         CXXBasePaths &Paths) {
2787
90.4k
  if (!getLangOpts().CPlusPlus)
2788
196
    return false;
2789
90.3k
2790
90.3k
  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2791
90.3k
  if (!DerivedRD)
2792
0
    return false;
2793
90.3k
2794
90.3k
  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2795
90.3k
  if (!BaseRD)
2796
0
    return false;
2797
90.3k
2798
90.3k
  if (!isCompleteType(Loc, Derived) && 
!DerivedRD->isBeingDefined()68
)
2799
1
    return false;
2800
90.2k
2801
90.2k
  return DerivedRD->isDerivedFrom(BaseRD, Paths);
2802
90.2k
}
2803
2804
static void BuildBasePathArray(const CXXBasePath &Path,
2805
37.0k
                               CXXCastPath &BasePathArray) {
2806
  // We first go backward and check if we have a virtual base.
2807
  // FIXME: It would be better if CXXBasePath had the base specifier for
2808
  // the nearest virtual base.
2809
37.0k
  unsigned Start = 0;
2810
78.6k
  for (unsigned I = Path.size(); I != 0; 
--I41.5k
) {
2811
42.2k
    if (Path[I - 1].Base->isVirtual()) {
2812
642
      Start = I - 1;
2813
642
      break;
2814
642
    }
2815
42.2k
  }
2816
37.0k
2817
  // Now add all bases.
2818
79.3k
  for (unsigned I = Start, E = Path.size(); I != E; 
++I42.2k
)
2819
42.2k
    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2820
37.0k
}
2821
2822
2823
void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2824
1.44k
                              CXXCastPath &BasePathArray) {
2825
1.44k
  assert(BasePathArray.empty() && "Base path array must be empty!");
2826
1.44k
  assert(Paths.isRecordingPaths() && "Must record paths!");
2827
1.44k
  return ::BuildBasePathArray(Paths.front(), BasePathArray);
2828
1.44k
}
2829
/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2830
/// conversion (where Derived and Base are class types) is
2831
/// well-formed, meaning that the conversion is unambiguous (and
2832
/// that all of the base classes are accessible). Returns true
2833
/// and emits a diagnostic if the code is ill-formed, returns false
2834
/// otherwise. Loc is the location where this routine should point to
2835
/// if there is an error, and Range is the source range to highlight
2836
/// if there is an error.
2837
///
2838
/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2839
/// diagnostic for the respective type of error will be suppressed, but the
2840
/// check for ill-formed code will still be performed.
2841
bool
2842
Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2843
                                   unsigned InaccessibleBaseID,
2844
                                   unsigned AmbiguousBaseConvID,
2845
                                   SourceLocation Loc, SourceRange Range,
2846
                                   DeclarationName Name,
2847
                                   CXXCastPath *BasePath,
2848
36.2k
                                   bool IgnoreAccess) {
2849
  // First, determine whether the path from Derived to Base is
2850
  // ambiguous. This is slightly more expensive than checking whether
2851
  // the Derived to Base conversion exists, because here we need to
2852
  // explore multiple paths to determine if there is an ambiguity.
2853
36.2k
  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2854
36.2k
                     /*DetectVirtual=*/false);
2855
36.2k
  bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2856
36.2k
  if (!DerivationOkay)
2857
1
    return true;
2858
36.2k
2859
36.2k
  const CXXBasePath *Path = nullptr;
2860
36.2k
  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2861
36.2k
    Path = &Paths.front();
2862
36.2k
2863
  // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2864
  // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2865
  // user to access such bases.
2866
36.2k
  if (!Path && 
getLangOpts().MSVCCompat59
) {
2867
9
    for (const CXXBasePath &PossiblePath : Paths) {
2868
9
      if (PossiblePath.size() == 1) {
2869
5
        Path = &PossiblePath;
2870
5
        if (AmbiguousBaseConvID)
2871
5
          Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2872
5
              << Base << Derived << Range;
2873
5
        break;
2874
5
      }
2875
9
    }
2876
5
  }
2877
36.2k
2878
36.2k
  if (Path) {
2879
36.2k
    if (!IgnoreAccess) {
2880
      // Check that the base class can be accessed.
2881
35.7k
      switch (
2882
35.7k
          CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2883
116
      case AR_inaccessible:
2884
116
        return true;
2885
35.6k
      case AR_accessible:
2886
35.6k
      case AR_dependent:
2887
35.6k
      case AR_delayed:
2888
35.6k
        break;
2889
36.1k
      }
2890
36.1k
    }
2891
36.1k
2892
    // Build a base path if necessary.
2893
36.1k
    if (BasePath)
2894
35.6k
      ::BuildBasePathArray(*Path, *BasePath);
2895
36.1k
    return false;
2896
36.1k
  }
2897
54
2898
54
  if (AmbiguousBaseConvID) {
2899
    // We know that the derived-to-base conversion is ambiguous, and
2900
    // we're going to produce a diagnostic. Perform the derived-to-base
2901
    // search just one more time to compute all of the possible paths so
2902
    // that we can print them out. This is more expensive than any of
2903
    // the previous derived-to-base checks we've done, but at this point
2904
    // performance isn't as much of an issue.
2905
50
    Paths.clear();
2906
50
    Paths.setRecordingPaths(true);
2907
50
    bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2908
50
    assert(StillOkay && "Can only be used with a derived-to-base conversion");
2909
50
    (void)StillOkay;
2910
50
2911
    // Build up a textual representation of the ambiguous paths, e.g.,
2912
    // D -> B -> A, that will be used to illustrate the ambiguous
2913
    // conversions in the diagnostic. We only print one of the paths
2914
    // to each base class subobject.
2915
50
    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2916
50
2917
50
    Diag(Loc, AmbiguousBaseConvID)
2918
50
    << Derived << Base << PathDisplayStr << Range << Name;
2919
50
  }
2920
54
  return true;
2921
54
}
2922
2923
bool
2924
Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2925
                                   SourceLocation Loc, SourceRange Range,
2926
                                   CXXCastPath *BasePath,
2927
30.7k
                                   bool IgnoreAccess) {
2928
30.7k
  return CheckDerivedToBaseConversion(
2929
30.7k
      Derived, Base, diag::err_upcast_to_inaccessible_base,
2930
30.7k
      diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2931
30.7k
      BasePath, IgnoreAccess);
2932
30.7k
}
2933
2934
2935
/// Builds a string representing ambiguous paths from a
2936
/// specific derived class to different subobjects of the same base
2937
/// class.
2938
///
2939
/// This function builds a string that can be used in error messages
2940
/// to show the different paths that one can take through the
2941
/// inheritance hierarchy to go from the derived class to different
2942
/// subobjects of a base class. The result looks something like this:
2943
/// @code
2944
/// struct D -> struct B -> struct A
2945
/// struct D -> struct C -> struct A
2946
/// @endcode
2947
331
std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2948
331
  std::string PathDisplayStr;
2949
331
  std::set<unsigned> DisplayedPaths;
2950
331
  for (CXXBasePaths::paths_iterator Path = Paths.begin();
2951
1.17k
       Path != Paths.end(); 
++Path844
) {
2952
844
    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2953
      // We haven't displayed a path to this particular base
2954
      // class subobject yet.
2955
780
      PathDisplayStr += "\n    ";
2956
780
      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2957
780
      for (CXXBasePath::const_iterator Element = Path->begin();
2958
2.37k
           Element != Path->end(); 
++Element1.59k
)
2959
1.59k
        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2960
780
    }
2961
844
  }
2962
331
2963
331
  return PathDisplayStr;
2964
331
}
2965
2966
//===----------------------------------------------------------------------===//
2967
// C++ class member Handling
2968
//===----------------------------------------------------------------------===//
2969
2970
/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2971
bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2972
                                SourceLocation ColonLoc,
2973
146k
                                const ParsedAttributesView &Attrs) {
2974
146k
  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2975
146k
  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2976
146k
                                                  ASLoc, ColonLoc);
2977
146k
  CurContext->addHiddenDecl(ASDecl);
2978
146k
  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2979
146k
}
2980
2981
/// CheckOverrideControl - Check C++11 override control semantics.
2982
3.29M
void Sema::CheckOverrideControl(NamedDecl *D) {
2983
3.29M
  if (D->isInvalidDecl())
2984
850
    return;
2985
3.29M
2986
  // We only care about "override" and "final" declarations.
2987
3.29M
  if (!D->hasAttr<OverrideAttr>() && 
!D->hasAttr<FinalAttr>()3.29M
)
2988
3.29M
    return;
2989
537
2990
537
  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2991
537
2992
  // We can't check dependent instance methods.
2993
537
  if (MD && 
MD->isInstance()535
&&
2994
534
      (MD->getParent()->hasAnyDependentBases() ||
2995
516
       MD->getType()->isDependentType()))
2996
24
    return;
2997
513
2998
513
  if (MD && 
!MD->isVirtual()511
) {
2999
    // If we have a non-virtual method, check if if hides a virtual method.
3000
    // (In that case, it's most likely the method has the wrong type.)
3001
18
    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3002
18
    FindHiddenVirtualMethods(MD, OverloadedMethods);
3003
18
3004
18
    if (!OverloadedMethods.empty()) {
3005
4
      if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3006
3
        Diag(OA->getLocation(),
3007
3
             diag::override_keyword_hides_virtual_member_function)
3008
3
          << "override" << (OverloadedMethods.size() > 1);
3009
1
      } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3010
1
        Diag(FA->getLocation(),
3011
1
             diag::override_keyword_hides_virtual_member_function)
3012
1
          << (FA->isSpelledAsSealed() ? 
"sealed"0
: "final")
3013
1
          << (OverloadedMethods.size() > 1);
3014
1
      }
3015
4
      NoteHiddenVirtualMethods(MD, OverloadedMethods);
3016
4
      MD->setInvalidDecl();
3017
4
      return;
3018
4
    }
3019
    // Fall through into the general case diagnostic.
3020
    // FIXME: We might want to attempt typo correction here.
3021
18
  }
3022
509
3023
509
  if (!MD || 
!MD->isVirtual()507
) {
3024
16
    if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3025
10
      Diag(OA->getLocation(),
3026
10
           diag::override_keyword_only_allowed_on_virtual_member_functions)
3027
10
        << "override" << FixItHint::CreateRemoval(OA->getLocation());
3028
10
      D->dropAttr<OverrideAttr>();
3029
10
    }
3030
16
    if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3031
6
      Diag(FA->getLocation(),
3032
6
           diag::override_keyword_only_allowed_on_virtual_member_functions)
3033
6
        << (FA->isSpelledAsSealed() ? 
"sealed"0
: "final")
3034
6
        << FixItHint::CreateRemoval(FA->getLocation());
3035
6
      D->dropAttr<FinalAttr>();
3036
6
    }
3037
16
    return;
3038
16
  }
3039
493
3040
  // C++11 [class.virtual]p5:
3041
  //   If a function is marked with the virt-specifier override and
3042
  //   does not override a member function of a base class, the program is
3043
  //   ill-formed.
3044
493
  bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3045
493
  if (MD->hasAttr<OverrideAttr>() && 
!HasOverriddenMethods422
)
3046
4
    Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3047
4
      << MD->getDeclName();
3048
493
}
3049
3050
140k
void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3051
140k
  if (D->isInvalidDecl() || 
D->hasAttr<OverrideAttr>()140k
)
3052
38
    return;
3053
140k
  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3054
140k
  if (!MD || MD->isImplicit() || 
MD->hasAttr<FinalAttr>()111k
)
3055
29.9k
    return;
3056
110k
3057
110k
  SourceLocation Loc = MD->getLocation();
3058
110k
  SourceLocation SpellingLoc = Loc;
3059
110k
  if (getSourceManager().isMacroArgExpansion(Loc))
3060
1
    SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3061
110k
  SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3062
110k
  if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3063
108k
      return;
3064
2.78k
3065
2.78k
  if (MD->size_overridden_methods() > 0) {
3066
1.79k
    auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3067
1.79k
      unsigned DiagID =
3068
1.79k
          Inconsistent && 
!Diags.isIgnored(DiagInconsistent, MD->getLocation())6
3069
4
              ? DiagInconsistent
3070
1.78k
              : DiagSuggest;
3071
1.79k
      Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3072
1.79k
      const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3073
1.79k
      Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3074
1.79k
    };
3075
1.79k
    if (isa<CXXDestructorDecl>(MD))
3076
362
      EmitDiag(
3077
362
          diag::warn_inconsistent_destructor_marked_not_override_overriding,
3078
362
          diag::warn_suggest_destructor_marked_not_override_overriding);
3079
1.43k
    else
3080
1.43k
      EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3081
1.43k
               diag::warn_suggest_function_marked_not_override_overriding);
3082
1.79k
  }
3083
2.78k
}
3084
3085
/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3086
/// function overrides a virtual member function marked 'final', according to
3087
/// C++11 [class.virtual]p4.
3088
bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3089
31.4k
                                                  const CXXMethodDecl *Old) {
3090
31.4k
  FinalAttr *FA = Old->getAttr<FinalAttr>();
3091
31.4k
  if (!FA)
3092
31.4k
    return false;
3093
7
3094
7
  Diag(New->getLocation(), diag::err_final_function_overridden)
3095
7
    << New->getDeclName()
3096
7
    << FA->isSpelledAsSealed();
3097
7
  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3098
7
  return true;
3099
7
}
3100
3101
138
static bool InitializationHasSideEffects(const FieldDecl &FD) {
3102
138
  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3103
  // FIXME: Destruction of ObjC lifetime types has side-effects.
3104
138
  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3105
28
    return !RD->isCompleteDefinition() ||
3106
28
           !RD->hasTrivialDefaultConstructor() ||
3107
23
           !RD->hasTrivialDestructor();
3108
110
  return false;
3109
110
}
3110
3111
2.36M
static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3112
2.36M
  ParsedAttributesView::const_iterator Itr =
3113
1.12M
      llvm::find_if(list, [](const ParsedAttr &AL) {
3114
1.12M
        return AL.isDeclspecPropertyAttribute();
3115
1.12M
      });
3116
2.36M
  if (Itr != list.end())
3117
99
    return &*Itr;
3118
2.36M
  return nullptr;
3119
2.36M
}
3120
3121
// Check if there is a field shadowing.
3122
void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3123
                                      DeclarationName FieldName,
3124
                                      const CXXRecordDecl *RD,
3125
1.86M
                                      bool DeclIsField) {
3126
1.86M
  if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3127
1.86M
    return;
3128
52
3129
  // To record a shadowed field in a base
3130
52
  std::map<CXXRecordDecl*, NamedDecl*> Bases;
3131
52
  auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3132
83
                           CXXBasePath &Path) {
3133
83
    const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3134
    // Record an ambiguous path directly
3135
83
    if (Bases.find(Base) != Bases.end())
3136
10
      return true;
3137
73
    for (const auto Field : Base->lookup(FieldName)) {
3138
23
      if ((isa<FieldDecl>(Field) || 
isa<IndirectFieldDecl>(Field)3
) &&
3139
21
          Field->getAccess() != AS_private) {
3140
15
        assert(Field->getAccess() != AS_none);
3141
15
        assert(Bases.find(Base) == Bases.end());
3142
15
        Bases[Base] = Field;
3143
15
        return true;
3144
15
      }
3145
23
    }
3146
58
    return false;
3147
73
  };
3148
52
3149
52
  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3150
52
                     /*DetectVirtual=*/true);
3151
52
  if (!RD->lookupInBases(FieldShadowed, Paths))
3152
39
    return;
3153
13
3154
25
  
for (const auto &P : Paths)13
{
3155
25
    auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3156
25
    auto It = Bases.find(Base);
3157
    // Skip duplicated bases
3158
25
    if (It == Bases.end())
3159
7
      continue;
3160
18
    auto BaseField = It->second;
3161
18
    assert(BaseField->getAccess() != AS_private);
3162
18
    if (AS_none !=
3163
14
        CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3164
14
      Diag(Loc, diag::warn_shadow_field)
3165
14
        << FieldName << RD << Base << DeclIsField;
3166
14
      Diag(BaseField->getLocation(), diag::note_shadow_field);
3167
14
      Bases.erase(It);
3168
14
    }
3169
18
  }
3170
13
}
3171
3172
/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3173
/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3174
/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3175
/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3176
/// present (but parsing it has been deferred).
3177
NamedDecl *
3178
Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3179
                               MultiTemplateParamsArg TemplateParameterLists,
3180
                               Expr *BW, const VirtSpecifiers &VS,
3181
2.36M
                               InClassInitStyle InitStyle) {
3182
2.36M
  const DeclSpec &DS = D.getDeclSpec();
3183
2.36M
  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3184
2.36M
  DeclarationName Name = NameInfo.getName();
3185
2.36M
  SourceLocation Loc = NameInfo.getLoc();
3186
2.36M
3187
  // For anonymous bitfields, the location should point to the type.
3188
2.36M
  if (Loc.isInvalid())
3189
1
    Loc = D.getBeginLoc();
3190
2.36M
3191
2.36M
  Expr *BitWidth = static_cast<Expr*>(BW);
3192
2.36M
3193
2.36M
  assert(isa<CXXRecordDecl>(CurContext));
3194
2.36M
  assert(!DS.isFriendSpecified());
3195
2.36M
3196
2.36M
  bool isFunc = D.isDeclarationOfFunction();
3197
2.36M
  const ParsedAttr *MSPropertyAttr =
3198
2.36M
      getMSPropertyAttr(D.getDeclSpec().getAttributes());
3199
2.36M
3200
2.36M
  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3201
    // The Microsoft extension __interface only permits public member functions
3202
    // and prohibits constructors, destructors, operators, non-public member
3203
    // functions, static methods and data members.
3204
23
    unsigned InvalidDecl;
3205
23
    bool ShowDeclName = true;
3206
23
    if (!isFunc &&
3207
3
        (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || 
MSPropertyAttr2
))
3208
2
      InvalidDecl = 0;
3209
21
    else if (!isFunc)
3210
1
      InvalidDecl = 1;
3211
20
    else if (AS != AS_public)
3212
2
      InvalidDecl = 2;
3213
18
    else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3214
1
      InvalidDecl = 3;
3215
17
    else switch (Name.getNameKind()) {
3216
1
      case DeclarationName::CXXConstructorName:
3217
1
        InvalidDecl = 4;
3218
1
        ShowDeclName = false;
3219
1
        break;
3220
0
3221
1
      case DeclarationName::CXXDestructorName:
3222
1
        InvalidDecl = 5;
3223
1
        ShowDeclName = false;
3224
1
        break;
3225
0
3226
2
      case DeclarationName::CXXOperatorName:
3227
2
      case DeclarationName::CXXConversionFunctionName:
3228
2
        InvalidDecl = 6;
3229
2
        break;
3230
2
3231
13
      default:
3232
13
        InvalidDecl = 0;
3233
13
        break;
3234
23
    }
3235
23
3236
23
    if (InvalidDecl) {
3237
8
      if (ShowDeclName)
3238
6
        Diag(Loc, diag::err_invalid_member_in_interface)
3239
6
          << (InvalidDecl-1) << Name;
3240
2
      else
3241
2
        Diag(Loc, diag::err_invalid_member_in_interface)
3242
2
          << (InvalidDecl-1) << "";
3243
8
      return nullptr;
3244
8
    }
3245
2.36M
  }
3246
2.36M
3247
  // C++ 9.2p6: A member shall not be declared to have automatic storage
3248
  // duration (auto, register) or with the extern storage-class-specifier.
3249
  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3250
  // data members and cannot be applied to names declared const or static,
3251
  // and cannot be applied to reference members.
3252
2.36M
  switch (DS.getStorageClassSpec()) {
3253
2.35M
  case DeclSpec::SCS_unspecified:
3254
2.35M
  case DeclSpec::SCS_typedef:
3255
2.35M
  case DeclSpec::SCS_static:
3256
2.35M
    break;
3257
2.82k
  case DeclSpec::SCS_mutable:
3258
2.82k
    if (isFunc) {
3259
4
      Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3260
4
3261
      // FIXME: It would be nicer if the keyword was ignored only for this
3262
      // declarator. Otherwise we could get follow-up errors.
3263
4
      D.getMutableDeclSpec().ClearStorageClassSpecs();
3264
4
    }
3265
2.82k
    break;
3266
19
  default:
3267
19
    Diag(DS.getStorageClassSpecLoc(),
3268
19
         diag::err_storageclass_invalid_for_member);
3269
19
    D.getMutableDeclSpec().ClearStorageClassSpecs();
3270
19
    break;
3271
2.36M
  }
3272
2.36M
3273
2.36M
  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3274
579k
                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3275
1.78M
                      !isFunc);
3276
2.36M
3277
2.36M
  if (DS.hasConstexprSpecifier() && 
isInstField200k
) {
3278
24
    SemaDiagnosticBuilder B =
3279
24
        Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3280
24
    SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3281
24
    if (InitStyle == ICIS_NoInit) {
3282
13
      B << 0 << 0;
3283
13
      if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3284
2
        B << FixItHint::CreateRemoval(ConstexprLoc);
3285
11
      else {
3286
11
        B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3287
11
        D.getMutableDeclSpec().ClearConstexprSpec();
3288
11
        const char *PrevSpec;
3289
11
        unsigned DiagID;
3290
11
        bool Failed = D.getMutableDeclSpec().SetTypeQual(
3291
11
            DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3292
11
        (void)Failed;
3293
11
        assert(!Failed && "Making a constexpr member const shouldn't fail");
3294
11
      }
3295
11
    } else {
3296
11
      B << 1;
3297
11
      const char *PrevSpec;
3298
11
      unsigned DiagID;
3299
11
      if (D.getMutableDeclSpec().SetStorageClassSpec(
3300
11
          *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3301
5
          Context.getPrintingPolicy())) {
3302
5
        assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3303
5
               "This is the only DeclSpec that should fail to be applied");
3304
5
        B << 1;
3305
6
      } else {
3306
6
        B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3307
6
        isInstField = false;
3308
6
      }
3309
11
    }
3310
24
  }
3311
2.36M
3312
2.36M
  NamedDecl *Member;
3313
2.36M
  if (isInstField) {
3314
979k
    CXXScopeSpec &SS = D.getCXXScopeSpec();
3315
979k
3316
    // Data members must have identifiers for names.
3317
979k
    if (!Name.isIdentifier()) {
3318
9
      Diag(Loc, diag::err_bad_variable_name)
3319
9
        << Name;
3320
9
      return nullptr;
3321
9
    }
3322
979k
3323
979k
    IdentifierInfo *II = Name.getAsIdentifierInfo();
3324
979k
3325
    // Member field could not be with "template" keyword.
3326
    // So TemplateParameterLists should be empty in this case.
3327
979k
    if (TemplateParameterLists.size()) {
3328
18
      TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3329
18
      if (TemplateParams->size()) {
3330
        // There is no such thing as a member field template.
3331
17
        Diag(D.getIdentifierLoc(), diag::err_template_member)
3332
17
            << II
3333
17
            << SourceRange(TemplateParams->getTemplateLoc(),
3334
17
                TemplateParams->getRAngleLoc());
3335
1
      } else {
3336
        // There is an extraneous 'template<>' for this member.
3337
1
        Diag(TemplateParams->getTemplateLoc(),
3338
1
            diag::err_template_member_noparams)
3339
1
            << II
3340
1
            << SourceRange(TemplateParams->getTemplateLoc(),
3341
1
                TemplateParams->getRAngleLoc());
3342
1
      }
3343
18
      return nullptr;
3344
18
    }
3345
979k
3346
979k
    if (SS.isSet() && 
!SS.isInvalid()6
) {
3347
      // The user provided a superfluous scope specifier inside a class
3348
      // definition:
3349
      //
3350
      // class X {
3351
      //   int X::member;
3352
      // };
3353
6
      if (DeclContext *DC = computeDeclContext(SS, false))
3354
2
        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3355
2
                                     D.getName().getKind() ==
3356
2
                                         UnqualifiedIdKind::IK_TemplateId);
3357
4
      else
3358
4
        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3359
4
          << Name << SS.getRange();
3360
6
3361
6
      SS.clear();
3362
6
    }
3363
979k
3364
979k
    if (MSPropertyAttr) {
3365
99
      Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3366
99
                                BitWidth, InitStyle, AS, *MSPropertyAttr);
3367
99
      if (!Member)
3368
3
        return nullptr;
3369
96
      isInstField = false;
3370
979k
    } else {
3371
979k
      Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3372
979k
                                BitWidth, InitStyle, AS);
3373
979k
      if (!Member)
3374
8
        return nullptr;
3375
979k
    }
3376
979k
3377
979k
    CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3378
1.38M
  } else {
3379
1.38M
    Member = HandleDeclarator(S, D, TemplateParameterLists);
3380
1.38M
    if (!Member)
3381
111
      return nullptr;
3382
1.38M
3383
    // Non-instance-fields can't have a bitfield.
3384
1.38M
    if (BitWidth) {
3385
9
      if (Member->isInvalidDecl()) {
3386
        // don't emit another diagnostic.
3387
9
      } else if (isa<VarDecl>(Member) || 
isa<VarTemplateDecl>(Member)7
) {
3388
        // C++ 9.6p3: A bit-field shall not be a static member.
3389
        // "static member 'A' cannot be a bit-field"
3390
5
        Diag(Loc, diag::err_static_not_bitfield)
3391
5
          << Name << BitWidth->getSourceRange();
3392
4
      } else if (isa<TypedefDecl>(Member)) {
3393
        // "typedef member 'x' cannot be a bit-field"
3394
2
        Diag(Loc, diag::err_typedef_not_bitfield)
3395
2
          << Name << BitWidth->getSourceRange();
3396
2
      } else {
3397
        // A function typedef ("typedef int f(); f a;").
3398
        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3399
2
        Diag(Loc, diag::err_not_integral_type_bitfield)
3400
2
          << Name << cast<ValueDecl>(Member)->getType()
3401
2
          << BitWidth->getSourceRange();
3402
2
      }
3403
9
3404
9
      BitWidth = nullptr;
3405
9
      Member->setInvalidDecl();
3406
9
    }
3407
1.38M
3408
1.38M
    NamedDecl *NonTemplateMember = Member;
3409
1.38M
    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3410
144k
      NonTemplateMember = FunTmpl->getTemplatedDecl();
3411
1.23M
    else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3412
395
      NonTemplateMember = VarTmpl->getTemplatedDecl();
3413
1.38M
3414
1.38M
    Member->setAccess(AS);
3415
1.38M
3416
    // If we have declared a member function template or static data member
3417
    // template, set the access of the templated declaration as well.
3418
1.38M
    if (NonTemplateMember != Member)
3419
144k
      NonTemplateMember->setAccess(AS);
3420
1.38M
3421
    // C++ [temp.deduct.guide]p3:
3422
    //   A deduction guide [...] for a member class template [shall be
3423
    //   declared] with the same access [as the template].
3424
1.38M
    if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3425
42
      auto *TD = DG->getDeducedTemplate();
3426
      // Access specifiers are only meaningful if both the template and the
3427
      // deduction guide are from the same scope.
3428
42
      if (AS != TD->getAccess() &&
3429
5
          TD->getDeclContext()->getRedeclContext()->Equals(
3430
4
              DG->getDeclContext()->getRedeclContext())) {
3431
4
        Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3432
4
        Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3433
4
            << TD->getAccess();
3434
4
        const AccessSpecDecl *LastAccessSpec = nullptr;
3435
62
        for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3436
62
          if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3437
9
            LastAccessSpec = AccessSpec;
3438
62
        }
3439
4
        assert(LastAccessSpec && "differing access with no access specifier");
3440
4
        Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3441
4
            << AS;
3442
4
      }
3443
42
    }
3444
1.38M
  }
3445
2.36M
3446
2.36M
  if (VS.isOverrideSpecified())
3447
438
    Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3448
438
                                         AttributeCommonInfo::AS_Keyword));
3449
2.36M
  if (VS.isFinalSpecified())
3450
89
    Member->addAttr(FinalAttr::Create(
3451
89
        Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3452
89
        static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3453
2.36M
3454
2.36M
  if (VS.getLastLocation().isValid()) {
3455
    // Update the end location of a method that has a virt-specifiers.
3456
516
    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3457
514
      MD->setRangeEnd(VS.getLastLocation());
3458
516
  }
3459
2.36M
3460
2.36M
  CheckOverrideControl(Member);
3461
2.36M
3462
2.36M
  assert((Name || isInstField) && "No identifier for non-field ?");
3463
2.36M
3464
2.36M
  if (isInstField) {
3465
979k
    FieldDecl *FD = cast<FieldDecl>(Member);
3466
979k
    FieldCollector->Add(FD);
3467
979k
3468
979k
    if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3469
      // Remember all explicit private FieldDecls that have a name, no side
3470
      // effects and are not part of a dependent type declaration.
3471
549
      if (!FD->isImplicit() && FD->getDeclName() &&
3472
534
          FD->getAccess() == AS_private &&
3473
163
          !FD->hasAttr<UnusedAttr>() &&
3474
157
          !FD->getParent()->isDependentContext() &&
3475
138
          !InitializationHasSideEffects(*FD))
3476
129
        UnusedPrivateFields.insert(FD);
3477
549
    }
3478
979k
  }
3479
2.36M
3480
2.36M
  return Member;
3481
2.36M
}
3482
3483
namespace {
3484
  class UninitializedFieldVisitor
3485
      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3486
    Sema &S;
3487
    // List of Decls to generate a warning on.  Also remove Decls that become
3488
    // initialized.
3489
    llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3490
    // List of base classes of the record.  Classes are removed after their
3491
    // initializers.
3492
    llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3493
    // Vector of decls to be removed from the Decl set prior to visiting the
3494
    // nodes.  These Decls may have been initialized in the prior initializer.
3495
    llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3496
    // If non-null, add a note to the warning pointing back to the constructor.
3497
    const CXXConstructorDecl *Constructor;
3498
    // Variables to hold state when processing an initializer list.  When
3499
    // InitList is true, special case initialization of FieldDecls matching
3500
    // InitListFieldDecl.
3501
    bool InitList;
3502
    FieldDecl *InitListFieldDecl;
3503
    llvm::SmallVector<unsigned, 4> InitFieldIndex;
3504
3505
  public:
3506
    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3507
    UninitializedFieldVisitor(Sema &S,
3508
                              llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3509
                              llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3510
      : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3511
32.1k
        Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3512
3513
    // Returns true if the use of ME is not an uninitialized use.
3514
    bool IsInitListMemberExprInitialized(MemberExpr *ME,
3515
65
                                         bool CheckReferenceOnly) {
3516
65
      llvm::SmallVector<FieldDecl*, 4> Fields;
3517
65
      bool ReferenceField = false;
3518
227
      while (ME) {
3519
162
        FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3520
162
        if (!FD)
3521
0
          return false;
3522
162
        Fields.push_back(FD);
3523
162
        if (FD->getType()->isReferenceType())
3524
12
          ReferenceField = true;
3525
162
        ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3526
162
      }
3527
65
3528
      // Binding a reference to an uninitialized field is not an
3529
      // uninitialized use.
3530
65
      if (CheckReferenceOnly && 
!ReferenceField12
)
3531
6
        return true;
3532
59
3533
59
      llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3534
      // Discard the first field since it is the field decl that is being
3535
      // initialized.
3536
150
      for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; 
++I91
) {
3537
91
        UsedFieldIndex.push_back((*I)->getFieldIndex());
3538
91
      }
3539
59
3540
59
      for (auto UsedIter = UsedFieldIndex.begin(),
3541
59
                UsedEnd = UsedFieldIndex.end(),
3542
59
                OrigIter = InitFieldIndex.begin(),
3543
59
                OrigEnd = InitFieldIndex.end();
3544
95
           UsedIter != UsedEnd && 
OrigIter != OrigEnd75
;
++UsedIter, ++OrigIter36
) {
3545
75
        if (*UsedIter < *OrigIter)
3546
18
          return true;
3547
57
        if (*UsedIter > *OrigIter)
3548
21
          break;
3549
57
      }
3550
59
3551
41
      return false;
3552
59
    }
3553
3554
    void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3555
5.25k
                          bool AddressOf) {
3556
5.25k
      if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3557
9
        return;
3558
5.24k
3559
      // FieldME is the inner-most MemberExpr that is not an anonymous struct
3560
      // or union.
3561
5.24k
      MemberExpr *FieldME = ME;
3562
5.24k
3563
5.24k
      bool AllPODFields = FieldME->getType().isPODType(S.Context);
3564
5.24k
3565
5.24k
      Expr *Base = ME;
3566
10.6k
      while (MemberExpr *SubME =
3567
5.43k
                 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3568
5.43k
3569
5.43k
        if (isa<VarDecl>(SubME->getMemberDecl()))
3570
8
          return;
3571
5.42k
3572
5.42k
        if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3573
5.32k
          if (!FD->isAnonymousStructOrUnion())
3574
5.30k
            FieldME = SubME;
3575
5.42k
3576
5.42k
        if (!FieldME->getType().isPODType(S.Context))
3577
324
          AllPODFields = false;
3578
5.42k
3579
5.42k
        Base = SubME->getBase();
3580
5.42k
      }
3581
5.24k
3582
5.23k
      if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3583
4.71k
        Visit(Base);
3584
4.71k
        return;
3585
4.71k
      }
3586
525
3587
525
      if (AddressOf && 
AllPODFields3
)
3588
2
        return;
3589
523
3590
523
      ValueDecl* FoundVD = FieldME->getMemberDecl();
3591
523
3592
523
      if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3593
10
        while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3594
0
          BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3595
0
        }
3596
10
3597
10
        if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3598
7
          QualType T = BaseCast->getType();
3599
7
          if (T->isPointerType() &&
3600
7
              BaseClasses.count(T->getPointeeType())) {
3601
4
            S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3602
4
                << T->getPointeeType() << FoundVD;
3603
4
          }
3604
7
        }
3605
10
      }
3606
523
3607
523
      if (!Decls.count(FoundVD))
3608
191
        return;
3609
332
3610
332
      const bool IsReference = FoundVD->getType()->isReferenceType();
3611
332
3612
332
      if (InitList && 
!AddressOf70
&&
FoundVD == InitListFieldDecl70
) {
3613
        // Special checking for initializer lists.
3614
65
        if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3615
24
          return;
3616
24
        }
3617
267
      } else {
3618
        // Prevent double warnings on use of unbounded references.
3619
267
        if (CheckReferenceOnly && 
!IsReference76
)
3620
72
          return;
3621
236
      }
3622
236
3623
236
      unsigned diag = IsReference
3624
5
          ? diag::warn_reference_field_is_uninit
3625
231
          : diag::warn_field_is_uninit;
3626
236
      S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3627
236
      if (Constructor)
3628
43
        S.Diag(Constructor->getLocation(),
3629
43
               diag::note_uninit_in_this_constructor)
3630
43
          << (Constructor->isDefaultConstructor() && 
Constructor->isImplicit()42
);
3631
236
3632
236
    }
3633
3634
13.7k
    void HandleValue(Expr *E, bool AddressOf) {
3635
13.7k
      E = E->IgnoreParens();
3636
13.7k
3637
13.7k
      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3638
5.08k
        HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3639
5.08k
                         AddressOf /*AddressOf*/);
3640
5.08k
        return;
3641
5.08k
      }
3642
8.61k
3643
8.61k
      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3644
16
        Visit(CO->getCond());
3645
16
        HandleValue(CO->getTrueExpr(), AddressOf);
3646
16
        HandleValue(CO->getFalseExpr(), AddressOf);
3647
16
        return;
3648
16
      }
3649
8.60k
3650
8.60k
      if (BinaryConditionalOperator *BCO =
3651
8
              dyn_cast<BinaryConditionalOperator>(E)) {
3652
8
        Visit(BCO->getCond());
3653
8
        HandleValue(BCO->getFalseExpr(), AddressOf);
3654
8
        return;
3655
8
      }
3656
8.59k
3657
8.59k
      if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3658
8
        HandleValue(OVE->getSourceExpr(), AddressOf);
3659
8
        return;
3660
8
      }
3661
8.58k
3662
8.58k
      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3663
35
        switch (BO->getOpcode()) {
3664
16
        default:
3665
16
          break;
3666
4
        case(BO_PtrMemD):
3667
4
        case(BO_PtrMemI):
3668
4
          HandleValue(BO->getLHS(), AddressOf);
3669
4
          Visit(BO->getRHS());
3670
4
          return;
3671
15
        case(BO_Comma):
3672
15
          Visit(BO->getLHS());
3673
15
          HandleValue(BO->getRHS(), AddressOf);
3674
15
          return;
3675
8.56k
        }
3676
8.56k
      }
3677
8.56k
3678
8.56k
      Visit(E);
3679
8.56k
    }
3680
3681
274
    void CheckInitListExpr(InitListExpr *ILE) {
3682
274
      InitFieldIndex.push_back(0);
3683
738
      for (auto Child : ILE->children()) {
3684
738
        if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3685
89
          CheckInitListExpr(SubList);
3686
649
        } else {
3687
649
          Visit(Child);
3688
649
        }
3689
738
        ++InitFieldIndex.back();
3690
738
      }
3691
274
      InitFieldIndex.pop_back();
3692
274
    }
3693
3694
    void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3695
30.4k
                          FieldDecl *Field, const Type *BaseClass) {
3696
      // Remove Decls that may have been initialized in the previous
3697
      // initializer.
3698
30.4k
      for (ValueDecl* VD : DeclsToRemove)
3699
9
        Decls.erase(VD);
3700
30.4k
      DeclsToRemove.clear();
3701
30.4k
3702
30.4k
      Constructor = FieldConstructor;
3703
30.4k
      InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3704
30.4k
3705
30.4k
      if (ILE && 
Field202
) {
3706
185
        InitList = true;
3707
185
        InitListFieldDecl = Field;
3708
185
        InitFieldIndex.clear();
3709
185
        CheckInitListExpr(ILE);
3710
30.3k
      } else {
3711
30.3k
        InitList = false;
3712
30.3k
        Visit(E);
3713
30.3k
      }
3714
30.4k
3715
30.4k
      if (Field)
3716
22.7k
        Decls.erase(Field);
3717
30.4k
      if (BaseClass)
3718
7.65k
        BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3719
30.4k
    }
3720
3721
174
    void VisitMemberExpr(MemberExpr *ME) {
3722
      // All uses of unbounded reference fields will warn.
3723
174
      HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3724
174
    }
3725
3726
15.5k
    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3727
15.5k
      if (E->getCastKind() == CK_LValueToRValue) {
3728
13.0k
        HandleValue(E->getSubExpr(), false /*AddressOf*/);
3729
13.0k
        return;
3730
13.0k
      }
3731
2.48k
3732
2.48k
      Inherited::VisitImplicitCastExpr(E);
3733
2.48k
    }
3734
3735
10.6k
    void VisitCXXConstructExpr(CXXConstructExpr *E) {
3736
10.6k
      if (E->getConstructor()->isCopyConstructor()) {
3737
262
        Expr *ArgExpr = E->getArg(0);
3738
262
        if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3739
3
          if (ILE->getNumInits() == 1)
3740
3
            ArgExpr = ILE->getInit(0);
3741
262
        if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3742
199
          if (ICE->getCastKind() == CK_NoOp)
3743
178
            ArgExpr = ICE->getSubExpr();
3744
262
        HandleValue(ArgExpr, false /*AddressOf*/);
3745
262
        return;
3746
262
      }
3747
10.3k
      Inherited::VisitCXXConstructExpr(E);
3748
10.3k
    }
3749
3750
89
    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3751
89
      Expr *Callee = E->getCallee();
3752
89
      if (isa<MemberExpr>(Callee)) {
3753
89
        HandleValue(Callee, false /*AddressOf*/);
3754
89
        for (auto Arg : E->arguments())
3755
3
          Visit(Arg);
3756
89
        return;
3757
89
      }
3758
0
3759
0
      Inherited::VisitCXXMemberCallExpr(E);
3760
0
    }
3761
3762
260
    void VisitCallExpr(CallExpr *E) {
3763
      // Treat std::move as a use.
3764
260
      if (E->isCallToStdMove()) {
3765
44
        HandleValue(E->getArg(0), /*AddressOf=*/false);
3766
44
        return;
3767
44
      }
3768
216
3769
216
      Inherited::VisitCallExpr(E);
3770
216
    }
3771
3772
41
    void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3773
41
      Expr *Callee = E->getCallee();
3774
41
3775
41
      if (isa<UnresolvedLookupExpr>(Callee))
3776
0
        return Inherited::VisitCXXOperatorCallExpr(E);
3777
41
3778
41
      Visit(Callee);
3779
41
      for (auto Arg : E->arguments())
3780
67
        HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3781
41
    }
3782
3783
1.86k
    void VisitBinaryOperator(BinaryOperator *E) {
3784
      // If a field assignment is detected, remove the field from the
3785
      // uninitiailized field set.
3786
1.86k
      if (E->getOpcode() == BO_Assign)
3787
16
        if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3788
15
          if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3789
15
            if (!FD->getType()->isReferenceType())
3790
14
              DeclsToRemove.push_back(FD);
3791
1.86k
3792
1.86k
      if (E->isCompoundAssignmentOp()) {
3793
3
        HandleValue(E->getLHS(), false /*AddressOf*/);
3794
3
        Visit(E->getRHS());
3795
3
        return;
3796
3
      }
3797
1.85k
3798
1.85k
      Inherited::VisitBinaryOperator(E);
3799
1.85k
    }
3800
3801
165
    void VisitUnaryOperator(UnaryOperator *E) {
3802
165
      if (E->isIncrementDecrementOp()) {
3803
36
        HandleValue(E->getSubExpr(), false /*AddressOf*/);
3804
36
        return;
3805
36
      }
3806
129
      if (E->getOpcode() == UO_AddrOf) {
3807
99
        if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3808
42
          HandleValue(ME->getBase(), true /*AddressOf*/);
3809
42
          return;
3810
42
        }
3811
87
      }
3812
87
3813
87
      Inherited::VisitUnaryOperator(E);
3814
87
    }
3815
  };
3816
3817
  // Diagnose value-uses of fields to initialize themselves, e.g.
3818
  //   foo(foo)
3819
  // where foo is not also a parameter to the constructor.
3820
  // Also diagnose across field uninitialized use such as
3821
  //   x(y), y(x)
3822
  // TODO: implement -Wuninitialized and fold this into that framework.
3823
  static void DiagnoseUninitializedFields(
3824
214k
      Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3825
214k
3826
214k
    if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3827
167k
                                           Constructor->getLocation())) {
3828
167k
      return;
3829
167k
    }
3830
47.3k
3831
47.3k
    if (Constructor->isInvalidDecl())
3832
81
      return;
3833
47.2k
3834
47.2k
    const CXXRecordDecl *RD = Constructor->getParent();
3835
47.2k
3836
47.2k
    if (RD->isDependentContext())
3837
4.41k
      return;
3838
42.8k
3839
    // Holds fields that are uninitialized.
3840
42.8k
    llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3841
42.8k
3842
    // At the beginning, all fields are uninitialized.
3843
279k
    for (auto *I : RD->decls()) {
3844
279k
      if (auto *FD = dyn_cast<FieldDecl>(I)) {
3845
39.0k
        UninitializedFields.insert(FD);
3846
240k
      } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3847
621
        UninitializedFields.insert(IFD->getAnonField());
3848
621
      }
3849
279k
    }
3850
42.8k
3851
42.8k
    llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3852
42.8k
    for (auto I : RD->bases())
3853
7.27k
      UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3854
42.8k
3855
42.8k
    if (UninitializedFields.empty() && 
UninitializedBaseClasses.empty()15.2k
)
3856
10.6k
      return;
3857
32.1k
3858
32.1k
    UninitializedFieldVisitor UninitializedChecker(SemaRef,
3859
32.1k
                                                   UninitializedFields,
3860
32.1k
                                                   UninitializedBaseClasses);
3861
32.1k
3862
30.5k
    for (const auto *FieldInit : Constructor->inits()) {
3863
30.5k
      if (UninitializedFields.empty() && 
UninitializedBaseClasses.empty()5.35k
)
3864
10
        break;
3865
30.4k
3866
30.4k
      Expr *InitExpr = FieldInit->getInit();
3867
30.4k
      if (!InitExpr)
3868
0
        continue;
3869
30.4k
3870
30.4k
      if (CXXDefaultInitExpr *Default =
3871
1.11k
              dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3872
1.11k
        InitExpr = Default->getExpr();
3873
1.11k
        if (!InitExpr)
3874
0
          continue;
3875
        // In class initializers will point to the constructor.
3876
1.11k
        UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3877
1.11k
                                              FieldInit->getAnyMember(),
3878
1.11k
                                              FieldInit->getBaseClass());
3879
29.3k
      } else {
3880
29.3k
        UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3881
29.3k
                                              FieldInit->getAnyMember(),
3882
29.3k
                                              FieldInit->getBaseClass());
3883
29.3k
      }
3884
30.4k
    }
3885
32.1k
  }
3886
} // namespace
3887
3888
/// Enter a new C++ default initializer scope. After calling this, the
3889
/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3890
/// parsing or instantiating the initializer failed.
3891
2.97k
void Sema::ActOnStartCXXInClassMemberInitializer() {
3892
  // Create a synthetic function scope to represent the call to the constructor
3893
  // that notionally surrounds a use of this initializer.
3894
2.97k
  PushFunctionScope();
3895
2.97k
}
3896
3897
122
void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3898
122
  if (!D.isFunctionDeclarator())
3899
4
    return;
3900
118
  auto &FTI = D.getFunctionTypeInfo();
3901
118
  if (!FTI.Params)
3902
62
    return;
3903
56
  for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3904
63
                                                          FTI.NumParams)) {
3905
63
    auto *ParamDecl = cast<NamedDecl>(Param.Param);
3906
63
    if (ParamDecl->getDeclName())
3907
35
      PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3908
63
  }
3909
56
}
3910
3911
122
ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3912
122
  if (ConstraintExpr.isInvalid())
3913
5
    return ExprError();
3914
117
  return CorrectDelayedTyposInExpr(ConstraintExpr);
3915
117
}
3916
3917
/// This is invoked after parsing an in-class initializer for a
3918
/// non-static C++ class member, and after instantiating an in-class initializer
3919
/// in a class template. Such actions are deferred until the class is complete.
3920
void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3921
                                                  SourceLocation InitLoc,
3922
2.97k
                                                  Expr *InitExpr) {
3923
  // Pop the notional constructor scope we created earlier.
3924
2.97k
  PopFunctionScopeInfo(nullptr, D);
3925
2.97k
3926
2.97k
  FieldDecl *FD = dyn_cast<FieldDecl>(D);
3927
2.97k
  assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3928
2.97k
         "must set init style when field is created");
3929
2.97k
3930
2.97k
  if (!InitExpr) {
3931
29
    D->setInvalidDecl();
3932
29
    if (FD)
3933
28
      FD->removeInClassInitializer();
3934
29
    return;
3935
29
  }
3936
2.94k
3937
2.94k
  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3938
1
    FD->setInvalidDecl();
3939
1
    FD->removeInClassInitializer();
3940
1
    return;
3941
1
  }
3942
2.94k
3943
2.94k
  ExprResult Init = InitExpr;
3944
2.94k
  if (!FD->getType()->isDependentType() && 
!InitExpr->isTypeDependent()2.81k
) {
3945
2.74k
    InitializedEntity Entity =
3946
2.74k
        InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3947
2.74k
    InitializationKind Kind =
3948
2.74k
        FD->getInClassInitStyle() == ICIS_ListInit
3949
83
            ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3950
83
                                                   InitExpr->getBeginLoc(),
3951
83
                                                   InitExpr->getEndLoc())
3952
2.66k
            : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3953
2.74k
    InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3954
2.74k
    Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3955
2.74k
    if (Init.isInvalid()) {
3956
34
      FD->setInvalidDecl();
3957
34
      return;
3958
34
    }
3959
2.91k
  }
3960
2.91k
3961
  // C++11 [class.base.init]p7:
3962
  //   The initialization of each base and member constitutes a
3963
  //   full-expression.
3964
2.91k
  Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3965
2.91k
  if (Init.isInvalid()) {
3966
0
    FD->setInvalidDecl();
3967
0
    return;
3968
0
  }
3969
2.91k
3970
2.91k
  InitExpr = Init.get();
3971
2.91k
3972
2.91k
  FD->setInClassInitializer(InitExpr);
3973
2.91k
}
3974
3975
/// Find the direct and/or virtual base specifiers that
3976
/// correspond to the given base type, for use in base initialization
3977
/// within a constructor.
3978
static bool FindBaseInitializer(Sema &SemaRef,
3979
                                CXXRecordDecl *ClassDecl,
3980
                                QualType BaseType,
3981
                                const CXXBaseSpecifier *&DirectBaseSpec,
3982
17.5k
                                const CXXBaseSpecifier *&VirtualBaseSpec) {
3983
  // First, check for a direct base class.
3984
17.5k
  DirectBaseSpec = nullptr;
3985
21.2k
  for (const auto &Base : ClassDecl->bases()) {
3986
21.2k
    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3987
      // We found a direct base of this type. That's what we're
3988
      // initializing.
3989
17.4k
      DirectBaseSpec = &Base;
3990
17.4k
      break;
3991
17.4k
    }
3992
21.2k
  }
3993
17.5k
3994
  // Check for a virtual base class.
3995
  // FIXME: We might be able to short-circuit this if we know in advance that
3996
  // there are no virtual bases.
3997
17.5k
  VirtualBaseSpec = nullptr;
3998
17.5k
  if (!DirectBaseSpec || 
!DirectBaseSpec->isVirtual()17.4k
) {
3999
    // We haven't found a base yet; search the class hierarchy for a
4000
    // virtual base class.
4001
17.4k
    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4002
17.4k
                       /*DetectVirtual=*/false);
4003
17.4k
    if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4004
17.4k
                              SemaRef.Context.getTypeDeclType(ClassDecl),
4005
17.4k
                              BaseType, Paths)) {
4006
17.4k
      for (CXXBasePaths::paths_iterator Path = Paths.begin();
4007
34.8k
           Path != Paths.end(); 
++Path17.3k
) {
4008
17.4k
        if (Path->back().Base->isVirtual()) {
4009
53
          VirtualBaseSpec = Path->back().Base;
4010
53
          break;
4011
53
        }
4012
17.4k
      }
4013
17.4k
    }
4014
17.4k
  }
4015
17.5k
4016
17.5k
  return DirectBaseSpec || 
VirtualBaseSpec85
;
4017
17.5k
}
4018
4019
/// Handle a C++ member initializer using braced-init-list syntax.
4020
MemInitResult
4021
Sema::ActOnMemInitializer(Decl *ConstructorD,
4022
                          Scope *S,
4023
                          CXXScopeSpec &SS,
4024
                          IdentifierInfo *MemberOrBase,
4025
                          ParsedType TemplateTypeTy,
4026
                          const DeclSpec &DS,
4027
                          SourceLocation IdLoc,
4028
                          Expr *InitList,
4029
369
                          SourceLocation EllipsisLoc) {
4030
369
  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4031
369
                             DS, IdLoc, InitList,
4032
369
                             EllipsisLoc);
4033
369
}
4034
4035
/// Handle a C++ member initializer using parentheses syntax.
4036
MemInitResult
4037
Sema::ActOnMemInitializer(Decl *ConstructorD,
4038
                          Scope *S,
4039
                          CXXScopeSpec &SS,
4040
                          IdentifierInfo *MemberOrBase,
4041
                          ParsedType TemplateTypeTy,
4042
                          const DeclSpec &DS,
4043
                          SourceLocation IdLoc,
4044
                          SourceLocation LParenLoc,
4045
                          ArrayRef<Expr *> Args,
4046
                          SourceLocation RParenLoc,
4047
192k
                          SourceLocation EllipsisLoc) {
4048
192k
  Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4049
192k
  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4050
192k
                             DS, IdLoc, List, EllipsisLoc);
4051
192k
}
4052
4053
namespace {
4054
4055
// Callback to only accept typo corrections that can be a valid C++ member
4056
// intializer: either a non-static field member or a base class.
4057
class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4058
public:
4059
  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4060
57
      : ClassDecl(ClassDecl) {}
4061
4062
12
  bool ValidateCandidate(const TypoCorrection &candidate) override {
4063
12
    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4064
8
      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4065
2
        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4066
6
      return isa<TypeDecl>(ND);
4067
6
    }
4068
4
    return false;
4069
4
  }
4070
4071
23
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
4072
23
    return std::make_unique<MemInitializerValidatorCCC>(*this);
4073
23
  }
4074
4075
private:
4076
  CXXRecordDecl *ClassDecl;
4077
};
4078
4079
}
4080
4081
ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4082
                                             CXXScopeSpec &SS,
4083
                                             ParsedType TemplateTypeTy,
4084
192k
                                             IdentifierInfo *MemberOrBase) {
4085
192k
  if (SS.getScopeRep() || 
TemplateTypeTy190k
)
4086
6.56k
    return nullptr;
4087
185k
  DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4088
185k
  if (Result.empty())
4089
10.3k
    return nullptr;
4090
175k
  ValueDecl *Member;
4091
175k
  if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4092
9.21k
      (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4093
166k
    return Member;
4094
8.99k
  return nullptr;
4095
8.99k
}
4096
4097
/// Handle a C++ member initializer.
4098
MemInitResult
4099
Sema::BuildMemInitializer(Decl *ConstructorD,
4100
                          Scope *S,
4101
                          CXXScopeSpec &SS,
4102
                          IdentifierInfo *MemberOrBase,
4103
                          ParsedType TemplateTypeTy,
4104
                          const DeclSpec &DS,
4105
                          SourceLocation IdLoc,
4106
                          Expr *Init,
4107
192k
                          SourceLocation EllipsisLoc) {
4108
192k
  ExprResult Res = CorrectDelayedTyposInExpr(Init);
4109
192k
  if (!Res.isUsable())
4110
0
    return true;
4111
192k
  Init = Res.get();
4112
192k
4113
192k
  if (!ConstructorD)
4114
0
    return true;
4115
192k
4116
192k
  AdjustDeclIfTemplate(ConstructorD);
4117
192k
4118
192k
  CXXConstructorDecl *Constructor
4119
192k
    = dyn_cast<CXXConstructorDecl>(ConstructorD);
4120
192k
  if (!Constructor) {
4121
    // The user wrote a constructor initializer on a function that is
4122
    // not a C++ constructor. Ignore the error for now, because we may
4123
    // have more member initializers coming; we'll diagnose it just
4124
    // once in ActOnMemInitializers.
4125
5
    return true;
4126
5
  }
4127
192k
4128
192k
  CXXRecordDecl *ClassDecl = Constructor->getParent();
4129
192k
4130
  // C++ [class.base.init]p2:
4131
  //   Names in a mem-initializer-id are looked up in the scope of the
4132
  //   constructor's class and, if not found in that scope, are looked
4133
  //   up in the scope containing the constructor's definition.
4134
  //   [Note: if the constructor's class contains a member with the
4135
  //   same name as a direct or virtual base class of the class, a
4136
  //   mem-initializer-id naming the member or base class and composed
4137
  //   of a single identifier refers to the class member. A
4138
  //   mem-initializer-id for the hidden base class may be specified
4139
  //   using a qualified name. ]
4140
192k
4141
  // Look for a member, first.
4142
192k
  if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4143
166k
          ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4144
166k
    if (EllipsisLoc.isValid())
4145
2
      Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4146
2
          << MemberOrBase
4147
2
          << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4148
166k
4149
166k
    return BuildMemberInitializer(Member, Init, IdLoc);
4150
166k
  }
4151
  // It didn't name a member, so see if it names a class.
4152
25.8k
  QualType BaseType;
4153
25.8k
  TypeSourceInfo *TInfo = nullptr;
4154
25.8k
4155
25.8k
  if (TemplateTypeTy) {
4156
4.86k
    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4157
4.86k
    if (BaseType.isNull())
4158
0
      return true;
4159
21.0k
  } else if (DS.getTypeSpecType() == TST_decltype) {
4160
4
    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4161
21.0k
  } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4162
2
    Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4163
2
    return true;
4164
21.0k
  } else {
4165
21.0k
    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4166
21.0k
    LookupParsedName(R, S, &SS);
4167
21.0k
4168
21.0k
    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4169
21.0k
    if (!TyD) {
4170
57
      if (R.isAmbiguous()) 
return true0
;
4171
57
4172
      // We don't want access-control diagnostics here.
4173
57
      R.suppressDiagnostics();
4174
57
4175
57
      if (SS.isSet() && 
isDependentScopeSpecifier(SS)30
) {
4176
24
        bool NotUnknownSpecialization = false;
4177
24
        DeclContext *DC = computeDeclContext(SS, false);
4178
24
        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4179
0
          NotUnknownSpecialization = !Record->hasAnyDependentBases();
4180
24
4181
24
        if (!NotUnknownSpecialization) {
4182
          // When the scope specifier can refer to a member of an unknown
4183
          // specialization, we take it as a type name.
4184
24
          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4185
24
                                       SS.getWithLocInContext(Context),
4186
24
                                       *MemberOrBase, IdLoc);
4187
24
          if (BaseType.isNull())
4188
0
            return true;
4189
24
4190
24
          TInfo = Context.CreateTypeSourceInfo(BaseType);
4191
24
          DependentNameTypeLoc TL =
4192
24
              TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4193
24
          if (!TL.isNull()) {
4194
24
            TL.setNameLoc(IdLoc);
4195
24
            TL.setElaboratedKeywordLoc(SourceLocation());
4196
24
            TL.setQualifierLoc(SS.getWithLocInContext(Context));
4197
24
          }
4198
24
4199
24
          R.clear();
4200
24
          R.setLookupName(MemberOrBase);
4201
24
        }
4202
24
      }
4203
57
4204
      // If no results were found, try to correct typos.
4205
57
      TypoCorrection Corr;
4206
57
      MemInitializerValidatorCCC CCC(ClassDecl);
4207
57
      if (R.empty() && 
BaseType.isNull()50
&&
4208
26
          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4209
6
                              CCC, CTK_ErrorRecovery, ClassDecl))) {
4210
6
        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4211
          // We have found a non-static data member with a similar
4212
          // name to what was typed; complain and initialize that
4213
          // member.
4214
2
          diagnoseTypo(Corr,
4215
2
                       PDiag(diag::err_mem_init_not_member_or_class_suggest)
4216
2
                         << MemberOrBase << true);
4217
2
          return BuildMemberInitializer(Member, Init, IdLoc);
4218
4
        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4219
4
          const CXXBaseSpecifier *DirectBaseSpec;
4220
4
          const CXXBaseSpecifier *VirtualBaseSpec;
4221
4
          if (FindBaseInitializer(*this, ClassDecl,
4222
4
                                  Context.getTypeDeclType(Type),
4223
4
                                  DirectBaseSpec, VirtualBaseSpec)) {
4224
            // We have found a direct or virtual base class with a
4225
            // similar name to what was typed; complain and initialize
4226
            // that base class.
4227
4
            diagnoseTypo(Corr,
4228
4
                         PDiag(diag::err_mem_init_not_member_or_class_suggest)
4229
4
                           << MemberOrBase << false,
4230
4
                         PDiag() /*Suppress note, we provide our own.*/);
4231
4
4232
4
            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4233
0
                                                              : VirtualBaseSpec;
4234
4
            Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4235
4
                << BaseSpec->getType() << BaseSpec->getSourceRange();
4236
4
4237
4
            TyD = Type;
4238
4
          }
4239
4
        }
4240
6
      }
4241
57
4242
55
      if (!TyD && 
BaseType.isNull()51
) {
4243
27
        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4244
27
          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4245
27
        return true;
4246
27
      }
4247
20.9k
    }
4248
20.9k
4249
20.9k
    if (BaseType.isNull()) {
4250
20.9k
      BaseType = Context.getTypeDeclType(TyD);
4251
20.9k
      MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4252
20.9k
      if (SS.isSet()) {
4253
1.67k
        BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4254
1.67k
                                             BaseType);
4255
1.67k
        TInfo = Context.CreateTypeSourceInfo(BaseType);
4256
1.67k
        ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4257
1.67k
        TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4258
1.67k
        TL.setElaboratedKeywordLoc(SourceLocation());
4259
1.67k
        TL.setQualifierLoc(SS.getWithLocInContext(Context));
4260
1.67k
      }
4261
20.9k
    }
4262
20.9k
  }
4263
25.8k
4264
25.8k
  if (!TInfo)
4265
19.2k
    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4266
25.8k
4267
25.8k
  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4268
25.8k
}
4269
4270
MemInitResult
4271
Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4272
191k
                             SourceLocation IdLoc) {
4273
191k
  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4274
191k
  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4275
191k
  assert((DirectMember || IndirectMember) &&
4276
191k
         "Member must be a FieldDecl or IndirectFieldDecl");
4277
191k
4278
191k
  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4279
1
    return true;
4280
191k
4281
191k
  if (Member->isInvalidDecl())
4282
1
    return true;
4283
191k
4284
191k
  MultiExprArg Args;
4285
191k
  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4286
190k
    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4287
1.26k
  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4288
375
    Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4289
890
  } else {
4290
    // Template instantiation doesn't reconstruct ParenListExprs for us.
4291
890
    Args = Init;
4292
890
  }
4293
191k
4294
191k
  SourceRange InitRange = Init->getSourceRange();
4295
191k
4296
191k
  if (Member->getType()->isDependentType() || 
Init->isTypeDependent()70.6k
) {
4297
    // Can't check initialization for a member of dependent type or when
4298
    // any of the arguments are type-dependent expressions.
4299
129k
    DiscardCleanupsInEvaluationContext();
4300
62.6k
  } else {
4301
62.6k
    bool InitList = false;
4302
62.6k
    if (isa<InitListExpr>(Init)) {
4303
151
      InitList = true;
4304
151
      Args = Init;
4305
151
    }
4306
62.6k
4307
    // Initialize the member.
4308
62.6k
    InitializedEntity MemberEntity =
4309
62.3k
      DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4310
228
                   : InitializedEntity::InitializeMember(IndirectMember,
4311
228
                                                         nullptr);
4312
62.6k
    InitializationKind Kind =
4313
151
        InitList ? InitializationKind::CreateDirectList(
4314
151
                       IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4315
62.4k
                 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4316
62.4k
                                                    InitRange.getEnd());
4317
62.6k
4318
62.6k
    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4319
62.6k
    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4320
62.6k
                                            nullptr);
4321
62.6k
    if (MemberInit.isInvalid())
4322
39
      return true;
4323
62.5k
4324
    // C++11 [class.base.init]p7:
4325
    //   The initialization of each base and member constitutes a
4326
    //   full-expression.
4327
62.5k
    MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4328
62.5k
                                     /*DiscardedValue*/ false);
4329
62.5k
    if (MemberInit.isInvalid())
4330
0
      return true;
4331
62.5k
4332
62.5k
    Init = MemberInit.get();
4333
62.5k
  }
4334
191k
4335
191k
  if (DirectMember) {
4336
191k
    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4337
191k
                                            InitRange.getBegin(), Init,
4338
191k
                                            InitRange.getEnd());
4339
244
  } else {
4340
244
    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4341
244
                                            InitRange.getBegin(), Init,
4342
244
                                            InitRange.getEnd());
4343
244
  }
4344
191k
}
4345
4346
MemInitResult
4347
Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4348
360
                                 CXXRecordDecl *ClassDecl) {
4349
360
  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4350
360
  if (!LangOpts.CPlusPlus11)
4351
1
    return Diag(NameLoc, diag::err_delegating_ctor)
4352
1
      << TInfo->getTypeLoc().getLocalSourceRange();
4353
359
  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4354
359
4355
359
  bool InitList = true;
4356
359
  MultiExprArg Args = Init;
4357
359
  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4358
359
    InitList = false;
4359
359
    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4360
359
  }
4361
359
4362
359
  SourceRange InitRange = Init->getSourceRange();
4363
  // Initialize the object.
4364
359
  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4365
359
                                     QualType(ClassDecl->getTypeForDecl(), 0));
4366
359
  InitializationKind Kind =
4367
0
      InitList ? InitializationKind::CreateDirectList(
4368
0
                     NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4369
359
               : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4370
359
                                                  InitRange.getEnd());
4371
359
  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4372
359
  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4373
359
                                              Args, nullptr);
4374
359
  if (DelegationInit.isInvalid())
4375
1
    return true;
4376
358
4377
358
  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4378
358
         "Delegating constructor with no target?");
4379
358
4380
  // C++11 [class.base.init]p7:
4381
  //   The initialization of each base and member constitutes a
4382
  //   full-expression.
4383
358
  DelegationInit = ActOnFinishFullExpr(
4384
358
      DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4385
358
  if (DelegationInit.isInvalid())
4386
0
    return true;
4387
358
4388
  // If we are in a dependent context, template instantiation will
4389
  // perform this type-checking again. Just save the arguments that we
4390
  // received in a ParenListExpr.
4391
  // FIXME: This isn't quite ideal, since our ASTs don't capture all
4392
  // of the information that we have about the base
4393
  // initializer. However, deconstructing the ASTs is a dicey process,
4394
  // and this approach is far more likely to get the corner cases right.
4395
358
  if (CurContext->isDependentContext())
4396
2
    DelegationInit = Init;
4397
358
4398
358
  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4399
358
                                          DelegationInit.getAs<Expr>(),
4400
358
                                          InitRange.getEnd());
4401
358
}
4402
4403
MemInitResult
4404
Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4405
                           Expr *Init, CXXRecordDecl *ClassDecl,
4406
34.0k
                           SourceLocation EllipsisLoc) {
4407
34.0k
  SourceLocation BaseLoc
4408
34.0k
    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4409
34.0k
4410
34.0k
  if (!BaseType->isDependentType() && 
!BaseType->isRecordType()17.9k
)
4411
4
    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4412
4
             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4413
34.0k
4414
  // C++ [class.base.init]p2:
4415
  //   [...] Unless the mem-initializer-id names a nonstatic data
4416
  //   member of the constructor's class or a direct or virtual base
4417
  //   of that class, the mem-initializer is ill-formed. A
4418
  //   mem-initializer-list can initialize a base class using any
4419
  //   name that denotes that base class type.
4420
34.0k
  bool Dependent = BaseType->isDependentType() || 
Init->isTypeDependent()17.9k
;
4421
34.0k
4422
34.0k
  SourceRange InitRange = Init->getSourceRange();
4423
34.0k
  if (EllipsisLoc.isValid()) {
4424
    // This is a pack expansion.
4425
2.36k
    if (!BaseType->containsUnexpandedParameterPack())  {
4426
0
      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4427
0
        << SourceRange(BaseLoc, InitRange.getEnd());
4428
0
4429
0
      EllipsisLoc = SourceLocation();
4430
0
    }
4431
31.6k
  } else {
4432
    // Check for any unexpanded parameter packs.
4433
31.6k
    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4434
1
      return true;
4435
31.6k
4436
31.6k
    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4437
0
      return true;
4438
34.0k
  }
4439
34.0k
4440
  // Check for direct and virtual base classes.
4441
34.0k
  const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4442
34.0k
  const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4443
34.0k
  if (!Dependent) {
4444
17.8k
    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4445
17.8k
                                       BaseType))
4446
358
      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4447
17.5k
4448
17.5k
    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4449
17.5k
                        VirtualBaseSpec);
4450
17.5k
4451
    // C++ [base.class.init]p2:
4452
    // Unless the mem-initializer-id names a nonstatic data member of the
4453
    // constructor's class or a direct or virtual base of that class, the
4454
    // mem-initializer is ill-formed.
4455
17.5k
    if (!DirectBaseSpec && 
!VirtualBaseSpec85
) {
4456
      // If the class has any dependent bases, then it's possible that
4457
      // one of those types will resolve to the same type as
4458
      // BaseType. Therefore, just treat this as a dependent base
4459
      // class initialization.  FIXME: Should we try to check the
4460
      // initialization anyway? It seems odd.
4461
35
      if (ClassDecl->hasAnyDependentBases())
4462
20
        Dependent = true;
4463
15
      else
4464
15
        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4465
15
          << BaseType << Context.getTypeDeclType(ClassDecl)
4466
15
          << BaseTInfo->getTypeLoc().getLocalSourceRange();
4467
33.6k
    }
4468
17.5k
  }
4469
33.6k
4470
33.6k
  if (Dependent) {
4471
16.1k
    DiscardCleanupsInEvaluationContext();
4472
16.1k
4473
16.1k
    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4474
16.1k
                                            /*IsVirtual=*/false,
4475
16.1k
                                            InitRange.getBegin(), Init,
4476
16.1k
                                            InitRange.getEnd(), EllipsisLoc);
4477
16.1k
  }
4478
17.5k
4479
  // C++ [base.class.init]p2:
4480
  //   If a mem-initializer-id is ambiguous because it designates both
4481
  //   a direct non-virtual base class and an inherited virtual base
4482
  //   class, the mem-initializer is ill-formed.
4483
17.5k
  if (DirectBaseSpec && 
VirtualBaseSpec17.4k
)
4484
3
    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4485
3
      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4486
17.5k
4487
17.5k
  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4488
17.5k
  if (!BaseSpec)
4489
50
    BaseSpec = VirtualBaseSpec;
4490
17.5k
4491
  // Initialize the base.
4492
17.5k
  bool InitList = true;
4493
17.5k
  MultiExprArg Args = Init;
4494
17.5k
  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4495
17.4k
    InitList = false;
4496
17.4k
    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4497
17.4k
  }
4498
17.5k
4499
17.5k
  InitializedEntity BaseEntity =
4500
17.5k
    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4501
17.5k
  InitializationKind Kind =
4502
25
      InitList ? InitializationKind::CreateDirectList(BaseLoc)
4503
17.4k
               : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4504
17.4k
                                                  InitRange.getEnd());
4505
17.5k
  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4506
17.5k
  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4507
17.5k
  if (BaseInit.isInvalid())
4508
17
    return true;
4509
17.4k
4510
  // C++11 [class.base.init]p7:
4511
  //   The initialization of each base and member constitutes a
4512
  //   full-expression.
4513
17.4k
  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4514
17.4k
                                 /*DiscardedValue*/ false);
4515
17.4k
  if (BaseInit.isInvalid())
4516
0
    return true;
4517
17.4k
4518
  // If we are in a dependent context, template instantiation will
4519
  // perform this type-checking again. Just save the arguments that we
4520
  // received in a ParenListExpr.
4521
  // FIXME: This isn't quite ideal, since our ASTs don't capture all
4522
  // of the information that we have about the base
4523
  // initializer. However, deconstructing the ASTs is a dicey process,
4524
  // and this approach is far more likely to get the corner cases right.
4525
17.4k
  if (CurContext->isDependentContext())
4526
1.20k
    BaseInit = Init;
4527
17.4k
4528
17.4k
  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4529
17.4k
                                          BaseSpec->isVirtual(),
4530
17.4k
                                          InitRange.getBegin(),
4531
17.4k
                                          BaseInit.getAs<Expr>(),
4532
17.4k
                                          InitRange.getEnd(), EllipsisLoc);
4533
17.4k
}
4534
4535
// Create a static_cast\<T&&>(expr).
4536
21.6k
static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4537
21.6k
  if (T.isNull()) T = E->getType();
4538
21.6k
  QualType TargetType = SemaRef.BuildReferenceType(
4539
21.6k
      T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4540
21.6k
  SourceLocation ExprLoc = E->getBeginLoc();
4541
21.6k
  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4542
21.6k
      TargetType, ExprLoc);
4543
21.6k
4544
21.6k
  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4545
21.6k
                                   SourceRange(ExprLoc, ExprLoc),
4546
21.6k
                                   E->getSourceRange()).get();
4547
21.6k
}
4548
4549
/// ImplicitInitializerKind - How an implicit base or member initializer should
4550
/// initialize its base or member.
4551
enum ImplicitInitializerKind {
4552
  IIK_Default,
4553
  IIK_Copy,
4554
  IIK_Move,
4555
  IIK_Inherit
4556
};
4557
4558
static bool
4559
BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4560
                             ImplicitInitializerKind ImplicitInitKind,
4561
                             CXXBaseSpecifier *BaseSpec,
4562
                             bool IsInheritedVirtualBase,
4563
18.8k
                             CXXCtorInitializer *&CXXBaseInit) {
4564
18.8k
  InitializedEntity InitEntity
4565
18.8k
    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4566
18.8k
                                        IsInheritedVirtualBase);
4567
18.8k
4568
18.8k
  ExprResult BaseInit;
4569
18.8k
4570
18.8k
  switch (ImplicitInitKind) {
4571
12.3k
  case IIK_Inherit:
4572
12.3k
  case IIK_Default: {
4573
12.3k
    InitializationKind InitKind
4574
12.3k
      = InitializationKind::CreateDefault(Constructor->getLocation());
4575
12.3k
    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4576
12.3k
    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4577
12.3k
    break;
4578
12.3k
  }
4579
12.3k
4580
6.47k
  case IIK_Move:
4581
6.47k
  case IIK_Copy: {
4582
6.47k
    bool Moving = ImplicitInitKind == IIK_Move;
4583
6.47k
    ParmVarDecl *Param = Constructor->getParamDecl(0);
4584
6.47k
    QualType ParamType = Param->getType().getNonReferenceType();
4585
6.47k
4586
6.47k
    Expr *CopyCtorArg =
4587
6.47k
      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4588
6.47k
                          SourceLocation(), Param, false,
4589
6.47k
                          Constructor->getLocation(), ParamType,
4590
6.47k
                          VK_LValue, nullptr);
4591
6.47k
4592
6.47k
    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4593
6.47k
4594
    // Cast to the base class to avoid ambiguities.
4595
6.47k
    QualType ArgTy =
4596
6.47k
      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4597
6.47k
                                       ParamType.getQualifiers());
4598
6.47k
4599
6.47k
    if (Moving) {
4600
2.41k
      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4601
2.41k
    }
4602
6.47k
4603
6.47k
    CXXCastPath BasePath;
4604
6.47k
    BasePath.push_back(BaseSpec);
4605
6.47k
    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4606
6.47k
                                            CK_UncheckedDerivedToBase,
4607
4.06k
                                            Moving ? 
VK_XValue2.41k
: VK_LValue,
4608
6.47k
                                            &BasePath).get();
4609
6.47k
4610
6.47k
    InitializationKind InitKind
4611
6.47k
      = InitializationKind::CreateDirect(Constructor->getLocation(),
4612
6.47k
                                         SourceLocation(), SourceLocation());
4613
6.47k
    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4614
6.47k
    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4615
6.47k
    break;
4616
18.8k
  }
4617
18.8k
  }
4618
18.8k
4619
18.8k
  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4620
18.8k
  if (BaseInit.isInvalid())
4621
21
    return true;
4622
18.8k
4623
18.8k
  CXXBaseInit =
4624
18.8k
    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4625
18.8k
               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4626
18.8k
                                                        SourceLocation()),
4627
18.8k
                                             BaseSpec->isVirtual(),
4628
18.8k
                                             SourceLocation(),
4629
18.8k
                                             BaseInit.getAs<Expr>(),
4630
18.8k
                                             SourceLocation(),
4631
18.8k
                                             SourceLocation());
4632
18.8k
4633
18.8k
  return false;
4634
18.8k
}
4635
4636
27.6k
static bool RefersToRValueRef(Expr *MemRef) {
4637
27.6k
  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4638
27.6k
  return Referenced->getType()->isRValueReferenceType();
4639
27.6k
}
4640
4641
static bool
4642
BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4643
                               ImplicitInitializerKind ImplicitInitKind,
4644
                               FieldDecl *Field, IndirectFieldDecl *Indirect,
4645
52.9k
                               CXXCtorInitializer *&CXXMemberInit) {
4646
52.9k
  if (Field->isInvalidDecl())
4647
0
    return true;
4648
52.9k
4649
52.9k
  SourceLocation Loc = Constructor->getLocation();
4650
52.9k
4651
52.9k
  if (ImplicitInitKind == IIK_Copy || 
ImplicitInitKind == IIK_Move42.8k
) {
4652
27.6k
    bool Moving = ImplicitInitKind == IIK_Move;
4653
27.6k
    ParmVarDecl *Param = Constructor->getParamDecl(0);
4654
27.6k
    QualType ParamType = Param->getType().getNonReferenceType();
4655
27.6k
4656
    // Suppress copying zero-width bitfields.
4657
27.6k
    if (Field->isZeroLengthBitField(SemaRef.Context))
4658
0
      return false;
4659
27.6k
4660
27.6k
    Expr *MemberExprBase =
4661
27.6k
      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4662
27.6k
                          SourceLocation(), Param, false,
4663
27.6k
                          Loc, ParamType, VK_LValue, nullptr);
4664
27.6k
4665
27.6k
    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4666
27.6k
4667
27.6k
    if (Moving) {
4668
17.4k
      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4669
17.4k
    }
4670
27.6k
4671
    // Build a reference to this field within the parameter.
4672
27.6k
    CXXScopeSpec SS;
4673
27.6k
    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4674
27.6k
                              Sema::LookupMemberName);
4675
0
    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4676
27.6k
                                  : cast<ValueDecl>(Field), AS_public);
4677
27.6k
    MemberLookup.resolveKind();
4678
27.6k
    ExprResult CtorArg
4679
27.6k
      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4680
27.6k
                                         ParamType, Loc,
4681
27.6k
                                         /*IsArrow=*/false,
4682
27.6k
                                         SS,
4683
27.6k
                                         /*TemplateKWLoc=*/SourceLocation(),
4684
27.6k
                                         /*FirstQualifierInScope=*/nullptr,
4685
27.6k
                                         MemberLookup,
4686
27.6k
                                         /*TemplateArgs=*/nullptr,
4687
27.6k
                                         /*S*/nullptr);
4688
27.6k
    if (CtorArg.isInvalid())
4689
0
      return true;
4690
27.6k
4691
    // C++11 [class.copy]p15:
4692
    //   - if a member m has rvalue reference type T&&, it is direct-initialized
4693
    //     with static_cast<T&&>(x.m);
4694
27.6k
    if (RefersToRValueRef(CtorArg.get())) {
4695
155
      CtorArg = CastForMoving(SemaRef, CtorArg.get());
4696
155
    }
4697
27.6k
4698
27.6k
    InitializedEntity Entity =
4699
0
        Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4700
0
                                                       /*Implicit*/ true)
4701
27.6k
                 : InitializedEntity::InitializeMember(Field, nullptr,
4702
27.6k
                                                       /*Implicit*/ true);
4703
27.6k
4704
    // Direct-initialize to use the copy constructor.
4705
27.6k
    InitializationKind InitKind =
4706
27.6k
      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4707
27.6k
4708
27.6k
    Expr *CtorArgE = CtorArg.getAs<Expr>();
4709
27.6k
    InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4710
27.6k
    ExprResult MemberInit =
4711
27.6k
        InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4712
27.6k
    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4713
27.6k
    if (MemberInit.isInvalid())
4714
0
      return true;
4715
27.6k
4716
27.6k
    if (Indirect)
4717
0
      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4718
0
          SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4719
27.6k
    else
4720
27.6k
      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4721
27.6k
          SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4722
27.6k
    return false;
4723
27.6k
  }
4724
25.3k
4725
25.3k
  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4726
25.3k
         "Unhandled implicit init kind!");
4727
25.3k
4728
25.3k
  QualType FieldBaseElementType =
4729
25.3k
    SemaRef.Context.getBaseElementType(Field->getType());
4730
25.3k
4731
25.3k
  if (FieldBaseElementType->isRecordType()) {
4732
3.30k
    InitializedEntity InitEntity =
4733
6
        Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4734
6
                                                       /*Implicit*/ true)
4735
3.29k
                 : InitializedEntity::InitializeMember(Field, nullptr,
4736
3.29k
                                                       /*Implicit*/ true);
4737
3.30k
    InitializationKind InitKind =
4738
3.30k
      InitializationKind::CreateDefault(Loc);
4739
3.30k
4740
3.30k
    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4741
3.30k
    ExprResult MemberInit =
4742
3.30k
      InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4743
3.30k
4744
3.30k
    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4745
3.30k
    if (MemberInit.isInvalid())
4746
13
      return true;
4747
3.28k
4748
3.28k
    if (Indirect)
4749
6
      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4750
6
                                                               Indirect, Loc,
4751
6
                                                               Loc,
4752
6
                                                               MemberInit.get(),
4753
6
                                                               Loc);
4754
3.28k
    else
4755
3.28k
      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4756
3.28k
                                                               Field, Loc, Loc,
4757
3.28k
                                                               MemberInit.get(),
4758
3.28k
                                                               Loc);
4759
3.28k
    return false;
4760
3.28k
  }
4761
22.0k
4762
22.0k
  if (!Field->getParent()->isUnion()) {
4763
22.0k
    if (FieldBaseElementType->isReferenceType()) {
4764
9
      SemaRef.Diag(Constructor->getLocation(),
4765
9
                   diag::err_uninitialized_member_in_ctor)
4766
9
      << (int)Constructor->isImplicit()
4767
9
      << SemaRef.Context.getTagDeclType(Constructor->getParent())
4768
9
      << 0 << Field->getDeclName();
4769
9
      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4770
9
      return true;
4771
9
    }
4772
22.0k
4773
22.0k
    if (FieldBaseElementType.isConstQualified()) {
4774
3
      SemaRef.Diag(Constructor->getLocation(),
4775
3
                   diag::err_uninitialized_member_in_ctor)
4776
3
      << (int)Constructor->isImplicit()
4777
3
      << SemaRef.Context.getTagDeclType(Constructor->getParent())
4778
3
      << 1 << Field->getDeclName();
4779
3
      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4780
3
      return true;
4781
3
    }
4782
22.0k
  }
4783
22.0k
4784
22.0k
  if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4785
    // ARC and Weak:
4786
    //   Default-initialize Objective-C pointers to NULL.
4787
27
    CXXMemberInit
4788
27
      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4789
27
                                                 Loc, Loc,
4790
27
                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4791
27
                                                 Loc);
4792
27
    return false;
4793
27
  }
4794
22.0k
4795
  // Nothing to initialize.
4796
22.0k
  CXXMemberInit = nullptr;
4797
22.0k
  return false;
4798
22.0k
}
4799
4800
namespace {
4801
struct BaseAndFieldInfo {
4802
  Sema &S;
4803
  CXXConstructorDecl *Ctor;
4804
  bool AnyErrorsInInits;
4805
  ImplicitInitializerKind IIK;
4806
  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4807
  SmallVector<CXXCtorInitializer*, 8> AllToInit;
4808
  llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4809
4810
  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4811
128k
    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4812
128k
    bool Generated = Ctor->isImplicit() || 
Ctor->isDefaulted()75.7k
;
4813
128k
    if (Ctor->getInheritedConstructor())
4814
294
      IIK = IIK_Inherit;
4815
128k
    else if (Generated && 
Ctor->isCopyConstructor()60.7k
)
4816
12.7k
      IIK = IIK_Copy;
4817
115k
    else if (Generated && 
Ctor->isMoveConstructor()47.9k
)
4818
22.5k
      IIK = IIK_Move;
4819
92.9k
    else
4820
92.9k
      IIK = IIK_Default;
4821
128k
  }
4822
4823
1.75M
  bool isImplicitCopyOrMove() const {
4824
1.75M
    switch (IIK) {
4825
412k
    case IIK_Copy:
4826
412k
    case IIK_Move:
4827
412k
      return true;
4828
412k
4829
1.34M
    case IIK_Default:
4830
1.34M
    case IIK_Inherit:
4831
1.34M
      return false;
4832
0
    }
4833
0
4834
0
    llvm_unreachable("Invalid ImplicitInitializerKind!");
4835
0
  }
4836
4837
85.8k
  bool addFieldInitializer(CXXCtorInitializer *Init) {
4838
85.8k
    AllToInit.push_back(Init);
4839
85.8k
4840
    // Check whether this initializer makes the field "used".
4841
85.8k
    if (Init->getInit()->HasSideEffects(S.Context))
4842
17.4k
      S.UnusedPrivateFields.remove(Init->getAnyMember());
4843
85.8k
4844
85.8k
    return false;
4845
85.8k
  }
4846
4847
63.6k
  bool isInactiveUnionMember(FieldDecl *Field) {
4848
63.6k
    RecordDecl *Record = Field->getParent();
4849
63.6k
    if (!Record->isUnion())
4850
55.7k
      return false;
4851
7.90k
4852
7.90k
    if (FieldDecl *Active =
4853
229
            ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4854
229
      return Active != Field->getCanonicalDecl();
4855
7.67k
4856
    // In an implicit copy or move constructor, ignore any in-class initializer.
4857
7.67k
    if (isImplicitCopyOrMove())
4858
1.18k
      return true;
4859
6.48k
4860
    // If there's no explicit initialization, the field is active only if it
4861
    // has an in-class initializer...
4862
6.48k
    if (Field->hasInClassInitializer())
4863
73
      return false;
4864
    // ... or it's an anonymous struct or union whose class has an in-class
4865
    // initializer.
4866
6.41k
    if (!Field->isAnonymousStructOrUnion())
4867
6.35k
      return true;
4868
55
    CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4869
55
    return !FieldRD->hasInClassInitializer();
4870
55
  }
4871
4872
  /// Determine whether the given field is, or is within, a union member
4873
  /// that is inactive (because there was an initializer given for a different
4874
  /// member of the union, or because the union was not initialized at all).
4875
  bool isWithinInactiveUnionMember(FieldDecl *Field,
4876
62.4k
                                   IndirectFieldDecl *Indirect) {
4877
62.4k
    if (!Indirect)
4878
61.2k
      return isInactiveUnionMember(Field);
4879
1.15k
4880
2.37k
    
for (auto *C : Indirect->chain())1.15k
{
4881
2.37k
      FieldDecl *Field = dyn_cast<FieldDecl>(C);
4882
2.37k
      if (Field && isInactiveUnionMember(Field))
4883
1.04k
        return true;
4884
2.37k
    }
4885
110
    return false;
4886
1.15k
  }
4887
};
4888
}
4889
4890
/// Determine whether the given type is an incomplete or zero-lenfgth
4891
/// array type.
4892
157k
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4893
157k
  if (T->isIncompleteArrayType())
4894
27
    return true;
4895
156k
4896
167k
  
while (const ConstantArrayType *156k
ArrayT = Context.getAsConstantArrayType(T)) {
4897
10.1k
    if (!ArrayT->getSize())
4898
43
      return true;
4899
10.1k
4900
10.1k
    T = ArrayT->getElementType();
4901
10.1k
  }
4902
156k
4903
156k
  return false;
4904
156k
}
4905
4906
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4907
                                    FieldDecl *Field,
4908
115k
                                    IndirectFieldDecl *Indirect = nullptr) {
4909
115k
  if (Field->isInvalidDecl())
4910
87
    return false;
4911
115k
4912
  // Overwhelmingly common case: we have a direct initializer for this field.
4913
115k
  if (CXXCtorInitializer *Init =
4914
53.3k
          Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4915
53.3k
    return Info.addFieldInitializer(Init);
4916
62.4k
4917
  // C++11 [class.base.init]p8:
4918
  //   if the entity is a non-static data member that has a
4919
  //   brace-or-equal-initializer and either
4920
  //   -- the constructor's class is a union and no other variant member of that
4921
  //      union is designated by a mem-initializer-id or
4922
  //   -- the constructor's class is not a union, and, if the entity is a member
4923
  //      of an anonymous union, no other member of that union is designated by
4924
  //      a mem-initializer-id,
4925
  //   the entity is initialized as specified in [dcl.init].
4926
  //
4927
  // We also apply the same rules to handle anonymous structs within anonymous
4928
  // unions.
4929
62.4k
  if (Info.isWithinInactiveUnionMember(Field, Indirect))
4930
7.81k
    return false;
4931
54.6k
4932
54.6k
  if (Field->hasInClassInitializer() && 
!Info.isImplicitCopyOrMove()1.70k
) {
4933
1.53k
    ExprResult DIE =
4934
1.53k
        SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4935
1.53k
    if (DIE.isInvalid())
4936
2
      return true;
4937
1.53k
4938
1.53k
    auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4939
1.53k
    SemaRef.checkInitializerLifetime(Entity, DIE.get());
4940
1.53k
4941
1.53k
    CXXCtorInitializer *Init;
4942
1.53k
    if (Indirect)
4943
53
      Init = new (SemaRef.Context)
4944
53
          CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4945
53
                             SourceLocation(), DIE.get(), SourceLocation());
4946
1.48k
    else
4947
1.48k
      Init = new (SemaRef.Context)
4948
1.48k
          CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4949
1.48k
                             SourceLocation(), DIE.get(), SourceLocation());
4950
1.53k
    return Info.addFieldInitializer(Init);
4951
1.53k
  }
4952
53.0k
4953
  // Don't initialize incomplete or zero-length arrays.
4954
53.0k
  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4955
42
    return false;
4956
53.0k
4957
  // Don't try to build an implicit initializer if there were semantic
4958
  // errors in any of the initializers (and therefore we might be
4959
  // missing some that the user actually wrote).
4960
53.0k
  if (Info.AnyErrorsInInits)
4961
58
    return false;
4962
52.9k
4963
52.9k
  CXXCtorInitializer *Init = nullptr;
4964
52.9k
  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4965
52.9k
                                     Indirect, Init))
4966
25
    return true;
4967
52.9k
4968
52.9k
  if (!Init)
4969
22.0k
    return false;
4970
30.9k
4971
30.9k
  return Info.addFieldInitializer(Init);
4972
30.9k
}
4973
4974
bool
4975
Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4976
358
                               CXXCtorInitializer *Initializer) {
4977
358
  assert(Initializer->isDelegatingInitializer());
4978
358
  Constructor->setNumCtorInitializers(1);
4979
358
  CXXCtorInitializer **initializer =
4980
358
    new (Context) CXXCtorInitializer*[1];
4981
358
  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4982
358
  Constructor->setCtorInitializers(initializer);
4983
358
4984
358
  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4985
358
    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4986
358
    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4987
358
  }
4988
358
4989
358
  DelegatingCtorDecls.push_back(Constructor);
4990
358
4991
358
  DiagnoseUninitializedFields(*this, Constructor);
4992
358
4993
358
  return false;
4994
358
}
4995
4996
bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4997
249k
                               ArrayRef<CXXCtorInitializer *> Initializers) {
4998
249k
  if (Constructor->isDependentContext()) {
4999
    // Just store the initializers as written, they will be checked during
5000
    // instantiation.
5001
120k
    if (!Initializers.empty()) {
5002
110k
      Constructor->setNumCtorInitializers(Initializers.size());
5003
110k
      CXXCtorInitializer **baseOrMemberInitializers =
5004
110k
        new (Context) CXXCtorInitializer*[Initializers.size()];
5005
110k
      memcpy(baseOrMemberInitializers, Initializers.data(),
5006
110k
             Initializers.size() * sizeof(CXXCtorInitializer*));
5007
110k
      Constructor->setCtorInitializers(baseOrMemberInitializers);
5008
110k
    }
5009
120k
5010
    // Let template instantiation know whether we had errors.
5011
120k
    if (AnyErrors)
5012
20
      Constructor->setInvalidDecl();
5013
120k
5014
120k
    return false;
5015
120k
  }
5016
128k
5017
128k
  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5018
128k
5019
  // We need to build the initializer AST according to order of construction
5020
  // and not what user specified in the Initializers list.
5021
128k
  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5022
128k
  if (!ClassDecl)
5023
0
    return true;
5024
128k
5025
128k
  bool HadError = false;
5026
128k
5027
198k
  for (unsigned i = 0; i < Initializers.size(); 
i++69.9k
) {
5028
69.9k
    CXXCtorInitializer *Member = Initializers[i];
5029
69.9k
5030
69.9k
    if (Member->isBaseInitializer())
5031
16.5k
      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5032
53.3k
    else {
5033
53.3k
      Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5034
53.3k
5035
53.3k
      if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5036
455
        for (auto *C : F->chain()) {
5037
455
          FieldDecl *FD = dyn_cast<FieldDecl>(C);
5038
455
          if (FD && FD->getParent()->isUnion())
5039
135
            Info.ActiveUnionMember.insert(std::make_pair(
5040
135
                FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5041
455
        }
5042
53.1k
      } else if (FieldDecl *FD = Member->getMember()) {
5043
53.1k
        if (FD->getParent()->isUnion())
5044
63
          Info.ActiveUnionMember.insert(std::make_pair(
5045
63
              FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5046
53.1k
      }
5047
53.3k
    }
5048
69.9k
  }
5049
128k
5050
  // Keep track of the direct virtual bases.
5051
128k
  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5052
34.8k
  for (auto &I : ClassDecl->bases()) {
5053
34.8k
    if (I.isVirtual())
5054
1.34k
      DirectVBases.insert(&I);
5055
34.8k
  }
5056
128k
5057
  // Push virtual bases before others.
5058
2.04k
  for (auto &VBase : ClassDecl->vbases()) {
5059
2.04k
    if (CXXCtorInitializer *Value
5060
174
        = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5061
      // [class.base.init]p7, per DR257:
5062
      //   A mem-initializer where the mem-initializer-id names a virtual base
5063
      //   class is ignored during execution of a constructor of any class that
5064
      //   is not the most derived class.
5065
174
      if (ClassDecl->isAbstract()) {
5066
        // FIXME: Provide a fixit to remove the base specifier. This requires
5067
        // tracking the location of the associated comma for a base specifier.
5068
2
        Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5069
2
          << VBase.getType() << ClassDecl;
5070
2
        DiagnoseAbstractType(ClassDecl);
5071
2
      }
5072
174
5073
174
      Info.AllToInit.push_back(Value);
5074
1.87k
    } else if (!AnyErrors && 
!ClassDecl->isAbstract()1.87k
) {
5075
      // [class.base.init]p8, per DR257:
5076
      //   If a given [...] base class is not named by a mem-initializer-id
5077
      //   [...] and the entity is not a virtual base class of an abstract
5078
      //   class, then [...] the entity is default-initialized.
5079
1.81k
      bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5080
1.81k
      CXXCtorInitializer *CXXBaseInit;
5081
1.81k
      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5082
1.81k
                                       &VBase, IsInheritedVirtualBase,
5083
13
                                       CXXBaseInit)) {
5084
13
        HadError = true;
5085
13
        continue;
5086
13
      }
5087
1.80k
5088
1.80k
      Info.AllToInit.push_back(CXXBaseInit);
5089
1.80k
    }
5090
2.04k
  }
5091
128k
5092
  // Non-virtual bases.
5093
34.8k
  for (auto &Base : ClassDecl->bases()) {
5094
    // Virtuals are in the virtual base list and already constructed.
5095
34.8k
    if (Base.isVirtual())
5096
1.34k
      continue;
5097
33.4k
5098
33.4k
    if (CXXCtorInitializer *Value
5099
16.4k
          = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5100
16.4k
      Info.AllToInit.push_back(Value);
5101
17.0k
    } else if (!AnyErrors) {
5102
17.0k
      CXXCtorInitializer *CXXBaseInit;
5103
17.0k
      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5104
17.0k
                                       &Base, /*IsInheritedVirtualBase=*/false,
5105
8
                                       CXXBaseInit)) {
5106
8
        HadError = true;
5107
8
        continue;
5108
8
      }
5109
17.0k
5110
17.0k
      Info.AllToInit.push_back(CXXBaseInit);
5111
17.0k
    }
5112
33.4k
  }
5113
128k
5114
  // Fields.
5115
1.86M
  for (auto *Mem : ClassDecl->decls()) {
5116
1.86M
    if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5117
      // C++ [class.bit]p2:
5118
      //   A declaration for a bit-field that omits the identifier declares an
5119
      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5120
      //   initialized.
5121
115k
      if (F->isUnnamedBitfield())
5122
59
        continue;
5123
115k
5124
      // If we're not generating the implicit copy/move constructor, then we'll
5125
      // handle anonymous struct/union fields based on their individual
5126
      // indirect fields.
5127
115k
      if (F->isAnonymousStructOrUnion() && 
!Info.isImplicitCopyOrMove()893
)
5128
558
        continue;
5129
114k
5130
114k
      if (CollectFieldInitializer(*this, Info, F))
5131
27
        HadError = true;
5132
114k
      continue;
5133
114k
    }
5134
1.74M
5135
    // Beyond this point, we only consider default initialization.
5136
1.74M
    if (Info.isImplicitCopyOrMove())
5137
410k
      continue;
5138
1.33M
5139
1.33M
    if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5140
1.34k
      if (F->getType()->isIncompleteArrayType()) {
5141
1
        assert(ClassDecl->hasFlexibleArrayMember() &&
5142
1
               "Incomplete array type is not valid");
5143
1
        continue;
5144
1
      }
5145
1.34k
5146
      // Initialize each field of an anonymous struct individually.
5147
1.34k
      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5148
0
        HadError = true;
5149
1.34k