Coverage Report

Created: 2022-05-14 11:35

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