Coverage Report

Created: 2020-11-24 06:42

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