Coverage Report

Created: 2019-07-24 05:18

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