Coverage Report

Created: 2020-02-15 09:57

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