Coverage Report

Created: 2021-06-15 06:44

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